diff --git a/.licenses/npm/@actions/artifact.dep.yml b/.licenses/npm/@actions/artifact.dep.yml index deff8acd..3fa7b651 100644 --- a/.licenses/npm/@actions/artifact.dep.yml +++ b/.licenses/npm/@actions/artifact.dep.yml @@ -1,30 +1,20 @@ --- name: "@actions/artifact" -version: 1.1.1 +version: 1.1.2 type: npm -summary: -homepage: +summary: Actions artifact lib +homepage: https://github.com/actions/toolkit/tree/main/packages/artifact license: mit licenses: -- sources: Auto-generated MIT license text - text: | - MIT License +- sources: LICENSE.md + text: |- + The MIT License (MIT) - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: + Copyright 2019 GitHub - The above copyright notice and this permission notice shall be included in all - copies or substantial portions of the Software. + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. notices: [] diff --git a/.licenses/npm/@actions/http-client.dep.yml b/.licenses/npm/@actions/http-client.dep.yml index 43316cbc..5c60ad35 100644 --- a/.licenses/npm/@actions/http-client.dep.yml +++ b/.licenses/npm/@actions/http-client.dep.yml @@ -1,9 +1,9 @@ --- name: "@actions/http-client" -version: 1.0.11 +version: 2.0.1 type: npm summary: Actions Http Client -homepage: https://github.com/actions/http-client#readme +homepage: https://github.com/actions/toolkit/tree/main/packages/http-client license: mit licenses: - sources: LICENSE diff --git a/.licenses/npm/@types/tmp.dep.yml b/.licenses/npm/@types/tmp.dep.yml deleted file mode 100644 index b8c91802..00000000 --- a/.licenses/npm/@types/tmp.dep.yml +++ /dev/null @@ -1,26 +0,0 @@ ---- -name: "@types/tmp" -version: 0.1.0 -type: npm -summary: TypeScript definitions for tmp -homepage: https://github.com/DefinitelyTyped/DefinitelyTyped#readme -license: mit -licenses: -- sources: LICENSE - text: " MIT License\r\n\r\n Copyright (c) Microsoft Corporation. All rights - reserved.\r\n\r\n Permission is hereby granted, free of charge, to any person - obtaining a copy\r\n of this software and associated documentation files (the - \"Software\"), to deal\r\n in the Software without restriction, including without - limitation the rights\r\n to use, copy, modify, merge, publish, distribute, - sublicense, and/or sell\r\n copies of the Software, and to permit persons to - whom the Software is\r\n furnished to do so, subject to the following conditions:\r\n\r\n - \ The above copyright notice and this permission notice shall be included in - all\r\n copies or substantial portions of the Software.\r\n\r\n THE SOFTWARE - IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n IMPLIED, - INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n FITNESS - FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n AUTHORS - OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n LIABILITY, - WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n OUT - OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n - \ SOFTWARE\r\n" -notices: [] diff --git a/.licenses/npm/glob.dep.yml b/.licenses/npm/glob.dep.yml index 39297a12..d22b145a 100644 --- a/.licenses/npm/glob.dep.yml +++ b/.licenses/npm/glob.dep.yml @@ -1,9 +1,9 @@ --- name: glob -version: 7.1.6 +version: 7.2.3 type: npm summary: a little globber -homepage: https://github.com/isaacs/node-glob#readme +homepage: license: isc licenses: - sources: LICENSE diff --git a/.licenses/npm/minimatch.dep.yml b/.licenses/npm/minimatch.dep.yml index 317e4bc8..a4ff623f 100644 --- a/.licenses/npm/minimatch.dep.yml +++ b/.licenses/npm/minimatch.dep.yml @@ -1,9 +1,9 @@ --- name: minimatch -version: 3.0.4 +version: 3.1.2 type: npm summary: a glob matcher in javascript -homepage: https://github.com/isaacs/minimatch#readme +homepage: license: isc licenses: - sources: LICENSE diff --git a/.licenses/npm/rimraf.dep.yml b/.licenses/npm/rimraf.dep.yml index 9349c1b3..a30c9dc4 100644 --- a/.licenses/npm/rimraf.dep.yml +++ b/.licenses/npm/rimraf.dep.yml @@ -1,9 +1,9 @@ --- name: rimraf -version: 2.6.3 +version: 3.0.2 type: npm summary: A deep deletion module for node (like `rm -rf`) -homepage: https://github.com/isaacs/rimraf#readme +homepage: license: isc licenses: - sources: LICENSE diff --git a/.licenses/npm/tmp-promise.dep.yml b/.licenses/npm/tmp-promise.dep.yml index 29d43613..a46e266b 100644 --- a/.licenses/npm/tmp-promise.dep.yml +++ b/.licenses/npm/tmp-promise.dep.yml @@ -1,9 +1,9 @@ --- name: tmp-promise -version: 2.1.1 +version: 3.0.3 type: npm summary: The tmp package with promises support and disposers. -homepage: https://github.com/benjamingr/tmp-promise#readme +homepage: license: mit licenses: - sources: Auto-generated MIT license text diff --git a/.licenses/npm/tmp.dep.yml b/.licenses/npm/tmp.dep.yml index cba10b33..da478bf7 100644 --- a/.licenses/npm/tmp.dep.yml +++ b/.licenses/npm/tmp.dep.yml @@ -1,6 +1,6 @@ --- name: tmp -version: 0.1.0 +version: 0.2.1 type: npm summary: Temporary file and directory creator homepage: http://github.com/raszi/node-tmp diff --git a/.licenses/npm/uuid.dep.yml b/.licenses/npm/uuid.dep.yml new file mode 100644 index 00000000..6a0f9809 --- /dev/null +++ b/.licenses/npm/uuid.dep.yml @@ -0,0 +1,20 @@ +--- +name: uuid +version: 8.3.2 +type: npm +summary: RFC4122 (v1, v4, and v5) UUIDs +homepage: +license: mit +licenses: +- sources: LICENSE.md + text: | + The MIT License (MIT) + + Copyright (c) 2010-2020 Robert Kieffer and other contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +notices: [] diff --git a/dist/index.js b/dist/index.js index ea665833..b8e7cc6f 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,3928 +1,2145 @@ /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ -/***/ 56966: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 79450: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const client_1 = __nccwpck_require__(46190); +__exportStar(__nccwpck_require__(15769), exports); +__exportStar(__nccwpck_require__(38182), exports); +__exportStar(__nccwpck_require__(46190), exports); +const client = new client_1.DefaultArtifactClient(); +exports["default"] = client; +//# sourceMappingURL=artifact.js.map -var iconvLite = __nccwpck_require__(85848); - -// Expose to the world -module.exports.O = convert; +/***/ }), -/** - * Convert encoding of an UTF-8 string or a buffer - * - * @param {String|Buffer} str String to be converted - * @param {String} to Encoding to be converted to - * @param {String} [from='UTF-8'] Encoding to be converted from - * @return {Buffer} Encoded string - */ -function convert(str, to, from) { - from = checkEncoding(from || 'UTF-8'); - to = checkEncoding(to || 'UTF-8'); - str = str || ''; +/***/ 54622: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var result; +"use strict"; - if (from !== 'UTF-8' && typeof str === 'string') { - str = Buffer.from(str, 'binary'); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Timestamp = void 0; +const runtime_1 = __nccwpck_require__(4061); +const runtime_2 = __nccwpck_require__(4061); +const runtime_3 = __nccwpck_require__(4061); +const runtime_4 = __nccwpck_require__(4061); +const runtime_5 = __nccwpck_require__(4061); +const runtime_6 = __nccwpck_require__(4061); +const runtime_7 = __nccwpck_require__(4061); +// @generated message type with reflection information, may provide speed optimized methods +class Timestamp$Type extends runtime_7.MessageType { + constructor() { + super("google.protobuf.Timestamp", [ + { no: 1, name: "seconds", kind: "scalar", T: 3 /*ScalarType.INT64*/ }, + { no: 2, name: "nanos", kind: "scalar", T: 5 /*ScalarType.INT32*/ } + ]); } - - if (from === to) { - if (typeof str === 'string') { - result = Buffer.from(str); - } else { - result = str; - } - } else { - try { - result = convertIconvLite(str, to, from); - } catch (E) { - console.error(E); - result = str; + /** + * Creates a new `Timestamp` for the current time. + */ + now() { + const msg = this.create(); + const ms = Date.now(); + msg.seconds = runtime_6.PbLong.from(Math.floor(ms / 1000)).toString(); + msg.nanos = (ms % 1000) * 1000000; + return msg; + } + /** + * Converts a `Timestamp` to a JavaScript Date. + */ + toDate(message) { + return new Date(runtime_6.PbLong.from(message.seconds).toNumber() * 1000 + Math.ceil(message.nanos / 1000000)); + } + /** + * Converts a JavaScript Date to a `Timestamp`. + */ + fromDate(date) { + const msg = this.create(); + const ms = date.getTime(); + msg.seconds = runtime_6.PbLong.from(Math.floor(ms / 1000)).toString(); + msg.nanos = (ms % 1000) * 1000000; + return msg; + } + /** + * In JSON format, the `Timestamp` type is encoded as a string + * in the RFC 3339 format. + */ + internalJsonWrite(message, options) { + let ms = runtime_6.PbLong.from(message.seconds).toNumber() * 1000; + if (ms < Date.parse("0001-01-01T00:00:00Z") || ms > Date.parse("9999-12-31T23:59:59Z")) + throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive."); + if (message.nanos < 0) + throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative."); + let z = "Z"; + if (message.nanos > 0) { + let nanosStr = (message.nanos + 1000000000).toString().substring(1); + if (nanosStr.substring(3) === "000000") + z = "." + nanosStr.substring(0, 3) + "Z"; + else if (nanosStr.substring(6) === "000") + z = "." + nanosStr.substring(0, 6) + "Z"; + else + z = "." + nanosStr + "Z"; } + return new Date(ms).toISOString().replace(".000Z", z); } - - if (typeof result === 'string') { - result = Buffer.from(result, 'utf-8'); + /** + * In JSON format, the `Timestamp` type is encoded as a string + * in the RFC 3339 format. + */ + internalJsonRead(json, options, target) { + if (typeof json !== "string") + throw new Error("Unable to parse Timestamp from JSON " + (0, runtime_5.typeofJsonValue)(json) + "."); + let matches = json.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/); + if (!matches) + throw new Error("Unable to parse Timestamp from JSON. Invalid format."); + let ms = Date.parse(matches[1] + "-" + matches[2] + "-" + matches[3] + "T" + matches[4] + ":" + matches[5] + ":" + matches[6] + (matches[8] ? matches[8] : "Z")); + if (Number.isNaN(ms)) + throw new Error("Unable to parse Timestamp from JSON. Invalid value."); + if (ms < Date.parse("0001-01-01T00:00:00Z") || ms > Date.parse("9999-12-31T23:59:59Z")) + throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive."); + if (!target) + target = this.create(); + target.seconds = runtime_6.PbLong.from(ms / 1000).toString(); + target.nanos = 0; + if (matches[7]) + target.nanos = (parseInt("1" + matches[7] + "0".repeat(9 - matches[7].length)) - 1000000000); + return target; } - - return result; -} - -/** - * Convert encoding of astring with iconv-lite - * - * @param {String|Buffer} str String to be converted - * @param {String} to Encoding to be converted to - * @param {String} [from='UTF-8'] Encoding to be converted from - * @return {Buffer} Encoded string - */ -function convertIconvLite(str, to, from) { - if (to === 'UTF-8') { - return iconvLite.decode(str, from); - } else if (from === 'UTF-8') { - return iconvLite.encode(str, to); - } else { - return iconvLite.encode(iconvLite.decode(str, from), to); + create(value) { + const message = { seconds: "0", nanos: 0 }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== undefined) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* int64 seconds */ 1: + message.seconds = reader.int64().toString(); + break; + case /* int32 nanos */ 2: + message.nanos = reader.int32(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + /* int64 seconds = 1; */ + if (message.seconds !== "0") + writer.tag(1, runtime_1.WireType.Varint).int64(message.seconds); + /* int32 nanos = 2; */ + if (message.nanos !== 0) + writer.tag(2, runtime_1.WireType.Varint).int32(message.nanos); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } } - /** - * Converts charset name if needed - * - * @param {String} name Character set - * @return {String} Character set name + * @generated MessageType for protobuf message google.protobuf.Timestamp */ -function checkEncoding(name) { - return (name || '') - .toString() - .trim() - .replace(/^latin[\-_]?(\d+)$/i, 'ISO-8859-$1') - .replace(/^win(?:dows)?[\-_]?(\d+)$/i, 'WINDOWS-$1') - .replace(/^utf[\-_]?(\d+)$/i, 'UTF-$1') - .replace(/^ks_c_5601\-1987$/i, 'CP949') - .replace(/^us[\-_]?ascii$/i, 'ASCII') - .toUpperCase(); -} - +exports.Timestamp = new Timestamp$Type(); +//# sourceMappingURL=timestamp.js.map /***/ }), -/***/ 77668: +/***/ 8626: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -var Buffer = (__nccwpck_require__(97084).Buffer); - -// Multibyte codec. In this scheme, a character is represented by 1 or more bytes. -// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. -// To save memory and loading time, we read table files only when requested. - -exports._dbcs = DBCSCodec; - -var UNASSIGNED = -1, - GB18030_CODE = -2, - SEQ_START = -10, - NODE_START = -1000, - UNASSIGNED_NODE = new Array(0x100), - DEF_CHAR = -1; - -for (var i = 0; i < 0x100; i++) - UNASSIGNED_NODE[i] = UNASSIGNED; - - -// Class DBCSCodec reads and initializes mapping tables. -function DBCSCodec(codecOptions, iconv) { - this.encodingName = codecOptions.encodingName; - if (!codecOptions) - throw new Error("DBCS codec is called without the data.") - if (!codecOptions.table) - throw new Error("Encoding '" + this.encodingName + "' has no data."); - - // Load tables. - var mappingTable = codecOptions.table(); - - - // Decode tables: MBCS -> Unicode. - - // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. - // Trie root is decodeTables[0]. - // Values: >= 0 -> unicode character code. can be > 0xFFFF - // == UNASSIGNED -> unknown/unassigned sequence. - // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. - // <= NODE_START -> index of the next node in our trie to process next byte. - // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. - this.decodeTables = []; - this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node. - - // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. - this.decodeTableSeq = []; - - // Actual mapping tables consist of chunks. Use them to fill up decode tables. - for (var i = 0; i < mappingTable.length; i++) - this._addDecodeChunk(mappingTable[i]); - - // Load & create GB18030 tables when needed. - if (typeof codecOptions.gb18030 === 'function') { - this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. - - // Add GB18030 common decode nodes. - var commonThirdByteNodeIdx = this.decodeTables.length; - this.decodeTables.push(UNASSIGNED_NODE.slice(0)); - - var commonFourthByteNodeIdx = this.decodeTables.length; - this.decodeTables.push(UNASSIGNED_NODE.slice(0)); - - // Fill out the tree - var firstByteNode = this.decodeTables[0]; - for (var i = 0x81; i <= 0xFE; i++) { - var secondByteNode = this.decodeTables[NODE_START - firstByteNode[i]]; - for (var j = 0x30; j <= 0x39; j++) { - if (secondByteNode[j] === UNASSIGNED) { - secondByteNode[j] = NODE_START - commonThirdByteNodeIdx; - } else if (secondByteNode[j] > NODE_START) { - throw new Error("gb18030 decode tables conflict at byte 2"); - } - - var thirdByteNode = this.decodeTables[NODE_START - secondByteNode[j]]; - for (var k = 0x81; k <= 0xFE; k++) { - if (thirdByteNode[k] === UNASSIGNED) { - thirdByteNode[k] = NODE_START - commonFourthByteNodeIdx; - } else if (thirdByteNode[k] === NODE_START - commonFourthByteNodeIdx) { - continue; - } else if (thirdByteNode[k] > NODE_START) { - throw new Error("gb18030 decode tables conflict at byte 3"); - } - - var fourthByteNode = this.decodeTables[NODE_START - thirdByteNode[k]]; - for (var l = 0x30; l <= 0x39; l++) { - if (fourthByteNode[l] === UNASSIGNED) - fourthByteNode[l] = GB18030_CODE; - } - } - } - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BytesValue = exports.StringValue = exports.BoolValue = exports.UInt32Value = exports.Int32Value = exports.UInt64Value = exports.Int64Value = exports.FloatValue = exports.DoubleValue = void 0; +// @generated by protobuf-ts 2.9.1 with parameter long_type_string,client_none,generate_dependencies +// @generated from protobuf file "google/protobuf/wrappers.proto" (package "google.protobuf", syntax proto3) +// tslint:disable +// +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// +// Wrappers for primitive (non-message) types. These types are useful +// for embedding primitives in the `google.protobuf.Any` type and for places +// where we need to distinguish between the absence of a primitive +// typed field and its default value. +// +const runtime_1 = __nccwpck_require__(4061); +const runtime_2 = __nccwpck_require__(4061); +const runtime_3 = __nccwpck_require__(4061); +const runtime_4 = __nccwpck_require__(4061); +const runtime_5 = __nccwpck_require__(4061); +const runtime_6 = __nccwpck_require__(4061); +const runtime_7 = __nccwpck_require__(4061); +// @generated message type with reflection information, may provide speed optimized methods +class DoubleValue$Type extends runtime_7.MessageType { + constructor() { + super("google.protobuf.DoubleValue", [ + { no: 1, name: "value", kind: "scalar", T: 1 /*ScalarType.DOUBLE*/ } + ]); } - - this.defaultCharUnicode = iconv.defaultCharUnicode; - - - // Encode tables: Unicode -> DBCS. - - // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. - // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. - // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). - // == UNASSIGNED -> no conversion found. Output a default char. - // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. - this.encodeTable = []; - - // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of - // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key - // means end of sequence (needed when one sequence is a strict subsequence of another). - // Objects are kept separately from encodeTable to increase performance. - this.encodeTableSeq = []; - - // Some chars can be decoded, but need not be encoded. - var skipEncodeChars = {}; - if (codecOptions.encodeSkipVals) - for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) { - var val = codecOptions.encodeSkipVals[i]; - if (typeof val === 'number') - skipEncodeChars[val] = true; - else - for (var j = val.from; j <= val.to; j++) - skipEncodeChars[j] = true; - } - - // Use decode trie to recursively fill out encode tables. - this._fillEncodeTable(0, 0, skipEncodeChars); - - // Add more encoding pairs when needed. - if (codecOptions.encodeAdd) { - for (var uChar in codecOptions.encodeAdd) - if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) - this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); + /** + * Encode `DoubleValue` to JSON number. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.scalar(2, message.value, "value", false, true); } - - this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; - if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?']; - if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); -} - -DBCSCodec.prototype.encoder = DBCSEncoder; -DBCSCodec.prototype.decoder = DBCSDecoder; - -// Decoder helpers -DBCSCodec.prototype._getDecodeTrieNode = function(addr) { - var bytes = []; - for (; addr > 0; addr >>>= 8) - bytes.push(addr & 0xFF); - if (bytes.length == 0) - bytes.push(0); - - var node = this.decodeTables[0]; - for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie. - var val = node[bytes[i]]; - - if (val == UNASSIGNED) { // Create new node. - node[bytes[i]] = NODE_START - this.decodeTables.length; - this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); - } - else if (val <= NODE_START) { // Existing node. - node = this.decodeTables[NODE_START - val]; - } - else - throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); + /** + * Decode `DoubleValue` from JSON number. + */ + internalJsonRead(json, options, target) { + if (!target) + target = this.create(); + target.value = this.refJsonReader.scalar(json, 1, undefined, "value"); + return target; } - return node; -} - - -DBCSCodec.prototype._addDecodeChunk = function(chunk) { - // First element of chunk is the hex mbcs code where we start. - var curAddr = parseInt(chunk[0], 16); - - // Choose the decoding node where we'll write our chars. - var writeTable = this._getDecodeTrieNode(curAddr); - curAddr = curAddr & 0xFF; - - // Write all other elements of the chunk to the table. - for (var k = 1; k < chunk.length; k++) { - var part = chunk[k]; - if (typeof part === "string") { // String, write as-is. - for (var l = 0; l < part.length;) { - var code = part.charCodeAt(l++); - if (0xD800 <= code && code < 0xDC00) { // Decode surrogate - var codeTrail = part.charCodeAt(l++); - if (0xDC00 <= codeTrail && codeTrail < 0xE000) - writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00); - else - throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); - } - else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used) - var len = 0xFFF - code + 2; - var seq = []; - for (var m = 0; m < len; m++) - seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq. - - writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; - this.decodeTableSeq.push(seq); - } - else - writeTable[curAddr++] = code; // Basic char + create(value) { + const message = { value: 0 }; + globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== undefined) + (0, runtime_5.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* double value */ 1: + message.value = reader.double(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } - } - else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character. - var charCode = writeTable[curAddr - 1] + 1; - for (var l = 0; l < part; l++) - writeTable[curAddr++] = charCode++; } - else - throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); + return message; + } + internalBinaryWrite(message, writer, options) { + /* double value = 1; */ + if (message.value !== 0) + writer.tag(1, runtime_3.WireType.Bit64).double(message.value); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } - if (curAddr > 0xFF) - throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); -} - -// Encoder helpers -DBCSCodec.prototype._getEncodeBucket = function(uCode) { - var high = uCode >> 8; // This could be > 0xFF because of astral characters. - if (this.encodeTable[high] === undefined) - this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand. - return this.encodeTable[high]; -} - -DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { - var bucket = this._getEncodeBucket(uCode); - var low = uCode & 0xFF; - if (bucket[low] <= SEQ_START) - this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it. - else if (bucket[low] == UNASSIGNED) - bucket[low] = dbcsCode; } - -DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { - - // Get the root of character tree according to first character of the sequence. - var uCode = seq[0]; - var bucket = this._getEncodeBucket(uCode); - var low = uCode & 0xFF; - - var node; - if (bucket[low] <= SEQ_START) { - // There's already a sequence with - use it. - node = this.encodeTableSeq[SEQ_START-bucket[low]]; +/** + * @generated MessageType for protobuf message google.protobuf.DoubleValue + */ +exports.DoubleValue = new DoubleValue$Type(); +// @generated message type with reflection information, may provide speed optimized methods +class FloatValue$Type extends runtime_7.MessageType { + constructor() { + super("google.protobuf.FloatValue", [ + { no: 1, name: "value", kind: "scalar", T: 2 /*ScalarType.FLOAT*/ } + ]); } - else { - // There was no sequence object - allocate a new one. - node = {}; - if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence. - bucket[low] = SEQ_START - this.encodeTableSeq.length; - this.encodeTableSeq.push(node); - } - - // Traverse the character tree, allocating new nodes as needed. - for (var j = 1; j < seq.length-1; j++) { - var oldVal = node[uCode]; - if (typeof oldVal === 'object') - node = oldVal; - else { - node = node[uCode] = {} - if (oldVal !== undefined) - node[DEF_CHAR] = oldVal - } + /** + * Encode `FloatValue` to JSON number. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.scalar(1, message.value, "value", false, true); } - - // Set the leaf to given dbcsCode. - uCode = seq[seq.length-1]; - node[uCode] = dbcsCode; -} - -DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { - var node = this.decodeTables[nodeIdx]; - var hasValues = false; - var subNodeEmpty = {}; - for (var i = 0; i < 0x100; i++) { - var uCode = node[i]; - var mbCode = prefix + i; - if (skipEncodeChars[mbCode]) - continue; - - if (uCode >= 0) { - this._setEncodeChar(uCode, mbCode); - hasValues = true; - } else if (uCode <= NODE_START) { - var subNodeIdx = NODE_START - uCode; - if (!subNodeEmpty[subNodeIdx]) { // Skip empty subtrees (they are too large in gb18030). - var newPrefix = (mbCode << 8) >>> 0; // NOTE: '>>> 0' keeps 32-bit num positive. - if (this._fillEncodeTable(subNodeIdx, newPrefix, skipEncodeChars)) - hasValues = true; - else - subNodeEmpty[subNodeIdx] = true; - } - } else if (uCode <= SEQ_START) { - this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); - hasValues = true; - } + /** + * Decode `FloatValue` from JSON number. + */ + internalJsonRead(json, options, target) { + if (!target) + target = this.create(); + target.value = this.refJsonReader.scalar(json, 1, undefined, "value"); + return target; } - return hasValues; -} - - - -// == Encoder ================================================================== - -function DBCSEncoder(options, codec) { - // Encoder state - this.leadSurrogate = -1; - this.seqObj = undefined; - - // Static data - this.encodeTable = codec.encodeTable; - this.encodeTableSeq = codec.encodeTableSeq; - this.defaultCharSingleByte = codec.defCharSB; - this.gb18030 = codec.gb18030; -} - -DBCSEncoder.prototype.write = function(str) { - var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)), - leadSurrogate = this.leadSurrogate, - seqObj = this.seqObj, nextChar = -1, - i = 0, j = 0; - - while (true) { - // 0. Get next character. - if (nextChar === -1) { - if (i == str.length) break; - var uCode = str.charCodeAt(i++); - } - else { - var uCode = nextChar; - nextChar = -1; - } - - // 1. Handle surrogates. - if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates. - if (uCode < 0xDC00) { // We've got lead surrogate. - if (leadSurrogate === -1) { - leadSurrogate = uCode; - continue; - } else { - leadSurrogate = uCode; - // Double lead surrogate found. - uCode = UNASSIGNED; - } - } else { // We've got trail surrogate. - if (leadSurrogate !== -1) { - uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00); - leadSurrogate = -1; - } else { - // Incomplete surrogate pair - only trail surrogate found. - uCode = UNASSIGNED; - } - - } - } - else if (leadSurrogate !== -1) { - // Incomplete surrogate pair - only lead surrogate found. - nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. - leadSurrogate = -1; - } - - // 2. Convert uCode character. - var dbcsCode = UNASSIGNED; - if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence - var resCode = seqObj[uCode]; - if (typeof resCode === 'object') { // Sequence continues. - seqObj = resCode; - continue; - - } else if (typeof resCode == 'number') { // Sequence finished. Write it. - dbcsCode = resCode; - - } else if (resCode == undefined) { // Current character is not part of the sequence. - - // Try default character for this sequence - resCode = seqObj[DEF_CHAR]; - if (resCode !== undefined) { - dbcsCode = resCode; // Found. Write it. - nextChar = uCode; // Current character will be written too in the next iteration. - - } else { - // TODO: What if we have no default? (resCode == undefined) - // Then, we should write first char of the sequence as-is and try the rest recursively. - // Didn't do it for now because no encoding has this situation yet. - // Currently, just skip the sequence and write current char. - } - } - seqObj = undefined; - } - else if (uCode >= 0) { // Regular character - var subtable = this.encodeTable[uCode >> 8]; - if (subtable !== undefined) - dbcsCode = subtable[uCode & 0xFF]; - - if (dbcsCode <= SEQ_START) { // Sequence start - seqObj = this.encodeTableSeq[SEQ_START-dbcsCode]; - continue; - } - - if (dbcsCode == UNASSIGNED && this.gb18030) { - // Use GB18030 algorithm to find character(s) to write. - var idx = findIdx(this.gb18030.uChars, uCode); - if (idx != -1) { - var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); - newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600; - newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260; - newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10; - newBuf[j++] = 0x30 + dbcsCode; - continue; - } - } - } - - // 3. Write dbcsCode character. - if (dbcsCode === UNASSIGNED) - dbcsCode = this.defaultCharSingleByte; - - if (dbcsCode < 0x100) { - newBuf[j++] = dbcsCode; - } - else if (dbcsCode < 0x10000) { - newBuf[j++] = dbcsCode >> 8; // high byte - newBuf[j++] = dbcsCode & 0xFF; // low byte - } - else if (dbcsCode < 0x1000000) { - newBuf[j++] = dbcsCode >> 16; - newBuf[j++] = (dbcsCode >> 8) & 0xFF; - newBuf[j++] = dbcsCode & 0xFF; - } else { - newBuf[j++] = dbcsCode >>> 24; - newBuf[j++] = (dbcsCode >>> 16) & 0xFF; - newBuf[j++] = (dbcsCode >>> 8) & 0xFF; - newBuf[j++] = dbcsCode & 0xFF; - } + create(value) { + const message = { value: 0 }; + globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== undefined) + (0, runtime_5.reflectionMergePartial)(this, message, value); + return message; } - - this.seqObj = seqObj; - this.leadSurrogate = leadSurrogate; - return newBuf.slice(0, j); -} - -DBCSEncoder.prototype.end = function() { - if (this.leadSurrogate === -1 && this.seqObj === undefined) - return; // All clean. Most often case. - - var newBuf = Buffer.alloc(10), j = 0; - - if (this.seqObj) { // We're in the sequence. - var dbcsCode = this.seqObj[DEF_CHAR]; - if (dbcsCode !== undefined) { // Write beginning of the sequence. - if (dbcsCode < 0x100) { - newBuf[j++] = dbcsCode; - } - else { - newBuf[j++] = dbcsCode >> 8; // high byte - newBuf[j++] = dbcsCode & 0xFF; // low byte + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* float value */ 1: + message.value = reader.float(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } - } else { - // See todo above. } - this.seqObj = undefined; + return message; } - - if (this.leadSurrogate !== -1) { - // Incomplete surrogate pair - only lead surrogate found. - newBuf[j++] = this.defaultCharSingleByte; - this.leadSurrogate = -1; + internalBinaryWrite(message, writer, options) { + /* float value = 1; */ + if (message.value !== 0) + writer.tag(1, runtime_3.WireType.Bit32).float(message.value); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } - - return newBuf.slice(0, j); -} - -// Export for testing -DBCSEncoder.prototype.findIdx = findIdx; - - -// == Decoder ================================================================== - -function DBCSDecoder(options, codec) { - // Decoder state - this.nodeIdx = 0; - this.prevBytes = []; - - // Static data - this.decodeTables = codec.decodeTables; - this.decodeTableSeq = codec.decodeTableSeq; - this.defaultCharUnicode = codec.defaultCharUnicode; - this.gb18030 = codec.gb18030; } - -DBCSDecoder.prototype.write = function(buf) { - var newBuf = Buffer.alloc(buf.length*2), - nodeIdx = this.nodeIdx, - prevBytes = this.prevBytes, prevOffset = this.prevBytes.length, - seqStart = -this.prevBytes.length, // idx of the start of current parsed sequence. - uCode; - - for (var i = 0, j = 0; i < buf.length; i++) { - var curByte = (i >= 0) ? buf[i] : prevBytes[i + prevOffset]; - - // Lookup in current trie node. - var uCode = this.decodeTables[nodeIdx][curByte]; - - if (uCode >= 0) { - // Normal character, just use it. - } - else if (uCode === UNASSIGNED) { // Unknown char. - // TODO: Callback with seq. - uCode = this.defaultCharUnicode.charCodeAt(0); - i = seqStart; // Skip one byte ('i' will be incremented by the for loop) and try to parse again. - } - else if (uCode === GB18030_CODE) { - if (i >= 3) { - var ptr = (buf[i-3]-0x81)*12600 + (buf[i-2]-0x30)*1260 + (buf[i-1]-0x81)*10 + (curByte-0x30); - } else { - var ptr = (prevBytes[i-3+prevOffset]-0x81)*12600 + - (((i-2 >= 0) ? buf[i-2] : prevBytes[i-2+prevOffset])-0x30)*1260 + - (((i-1 >= 0) ? buf[i-1] : prevBytes[i-1+prevOffset])-0x81)*10 + - (curByte-0x30); - } - var idx = findIdx(this.gb18030.gbChars, ptr); - uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; - } - else if (uCode <= NODE_START) { // Go to next trie node. - nodeIdx = NODE_START - uCode; - continue; - } - else if (uCode <= SEQ_START) { // Output a sequence of chars. - var seq = this.decodeTableSeq[SEQ_START - uCode]; - for (var k = 0; k < seq.length - 1; k++) { - uCode = seq[k]; - newBuf[j++] = uCode & 0xFF; - newBuf[j++] = uCode >> 8; - } - uCode = seq[seq.length-1]; - } - else - throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); - - // Write the character to buffer, handling higher planes using surrogate pair. - if (uCode >= 0x10000) { - uCode -= 0x10000; - var uCodeLead = 0xD800 | (uCode >> 10); - newBuf[j++] = uCodeLead & 0xFF; - newBuf[j++] = uCodeLead >> 8; - - uCode = 0xDC00 | (uCode & 0x3FF); - } - newBuf[j++] = uCode & 0xFF; - newBuf[j++] = uCode >> 8; - - // Reset trie node. - nodeIdx = 0; seqStart = i+1; +/** + * @generated MessageType for protobuf message google.protobuf.FloatValue + */ +exports.FloatValue = new FloatValue$Type(); +// @generated message type with reflection information, may provide speed optimized methods +class Int64Value$Type extends runtime_7.MessageType { + constructor() { + super("google.protobuf.Int64Value", [ + { no: 1, name: "value", kind: "scalar", T: 3 /*ScalarType.INT64*/ } + ]); } - - this.nodeIdx = nodeIdx; - this.prevBytes = (seqStart >= 0) - ? Array.prototype.slice.call(buf, seqStart) - : prevBytes.slice(seqStart + prevOffset).concat(Array.prototype.slice.call(buf)); - - return newBuf.slice(0, j).toString('ucs2'); -} - -DBCSDecoder.prototype.end = function() { - var ret = ''; - - // Try to parse all remaining chars. - while (this.prevBytes.length > 0) { - // Skip 1 character in the buffer. - ret += this.defaultCharUnicode; - var bytesArr = this.prevBytes.slice(1); - - // Parse remaining as usual. - this.prevBytes = []; - this.nodeIdx = 0; - if (bytesArr.length > 0) - ret += this.write(bytesArr); + /** + * Encode `Int64Value` to JSON string. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.scalar(runtime_1.ScalarType.INT64, message.value, "value", false, true); } - - this.prevBytes = []; - this.nodeIdx = 0; - return ret; -} - -// Binary search for GB18030. Returns largest i such that table[i] <= val. -function findIdx(table, val) { - if (table[0] > val) - return -1; - - var l = 0, r = table.length; - while (l < r-1) { // always table[l] <= val < table[r] - var mid = l + ((r-l+1) >> 1); - if (table[mid] <= val) - l = mid; - else - r = mid; + /** + * Decode `Int64Value` from JSON string. + */ + internalJsonRead(json, options, target) { + if (!target) + target = this.create(); + target.value = this.refJsonReader.scalar(json, runtime_1.ScalarType.INT64, runtime_2.LongType.STRING, "value"); + return target; } - return l; -} - - - -/***/ }), - -/***/ 39478: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -// Description of supported double byte encodings and aliases. -// Tables are not require()-d until they are needed to speed up library load. -// require()-s are direct to support Browserify. - -module.exports = { - - // == Japanese/ShiftJIS ==================================================== - // All japanese encodings are based on JIS X set of standards: - // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. - // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. - // Has several variations in 1978, 1983, 1990 and 1997. - // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. - // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. - // 2 planes, first is superset of 0208, second - revised 0212. - // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) - - // Byte encodings are: - // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte - // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. - // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. - // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. - // 0x00-0x7F - lower part of 0201 - // 0x8E, 0xA1-0xDF - upper part of 0201 - // (0xA1-0xFE)x2 - 0208 plane (94x94). - // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). - // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. - // Used as-is in ISO2022 family. - // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, - // 0201-1976 Roman, 0208-1978, 0208-1983. - // * ISO2022-JP-1: Adds esc seq for 0212-1990. - // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. - // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. - // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. - // - // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. - // - // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html - - 'shiftjis': { - type: '_dbcs', - table: function() { return __nccwpck_require__(48064) }, - encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, - encodeSkipVals: [{from: 0xED40, to: 0xF940}], - }, - 'csshiftjis': 'shiftjis', - 'mskanji': 'shiftjis', - 'sjis': 'shiftjis', - 'windows31j': 'shiftjis', - 'ms31j': 'shiftjis', - 'xsjis': 'shiftjis', - 'windows932': 'shiftjis', - 'ms932': 'shiftjis', - '932': 'shiftjis', - 'cp932': 'shiftjis', - - 'eucjp': { - type: '_dbcs', - table: function() { return __nccwpck_require__(64688) }, - encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, - }, - - // TODO: KDDI extension to Shift_JIS - // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. - // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. - - - // == Chinese/GBK ========================================================== - // http://en.wikipedia.org/wiki/GBK - // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder - - // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 - 'gb2312': 'cp936', - 'gb231280': 'cp936', - 'gb23121980': 'cp936', - 'csgb2312': 'cp936', - 'csiso58gb231280': 'cp936', - 'euccn': 'cp936', - - // Microsoft's CP936 is a subset and approximation of GBK. - 'windows936': 'cp936', - 'ms936': 'cp936', - '936': 'cp936', - 'cp936': { - type: '_dbcs', - table: function() { return __nccwpck_require__(85497) }, - }, - - // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. - 'gbk': { - type: '_dbcs', - table: function() { return (__nccwpck_require__(85497).concat)(__nccwpck_require__(49670)) }, - }, - 'xgbk': 'gbk', - 'isoir58': 'gbk', - - // GB18030 is an algorithmic extension of GBK. - // Main source: https://www.w3.org/TR/encoding/#gbk-encoder - // http://icu-project.org/docs/papers/gb18030.html - // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml - // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 - 'gb18030': { - type: '_dbcs', - table: function() { return (__nccwpck_require__(85497).concat)(__nccwpck_require__(49670)) }, - gb18030: function() { return __nccwpck_require__(19331) }, - encodeSkipVals: [0x80], - encodeAdd: {'€': 0xA2E3}, - }, - - 'chinese': 'gb18030', - - - // == Korean =============================================================== - // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. - 'windows949': 'cp949', - 'ms949': 'cp949', - '949': 'cp949', - 'cp949': { - type: '_dbcs', - table: function() { return __nccwpck_require__(99519) }, - }, - - 'cseuckr': 'cp949', - 'csksc56011987': 'cp949', - 'euckr': 'cp949', - 'isoir149': 'cp949', - 'korean': 'cp949', - 'ksc56011987': 'cp949', - 'ksc56011989': 'cp949', - 'ksc5601': 'cp949', - - - // == Big5/Taiwan/Hong Kong ================================================ - // There are lots of tables for Big5 and cp950. Please see the following links for history: - // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html - // Variations, in roughly number of defined chars: - // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT - // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ - // * Big5-2003 (Taiwan standard) almost superset of cp950. - // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. - // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. - // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. - // Plus, it has 4 combining sequences. - // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 - // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. - // Implementations are not consistent within browsers; sometimes labeled as just big5. - // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. - // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 - // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. - // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt - // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt - // - // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder - // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. - - 'windows950': 'cp950', - 'ms950': 'cp950', - '950': 'cp950', - 'cp950': { - type: '_dbcs', - table: function() { return __nccwpck_require__(31745) }, - }, - - // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. - 'big5': 'big5hkscs', - 'big5hkscs': { - type: '_dbcs', - table: function() { return (__nccwpck_require__(31745).concat)(__nccwpck_require__(93991)) }, - encodeSkipVals: [ - // Although Encoding Standard says we should avoid encoding to HKSCS area (See Step 1 of - // https://encoding.spec.whatwg.org/#index-big5-pointer), we still do it to increase compatibility with ICU. - // But if a single unicode point can be encoded both as HKSCS and regular Big5, we prefer the latter. - 0x8e69, 0x8e6f, 0x8e7e, 0x8eab, 0x8eb4, 0x8ecd, 0x8ed0, 0x8f57, 0x8f69, 0x8f6e, 0x8fcb, 0x8ffe, - 0x906d, 0x907a, 0x90c4, 0x90dc, 0x90f1, 0x91bf, 0x92af, 0x92b0, 0x92b1, 0x92b2, 0x92d1, 0x9447, 0x94ca, - 0x95d9, 0x96fc, 0x9975, 0x9b76, 0x9b78, 0x9b7b, 0x9bc6, 0x9bde, 0x9bec, 0x9bf6, 0x9c42, 0x9c53, 0x9c62, - 0x9c68, 0x9c6b, 0x9c77, 0x9cbc, 0x9cbd, 0x9cd0, 0x9d57, 0x9d5a, 0x9dc4, 0x9def, 0x9dfb, 0x9ea9, 0x9eef, - 0x9efd, 0x9f60, 0x9fcb, 0xa077, 0xa0dc, 0xa0df, 0x8fcc, 0x92c8, 0x9644, 0x96ed, - - // Step 2 of https://encoding.spec.whatwg.org/#index-big5-pointer: Use last pointer for U+2550, U+255E, U+2561, U+256A, U+5341, or U+5345 - 0xa2a4, 0xa2a5, 0xa2a7, 0xa2a6, 0xa2cc, 0xa2ce, - ], - }, - - 'cnbig5': 'big5hkscs', - 'csbig5': 'big5hkscs', - 'xxbig5': 'big5hkscs', -}; - - -/***/ }), - -/***/ 16386: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -// Update this array if you add/rename/remove files in this directory. -// We support Browserify by skipping automatic module discovery and requiring modules directly. -var modules = [ - __nccwpck_require__(27489), - __nccwpck_require__(55341), - __nccwpck_require__(32602), - __nccwpck_require__(49451), - __nccwpck_require__(96441), - __nccwpck_require__(99118), - __nccwpck_require__(70820), - __nccwpck_require__(77668), - __nccwpck_require__(39478), -]; - -// Put all encoding/alias/codec definitions to single object and export it. -for (var i = 0; i < modules.length; i++) { - var module = modules[i]; - for (var enc in module) - if (Object.prototype.hasOwnProperty.call(module, enc)) - exports[enc] = module[enc]; -} - - -/***/ }), - -/***/ 27489: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var Buffer = (__nccwpck_require__(97084).Buffer); - -// Export Node.js internal encodings. - -module.exports = { - // Encodings - utf8: { type: "_internal", bomAware: true}, - cesu8: { type: "_internal", bomAware: true}, - unicode11utf8: "utf8", - - ucs2: { type: "_internal", bomAware: true}, - utf16le: "ucs2", - - binary: { type: "_internal" }, - base64: { type: "_internal" }, - hex: { type: "_internal" }, - - // Codec. - _internal: InternalCodec, -}; - -//------------------------------------------------------------------------------ - -function InternalCodec(codecOptions, iconv) { - this.enc = codecOptions.encodingName; - this.bomAware = codecOptions.bomAware; - - if (this.enc === "base64") - this.encoder = InternalEncoderBase64; - else if (this.enc === "cesu8") { - this.enc = "utf8"; // Use utf8 for decoding. - this.encoder = InternalEncoderCesu8; - - // Add decoder for versions of Node not supporting CESU-8 - if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { - this.decoder = InternalDecoderCesu8; - this.defaultCharUnicode = iconv.defaultCharUnicode; + create(value) { + const message = { value: "0" }; + globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== undefined) + (0, runtime_5.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* int64 value */ 1: + message.value = reader.int64().toString(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } } + return message; } -} - -InternalCodec.prototype.encoder = InternalEncoder; -InternalCodec.prototype.decoder = InternalDecoder; - -//------------------------------------------------------------------------------ - -// We use node.js internal decoder. Its signature is the same as ours. -var StringDecoder = (__nccwpck_require__(71576).StringDecoder); - -if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. - StringDecoder.prototype.end = function() {}; - - -function InternalDecoder(options, codec) { - this.decoder = new StringDecoder(codec.enc); -} - -InternalDecoder.prototype.write = function(buf) { - if (!Buffer.isBuffer(buf)) { - buf = Buffer.from(buf); + internalBinaryWrite(message, writer, options) { + /* int64 value = 1; */ + if (message.value !== "0") + writer.tag(1, runtime_3.WireType.Varint).int64(message.value); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } - - return this.decoder.write(buf); -} - -InternalDecoder.prototype.end = function() { - return this.decoder.end(); -} - - -//------------------------------------------------------------------------------ -// Encoder is mostly trivial - -function InternalEncoder(options, codec) { - this.enc = codec.enc; -} - -InternalEncoder.prototype.write = function(str) { - return Buffer.from(str, this.enc); -} - -InternalEncoder.prototype.end = function() { -} - - -//------------------------------------------------------------------------------ -// Except base64 encoder, which must keep its state. - -function InternalEncoderBase64(options, codec) { - this.prevStr = ''; -} - -InternalEncoderBase64.prototype.write = function(str) { - str = this.prevStr + str; - var completeQuads = str.length - (str.length % 4); - this.prevStr = str.slice(completeQuads); - str = str.slice(0, completeQuads); - - return Buffer.from(str, "base64"); } - -InternalEncoderBase64.prototype.end = function() { - return Buffer.from(this.prevStr, "base64"); -} - - -//------------------------------------------------------------------------------ -// CESU-8 encoder is also special. - -function InternalEncoderCesu8(options, codec) { -} - -InternalEncoderCesu8.prototype.write = function(str) { - var buf = Buffer.alloc(str.length * 3), bufIdx = 0; - for (var i = 0; i < str.length; i++) { - var charCode = str.charCodeAt(i); - // Naive implementation, but it works because CESU-8 is especially easy - // to convert from UTF-16 (which all JS strings are encoded in). - if (charCode < 0x80) - buf[bufIdx++] = charCode; - else if (charCode < 0x800) { - buf[bufIdx++] = 0xC0 + (charCode >>> 6); - buf[bufIdx++] = 0x80 + (charCode & 0x3f); - } - else { // charCode will always be < 0x10000 in javascript. - buf[bufIdx++] = 0xE0 + (charCode >>> 12); - buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f); - buf[bufIdx++] = 0x80 + (charCode & 0x3f); +/** + * @generated MessageType for protobuf message google.protobuf.Int64Value + */ +exports.Int64Value = new Int64Value$Type(); +// @generated message type with reflection information, may provide speed optimized methods +class UInt64Value$Type extends runtime_7.MessageType { + constructor() { + super("google.protobuf.UInt64Value", [ + { no: 1, name: "value", kind: "scalar", T: 4 /*ScalarType.UINT64*/ } + ]); + } + /** + * Encode `UInt64Value` to JSON string. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.scalar(runtime_1.ScalarType.UINT64, message.value, "value", false, true); + } + /** + * Decode `UInt64Value` from JSON string. + */ + internalJsonRead(json, options, target) { + if (!target) + target = this.create(); + target.value = this.refJsonReader.scalar(json, runtime_1.ScalarType.UINT64, runtime_2.LongType.STRING, "value"); + return target; + } + create(value) { + const message = { value: "0" }; + globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== undefined) + (0, runtime_5.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* uint64 value */ 1: + message.value = reader.uint64().toString(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } } + return message; + } + internalBinaryWrite(message, writer, options) { + /* uint64 value = 1; */ + if (message.value !== "0") + writer.tag(1, runtime_3.WireType.Varint).uint64(message.value); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } - return buf.slice(0, bufIdx); -} - -InternalEncoderCesu8.prototype.end = function() { } - -//------------------------------------------------------------------------------ -// CESU-8 decoder is not implemented in Node v4.0+ - -function InternalDecoderCesu8(options, codec) { - this.acc = 0; - this.contBytes = 0; - this.accBytes = 0; - this.defaultCharUnicode = codec.defaultCharUnicode; +/** + * @generated MessageType for protobuf message google.protobuf.UInt64Value + */ +exports.UInt64Value = new UInt64Value$Type(); +// @generated message type with reflection information, may provide speed optimized methods +class Int32Value$Type extends runtime_7.MessageType { + constructor() { + super("google.protobuf.Int32Value", [ + { no: 1, name: "value", kind: "scalar", T: 5 /*ScalarType.INT32*/ } + ]); + } + /** + * Encode `Int32Value` to JSON string. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.scalar(5, message.value, "value", false, true); + } + /** + * Decode `Int32Value` from JSON string. + */ + internalJsonRead(json, options, target) { + if (!target) + target = this.create(); + target.value = this.refJsonReader.scalar(json, 5, undefined, "value"); + return target; + } + create(value) { + const message = { value: 0 }; + globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== undefined) + (0, runtime_5.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* int32 value */ 1: + message.value = reader.int32(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + /* int32 value = 1; */ + if (message.value !== 0) + writer.tag(1, runtime_3.WireType.Varint).int32(message.value); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } } - -InternalDecoderCesu8.prototype.write = function(buf) { - var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, - res = ''; - for (var i = 0; i < buf.length; i++) { - var curByte = buf[i]; - if ((curByte & 0xC0) !== 0x80) { // Leading byte - if (contBytes > 0) { // Previous code is invalid - res += this.defaultCharUnicode; - contBytes = 0; +/** + * @generated MessageType for protobuf message google.protobuf.Int32Value + */ +exports.Int32Value = new Int32Value$Type(); +// @generated message type with reflection information, may provide speed optimized methods +class UInt32Value$Type extends runtime_7.MessageType { + constructor() { + super("google.protobuf.UInt32Value", [ + { no: 1, name: "value", kind: "scalar", T: 13 /*ScalarType.UINT32*/ } + ]); + } + /** + * Encode `UInt32Value` to JSON string. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.scalar(13, message.value, "value", false, true); + } + /** + * Decode `UInt32Value` from JSON string. + */ + internalJsonRead(json, options, target) { + if (!target) + target = this.create(); + target.value = this.refJsonReader.scalar(json, 13, undefined, "value"); + return target; + } + create(value) { + const message = { value: 0 }; + globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== undefined) + (0, runtime_5.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* uint32 value */ 1: + message.value = reader.uint32(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } - - if (curByte < 0x80) { // Single-byte code - res += String.fromCharCode(curByte); - } else if (curByte < 0xE0) { // Two-byte code - acc = curByte & 0x1F; - contBytes = 1; accBytes = 1; - } else if (curByte < 0xF0) { // Three-byte code - acc = curByte & 0x0F; - contBytes = 2; accBytes = 1; - } else { // Four or more are not supported for CESU-8. - res += this.defaultCharUnicode; + } + return message; + } + internalBinaryWrite(message, writer, options) { + /* uint32 value = 1; */ + if (message.value !== 0) + writer.tag(1, runtime_3.WireType.Varint).uint32(message.value); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } +} +/** + * @generated MessageType for protobuf message google.protobuf.UInt32Value + */ +exports.UInt32Value = new UInt32Value$Type(); +// @generated message type with reflection information, may provide speed optimized methods +class BoolValue$Type extends runtime_7.MessageType { + constructor() { + super("google.protobuf.BoolValue", [ + { no: 1, name: "value", kind: "scalar", T: 8 /*ScalarType.BOOL*/ } + ]); + } + /** + * Encode `BoolValue` to JSON bool. + */ + internalJsonWrite(message, options) { + return message.value; + } + /** + * Decode `BoolValue` from JSON bool. + */ + internalJsonRead(json, options, target) { + if (!target) + target = this.create(); + target.value = this.refJsonReader.scalar(json, 8, undefined, "value"); + return target; + } + create(value) { + const message = { value: false }; + globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== undefined) + (0, runtime_5.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool value */ 1: + message.value = reader.bool(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } - } else { // Continuation byte - if (contBytes > 0) { // We're waiting for it. - acc = (acc << 6) | (curByte & 0x3f); - contBytes--; accBytes++; - if (contBytes === 0) { - // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80) - if (accBytes === 2 && acc < 0x80 && acc > 0) - res += this.defaultCharUnicode; - else if (accBytes === 3 && acc < 0x800) - res += this.defaultCharUnicode; - else - // Actually add character. - res += String.fromCharCode(acc); - } - } else { // Unexpected continuation byte - res += this.defaultCharUnicode; + } + return message; + } + internalBinaryWrite(message, writer, options) { + /* bool value = 1; */ + if (message.value !== false) + writer.tag(1, runtime_3.WireType.Varint).bool(message.value); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } +} +/** + * @generated MessageType for protobuf message google.protobuf.BoolValue + */ +exports.BoolValue = new BoolValue$Type(); +// @generated message type with reflection information, may provide speed optimized methods +class StringValue$Type extends runtime_7.MessageType { + constructor() { + super("google.protobuf.StringValue", [ + { no: 1, name: "value", kind: "scalar", T: 9 /*ScalarType.STRING*/ } + ]); + } + /** + * Encode `StringValue` to JSON string. + */ + internalJsonWrite(message, options) { + return message.value; + } + /** + * Decode `StringValue` from JSON string. + */ + internalJsonRead(json, options, target) { + if (!target) + target = this.create(); + target.value = this.refJsonReader.scalar(json, 9, undefined, "value"); + return target; + } + create(value) { + const message = { value: "" }; + globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== undefined) + (0, runtime_5.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* string value */ 1: + message.value = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } + return message; + } + internalBinaryWrite(message, writer, options) { + /* string value = 1; */ + if (message.value !== "") + writer.tag(1, runtime_3.WireType.LengthDelimited).string(message.value); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } - this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes; - return res; } - -InternalDecoderCesu8.prototype.end = function() { - var res = 0; - if (this.contBytes > 0) - res += this.defaultCharUnicode; - return res; +/** + * @generated MessageType for protobuf message google.protobuf.StringValue + */ +exports.StringValue = new StringValue$Type(); +// @generated message type with reflection information, may provide speed optimized methods +class BytesValue$Type extends runtime_7.MessageType { + constructor() { + super("google.protobuf.BytesValue", [ + { no: 1, name: "value", kind: "scalar", T: 12 /*ScalarType.BYTES*/ } + ]); + } + /** + * Encode `BytesValue` to JSON string. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.scalar(12, message.value, "value", false, true); + } + /** + * Decode `BytesValue` from JSON string. + */ + internalJsonRead(json, options, target) { + if (!target) + target = this.create(); + target.value = this.refJsonReader.scalar(json, 12, undefined, "value"); + return target; + } + create(value) { + const message = { value: new Uint8Array(0) }; + globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== undefined) + (0, runtime_5.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bytes value */ 1: + message.value = reader.bytes(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; + } + internalBinaryWrite(message, writer, options) { + /* bytes value = 1; */ + if (message.value.length) + writer.tag(1, runtime_3.WireType.LengthDelimited).bytes(message.value); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; + } } - +/** + * @generated MessageType for protobuf message google.protobuf.BytesValue + */ +exports.BytesValue = new BytesValue$Type(); +//# sourceMappingURL=wrappers.js.map /***/ }), -/***/ 96441: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 49960: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -var Buffer = (__nccwpck_require__(97084).Buffer); - -// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that -// correspond to encoded bytes (if 128 - then lower half is ASCII). - -exports._sbcs = SBCSCodec; -function SBCSCodec(codecOptions, iconv) { - if (!codecOptions) - throw new Error("SBCS codec is called without the data.") - - // Prepare char buffer for decoding. - if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)) - throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)"); - - if (codecOptions.chars.length === 128) { - var asciiString = ""; - for (var i = 0; i < 128; i++) - asciiString += String.fromCharCode(i); - codecOptions.chars = asciiString + codecOptions.chars; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; } - - this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2'); - - // Encoding buffer. - var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); - - for (var i = 0; i < codecOptions.chars.length; i++) - encodeBuf[codecOptions.chars.charCodeAt(i)] = i; - - this.encodeBuf = encodeBuf; -} - -SBCSCodec.prototype.encoder = SBCSEncoder; -SBCSCodec.prototype.decoder = SBCSDecoder; - - -function SBCSEncoder(options, codec) { - this.encodeBuf = codec.encodeBuf; -} - -SBCSEncoder.prototype.write = function(str) { - var buf = Buffer.alloc(str.length); - for (var i = 0; i < str.length; i++) - buf[i] = this.encodeBuf[str.charCodeAt(i)]; - - return buf; -} - -SBCSEncoder.prototype.end = function() { -} - - -function SBCSDecoder(options, codec) { - this.decodeBuf = codec.decodeBuf; -} - -SBCSDecoder.prototype.write = function(buf) { - // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. - var decodeBuf = this.decodeBuf; - var newBuf = Buffer.alloc(buf.length*2); - var idx1 = 0, idx2 = 0; - for (var i = 0; i < buf.length; i++) { - idx1 = buf[i]*2; idx2 = i*2; - newBuf[idx2] = decodeBuf[idx1]; - newBuf[idx2+1] = decodeBuf[idx1+1]; - } - return newBuf.toString('ucs2'); -} - -SBCSDecoder.prototype.end = function() { -} - - -/***/ }), - -/***/ 70820: -/***/ ((module) => { - -"use strict"; - - -// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. -module.exports = { - "437": "cp437", - "737": "cp737", - "775": "cp775", - "850": "cp850", - "852": "cp852", - "855": "cp855", - "856": "cp856", - "857": "cp857", - "858": "cp858", - "860": "cp860", - "861": "cp861", - "862": "cp862", - "863": "cp863", - "864": "cp864", - "865": "cp865", - "866": "cp866", - "869": "cp869", - "874": "windows874", - "922": "cp922", - "1046": "cp1046", - "1124": "cp1124", - "1125": "cp1125", - "1129": "cp1129", - "1133": "cp1133", - "1161": "cp1161", - "1162": "cp1162", - "1163": "cp1163", - "1250": "windows1250", - "1251": "windows1251", - "1252": "windows1252", - "1253": "windows1253", - "1254": "windows1254", - "1255": "windows1255", - "1256": "windows1256", - "1257": "windows1257", - "1258": "windows1258", - "28591": "iso88591", - "28592": "iso88592", - "28593": "iso88593", - "28594": "iso88594", - "28595": "iso88595", - "28596": "iso88596", - "28597": "iso88597", - "28598": "iso88598", - "28599": "iso88599", - "28600": "iso885910", - "28601": "iso885911", - "28603": "iso885913", - "28604": "iso885914", - "28605": "iso885915", - "28606": "iso885916", - "windows874": { - "type": "_sbcs", - "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - }, - "win874": "windows874", - "cp874": "windows874", - "windows1250": { - "type": "_sbcs", - "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" - }, - "win1250": "windows1250", - "cp1250": "windows1250", - "windows1251": { - "type": "_sbcs", - "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" - }, - "win1251": "windows1251", - "cp1251": "windows1251", - "windows1252": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "win1252": "windows1252", - "cp1252": "windows1252", - "windows1253": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" - }, - "win1253": "windows1253", - "cp1253": "windows1253", - "windows1254": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" - }, - "win1254": "windows1254", - "cp1254": "windows1254", - "windows1255": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" - }, - "win1255": "windows1255", - "cp1255": "windows1255", - "windows1256": { - "type": "_sbcs", - "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے" - }, - "win1256": "windows1256", - "cp1256": "windows1256", - "windows1257": { - "type": "_sbcs", - "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙" - }, - "win1257": "windows1257", - "cp1257": "windows1257", - "windows1258": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" - }, - "win1258": "windows1258", - "cp1258": "windows1258", - "iso88591": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "cp28591": "iso88591", - "iso88592": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" - }, - "cp28592": "iso88592", - "iso88593": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�Ż°ħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙" - }, - "cp28593": "iso88593", - "iso88594": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤ĨĻ§¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩļˇ¸šēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖ×ØŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙" - }, - "cp28594": "iso88594", - "iso88595": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ" - }, - "cp28595": "iso88595", - "iso88596": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������" - }, - "cp28596": "iso88596", - "iso88597": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" - }, - "cp28597": "iso88597", - "iso88598": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" - }, - "cp28598": "iso88598", - "iso88599": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" - }, - "cp28599": "iso88599", - "iso885910": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨĶ§ĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ" - }, - "cp28600": "iso885910", - "iso885911": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - }, - "cp28601": "iso885911", - "iso885913": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’" - }, - "cp28603": "iso885913", - "iso885914": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ" - }, - "cp28604": "iso885914", - "iso885915": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "cp28605": "iso885915", - "iso885916": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Š§š©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ" - }, - "cp28606": "iso885916", - "cp437": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm437": "cp437", - "csibm437": "cp437", - "cp737": { - "type": "_sbcs", - "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ " - }, - "ibm737": "cp737", - "csibm737": "cp737", - "cp775": { - "type": "_sbcs", - "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£ØפĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ " - }, - "ibm775": "cp775", - "csibm775": "cp775", - "cp850": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " - }, - "ibm850": "cp850", - "csibm850": "cp850", - "cp852": { - "type": "_sbcs", - "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ " - }, - "ibm852": "cp852", - "csibm852": "cp852", - "cp855": { - "type": "_sbcs", - "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ " - }, - "ibm855": "cp855", - "csibm855": "cp855", - "cp856": { - "type": "_sbcs", - "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ " - }, - "ibm856": "cp856", - "csibm856": "cp856", - "cp857": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ " - }, - "ibm857": "cp857", - "csibm857": "cp857", - "cp858": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " - }, - "ibm858": "cp858", - "csibm858": "cp858", - "cp860": { - "type": "_sbcs", - "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm860": "cp860", - "csibm860": "cp860", - "cp861": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm861": "cp861", - "csibm861": "cp861", - "cp862": { - "type": "_sbcs", - "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm862": "cp862", - "csibm862": "cp862", - "cp863": { - "type": "_sbcs", - "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm863": "cp863", - "csibm863": "cp863", - "cp864": { - "type": "_sbcs", - "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�" - }, - "ibm864": "cp864", - "csibm864": "cp864", - "cp865": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm865": "cp865", - "csibm865": "cp865", - "cp866": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ " - }, - "ibm866": "cp866", - "csibm866": "cp866", - "cp869": { - "type": "_sbcs", - "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ " - }, - "ibm869": "cp869", - "csibm869": "cp869", - "cp922": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖ×ØÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ" - }, - "ibm922": "cp922", - "csibm922": "cp922", - "cp1046": { - "type": "_sbcs", - "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�" - }, - "ibm1046": "cp1046", - "csibm1046": "cp1046", - "cp1124": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ" - }, - "ibm1124": "cp1124", - "csibm1124": "cp1124", - "cp1125": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ " - }, - "ibm1125": "cp1125", - "csibm1125": "cp1125", - "cp1129": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" - }, - "ibm1129": "cp1129", - "csibm1129": "cp1129", - "cp1133": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�" - }, - "ibm1133": "cp1133", - "csibm1133": "cp1133", - "cp1161": { - "type": "_sbcs", - "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ " - }, - "ibm1161": "cp1161", - "csibm1161": "cp1161", - "cp1162": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - }, - "ibm1162": "cp1162", - "csibm1162": "cp1162", - "cp1163": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" - }, - "ibm1163": "cp1163", - "csibm1163": "cp1163", - "maccroatian": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ" - }, - "maccyrillic": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" - }, - "macgreek": { - "type": "_sbcs", - "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�" - }, - "maciceland": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macroman": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macromania": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macthai": { - "type": "_sbcs", - "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����" - }, - "macturkish": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macukraine": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" - }, - "koi8r": { - "type": "_sbcs", - "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "koi8u": { - "type": "_sbcs", - "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "koi8ru": { - "type": "_sbcs", - "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "koi8t": { - "type": "_sbcs", - "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "armscii8": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�" - }, - "rk1048": { - "type": "_sbcs", - "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" - }, - "tcvn": { - "type": "_sbcs", - "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ" - }, - "georgianacademy": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "georgianps": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "pt154": { - "type": "_sbcs", - "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" - }, - "viscii": { - "type": "_sbcs", - "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ" - }, - "iso646cn": { - "type": "_sbcs", - "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" - }, - "iso646jp": { - "type": "_sbcs", - "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" - }, - "hproman8": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�" - }, - "macintosh": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "ascii": { - "type": "_sbcs", - "chars": "��������������������������������������������������������������������������������������������������������������������������������" - }, - "tis620": { - "type": "_sbcs", - "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - } -} - -/***/ }), - -/***/ 99118: -/***/ ((module) => { - -"use strict"; - - -// Manually added data to be used by sbcs codec in addition to generated one. - -module.exports = { - // Not supported by iconv, not sure why. - "10029": "maccenteuro", - "maccenteuro": { - "type": "_sbcs", - "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" - }, - - "808": "cp808", - "ibm808": "cp808", - "cp808": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " - }, - - "mik": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - - "cp720": { - "type": "_sbcs", - "chars": "\x80\x81éâ\x84à\x86çêëèïî\x8d\x8e\x8f\x90\u0651\u0652ô¤ـûùءآأؤ£إئابةتثجحخدذرزسشص«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ضطظعغفµقكلمنهوىي≡\u064b\u064c\u064d\u064e\u064f\u0650≈°∙·√ⁿ²■\u00a0" - }, - - // Aliases of generated encodings. - "ascii8bit": "ascii", - "usascii": "ascii", - "ansix34": "ascii", - "ansix341968": "ascii", - "ansix341986": "ascii", - "csascii": "ascii", - "cp367": "ascii", - "ibm367": "ascii", - "isoir6": "ascii", - "iso646us": "ascii", - "iso646irv": "ascii", - "us": "ascii", - - "latin1": "iso88591", - "latin2": "iso88592", - "latin3": "iso88593", - "latin4": "iso88594", - "latin5": "iso88599", - "latin6": "iso885910", - "latin7": "iso885913", - "latin8": "iso885914", - "latin9": "iso885915", - "latin10": "iso885916", - - "csisolatin1": "iso88591", - "csisolatin2": "iso88592", - "csisolatin3": "iso88593", - "csisolatin4": "iso88594", - "csisolatincyrillic": "iso88595", - "csisolatinarabic": "iso88596", - "csisolatingreek" : "iso88597", - "csisolatinhebrew": "iso88598", - "csisolatin5": "iso88599", - "csisolatin6": "iso885910", - - "l1": "iso88591", - "l2": "iso88592", - "l3": "iso88593", - "l4": "iso88594", - "l5": "iso88599", - "l6": "iso885910", - "l7": "iso885913", - "l8": "iso885914", - "l9": "iso885915", - "l10": "iso885916", - - "isoir14": "iso646jp", - "isoir57": "iso646cn", - "isoir100": "iso88591", - "isoir101": "iso88592", - "isoir109": "iso88593", - "isoir110": "iso88594", - "isoir144": "iso88595", - "isoir127": "iso88596", - "isoir126": "iso88597", - "isoir138": "iso88598", - "isoir148": "iso88599", - "isoir157": "iso885910", - "isoir166": "tis620", - "isoir179": "iso885913", - "isoir199": "iso885914", - "isoir203": "iso885915", - "isoir226": "iso885916", - - "cp819": "iso88591", - "ibm819": "iso88591", - - "cyrillic": "iso88595", - - "arabic": "iso88596", - "arabic8": "iso88596", - "ecma114": "iso88596", - "asmo708": "iso88596", - - "greek" : "iso88597", - "greek8" : "iso88597", - "ecma118" : "iso88597", - "elot928" : "iso88597", - - "hebrew": "iso88598", - "hebrew8": "iso88598", - - "turkish": "iso88599", - "turkish8": "iso88599", - - "thai": "iso885911", - "thai8": "iso885911", - - "celtic": "iso885914", - "celtic8": "iso885914", - "isoceltic": "iso885914", - - "tis6200": "tis620", - "tis62025291": "tis620", - "tis62025330": "tis620", - - "10000": "macroman", - "10006": "macgreek", - "10007": "maccyrillic", - "10079": "maciceland", - "10081": "macturkish", - - "cspc8codepage437": "cp437", - "cspc775baltic": "cp775", - "cspc850multilingual": "cp850", - "cspcp852": "cp852", - "cspc862latinhebrew": "cp862", - "cpgr": "cp869", - - "msee": "cp1250", - "mscyrl": "cp1251", - "msansi": "cp1252", - "msgreek": "cp1253", - "msturk": "cp1254", - "mshebr": "cp1255", - "msarab": "cp1256", - "winbaltrim": "cp1257", - - "cp20866": "koi8r", - "20866": "koi8r", - "ibm878": "koi8r", - "cskoi8r": "koi8r", - - "cp21866": "koi8u", - "21866": "koi8u", - "ibm1168": "koi8u", - - "strk10482002": "rk1048", - - "tcvn5712": "tcvn", - "tcvn57121": "tcvn", - - "gb198880": "iso646cn", - "cn": "iso646cn", - - "csiso14jisc6220ro": "iso646jp", - "jisc62201969ro": "iso646jp", - "jp": "iso646jp", - - "cshproman8": "hproman8", - "r8": "hproman8", - "roman8": "hproman8", - "xroman8": "hproman8", - "ibm1051": "hproman8", - - "mac": "macintosh", - "csmacintosh": "macintosh", + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; - - +Object.defineProperty(exports, "__esModule", ({ value: true })); +__exportStar(__nccwpck_require__(54622), exports); +__exportStar(__nccwpck_require__(8626), exports); +__exportStar(__nccwpck_require__(58178), exports); +__exportStar(__nccwpck_require__(63077), exports); +//# sourceMappingURL=index.js.map /***/ }), -/***/ 32602: +/***/ 58178: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -var Buffer = (__nccwpck_require__(97084).Buffer); - -// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js - -// == UTF16-BE codec. ========================================================== - -exports.utf16be = Utf16BECodec; -function Utf16BECodec() { -} - -Utf16BECodec.prototype.encoder = Utf16BEEncoder; -Utf16BECodec.prototype.decoder = Utf16BEDecoder; -Utf16BECodec.prototype.bomAware = true; - - -// -- Encoding - -function Utf16BEEncoder() { -} - -Utf16BEEncoder.prototype.write = function(str) { - var buf = Buffer.from(str, 'ucs2'); - for (var i = 0; i < buf.length; i += 2) { - var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ArtifactService = exports.GetSignedArtifactURLResponse = exports.GetSignedArtifactURLRequest = exports.ListArtifactsResponse_MonolithArtifact = exports.ListArtifactsResponse = exports.ListArtifactsRequest = exports.FinalizeArtifactResponse = exports.FinalizeArtifactRequest = exports.CreateArtifactResponse = exports.CreateArtifactRequest = void 0; +// @generated by protobuf-ts 2.9.1 with parameter long_type_string,client_none,generate_dependencies +// @generated from protobuf file "results/api/v1/artifact.proto" (package "github.actions.results.api.v1", syntax proto3) +// tslint:disable +const runtime_rpc_1 = __nccwpck_require__(60012); +const runtime_1 = __nccwpck_require__(4061); +const runtime_2 = __nccwpck_require__(4061); +const runtime_3 = __nccwpck_require__(4061); +const runtime_4 = __nccwpck_require__(4061); +const runtime_5 = __nccwpck_require__(4061); +const wrappers_1 = __nccwpck_require__(8626); +const wrappers_2 = __nccwpck_require__(8626); +const timestamp_1 = __nccwpck_require__(54622); +// @generated message type with reflection information, may provide speed optimized methods +class CreateArtifactRequest$Type extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.CreateArtifactRequest", [ + { no: 1, name: "workflow_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, + { no: 2, name: "workflow_job_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, + { no: 3, name: "name", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, + { no: 4, name: "expires_at", kind: "message", T: () => timestamp_1.Timestamp }, + { no: 5, name: "version", kind: "scalar", T: 5 /*ScalarType.INT32*/ } + ]); } - return buf; -} - -Utf16BEEncoder.prototype.end = function() { -} - - -// -- Decoding - -function Utf16BEDecoder() { - this.overflowByte = -1; -} - -Utf16BEDecoder.prototype.write = function(buf) { - if (buf.length == 0) - return ''; - - var buf2 = Buffer.alloc(buf.length + 1), - i = 0, j = 0; - - if (this.overflowByte !== -1) { - buf2[0] = buf[0]; - buf2[1] = this.overflowByte; - i = 1; j = 2; + create(value) { + const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "", version: 0 }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== undefined) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; } - - for (; i < buf.length-1; i += 2, j+= 2) { - buf2[j] = buf[i+1]; - buf2[j+1] = buf[i]; + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* string workflow_run_backend_id */ 1: + message.workflowRunBackendId = reader.string(); + break; + case /* string workflow_job_run_backend_id */ 2: + message.workflowJobRunBackendId = reader.string(); + break; + case /* string name */ 3: + message.name = reader.string(); + break; + case /* google.protobuf.Timestamp expires_at */ 4: + message.expiresAt = timestamp_1.Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.expiresAt); + break; + case /* int32 version */ 5: + message.version = reader.int32(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } + } + return message; } - - this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; - - return buf2.slice(0, j).toString('ucs2'); -} - -Utf16BEDecoder.prototype.end = function() { - this.overflowByte = -1; -} - - -// == UTF-16 codec ============================================================= -// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic. -// Defaults to UTF-16LE, as it's prevalent and default in Node. -// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le -// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'}); - -// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). - -exports.utf16 = Utf16Codec; -function Utf16Codec(codecOptions, iconv) { - this.iconv = iconv; -} - -Utf16Codec.prototype.encoder = Utf16Encoder; -Utf16Codec.prototype.decoder = Utf16Decoder; - - -// -- Encoding (pass-through) - -function Utf16Encoder(options, codec) { - options = options || {}; - if (options.addBOM === undefined) - options.addBOM = true; - this.encoder = codec.iconv.getEncoder('utf-16le', options); -} - -Utf16Encoder.prototype.write = function(str) { - return this.encoder.write(str); -} - -Utf16Encoder.prototype.end = function() { - return this.encoder.end(); -} - - -// -- Decoding - -function Utf16Decoder(options, codec) { - this.decoder = null; - this.initialBufs = []; - this.initialBufsLen = 0; - - this.options = options || {}; - this.iconv = codec.iconv; -} - -Utf16Decoder.prototype.write = function(buf) { - if (!this.decoder) { - // Codec is not chosen yet. Accumulate initial bytes. - this.initialBufs.push(buf); - this.initialBufsLen += buf.length; - - if (this.initialBufsLen < 16) // We need more bytes to use space heuristic (see below) - return ''; - - // We have enough bytes -> detect endianness. - var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); - - var resStr = ''; - for (var i = 0; i < this.initialBufs.length; i++) - resStr += this.decoder.write(this.initialBufs[i]); - - this.initialBufs.length = this.initialBufsLen = 0; - return resStr; + internalBinaryWrite(message, writer, options) { + /* string workflow_run_backend_id = 1; */ + if (message.workflowRunBackendId !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); + /* string workflow_job_run_backend_id = 2; */ + if (message.workflowJobRunBackendId !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); + /* string name = 3; */ + if (message.name !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.name); + /* google.protobuf.Timestamp expires_at = 4; */ + if (message.expiresAt) + timestamp_1.Timestamp.internalBinaryWrite(message.expiresAt, writer.tag(4, runtime_1.WireType.LengthDelimited).fork(), options).join(); + /* int32 version = 5; */ + if (message.version !== 0) + writer.tag(5, runtime_1.WireType.Varint).int32(message.version); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } - - return this.decoder.write(buf); } - -Utf16Decoder.prototype.end = function() { - if (!this.decoder) { - var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); - - var resStr = ''; - for (var i = 0; i < this.initialBufs.length; i++) - resStr += this.decoder.write(this.initialBufs[i]); - - var trail = this.decoder.end(); - if (trail) - resStr += trail; - - this.initialBufs.length = this.initialBufsLen = 0; - return resStr; +/** + * @generated MessageType for protobuf message github.actions.results.api.v1.CreateArtifactRequest + */ +exports.CreateArtifactRequest = new CreateArtifactRequest$Type(); +// @generated message type with reflection information, may provide speed optimized methods +class CreateArtifactResponse$Type extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.CreateArtifactResponse", [ + { no: 1, name: "ok", kind: "scalar", T: 8 /*ScalarType.BOOL*/ }, + { no: 2, name: "signed_upload_url", kind: "scalar", T: 9 /*ScalarType.STRING*/ } + ]); } - return this.decoder.end(); -} - -function detectEncoding(bufs, defaultEncoding) { - var b = []; - var charsProcessed = 0; - var asciiCharsLE = 0, asciiCharsBE = 0; // Number of ASCII chars when decoded as LE or BE. - - outer_loop: - for (var i = 0; i < bufs.length; i++) { - var buf = bufs[i]; - for (var j = 0; j < buf.length; j++) { - b.push(buf[j]); - if (b.length === 2) { - if (charsProcessed === 0) { - // Check BOM first. - if (b[0] === 0xFF && b[1] === 0xFE) return 'utf-16le'; - if (b[0] === 0xFE && b[1] === 0xFF) return 'utf-16be'; - } - - if (b[0] === 0 && b[1] !== 0) asciiCharsBE++; - if (b[0] !== 0 && b[1] === 0) asciiCharsLE++; - - b.length = 0; - charsProcessed++; - - if (charsProcessed >= 100) { - break outer_loop; - } + create(value) { + const message = { ok: false, signedUploadUrl: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== undefined) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ 1: + message.ok = reader.bool(); + break; + case /* string signed_upload_url */ 2: + message.signedUploadUrl = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } + return message; + } + internalBinaryWrite(message, writer, options) { + /* bool ok = 1; */ + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + /* string signed_upload_url = 2; */ + if (message.signedUploadUrl !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } - - // Make decisions. - // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon. - // So, we count ASCII as if it was LE or BE, and decide from that. - if (asciiCharsBE > asciiCharsLE) return 'utf-16be'; - if (asciiCharsBE < asciiCharsLE) return 'utf-16le'; - - // Couldn't decide (likely all zeros or not enough data). - return defaultEncoding || 'utf-16le'; -} - - - - -/***/ }), - -/***/ 55341: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -var Buffer = (__nccwpck_require__(97084).Buffer); - -// == UTF32-LE/BE codec. ========================================================== - -exports._utf32 = Utf32Codec; - -function Utf32Codec(codecOptions, iconv) { - this.iconv = iconv; - this.bomAware = true; - this.isLE = codecOptions.isLE; -} - -exports.utf32le = { type: '_utf32', isLE: true }; -exports.utf32be = { type: '_utf32', isLE: false }; - -// Aliases -exports.ucs4le = 'utf32le'; -exports.ucs4be = 'utf32be'; - -Utf32Codec.prototype.encoder = Utf32Encoder; -Utf32Codec.prototype.decoder = Utf32Decoder; - -// -- Encoding - -function Utf32Encoder(options, codec) { - this.isLE = codec.isLE; - this.highSurrogate = 0; } - -Utf32Encoder.prototype.write = function(str) { - var src = Buffer.from(str, 'ucs2'); - var dst = Buffer.alloc(src.length * 2); - var write32 = this.isLE ? dst.writeUInt32LE : dst.writeUInt32BE; - var offset = 0; - - for (var i = 0; i < src.length; i += 2) { - var code = src.readUInt16LE(i); - var isHighSurrogate = (0xD800 <= code && code < 0xDC00); - var isLowSurrogate = (0xDC00 <= code && code < 0xE000); - - if (this.highSurrogate) { - if (isHighSurrogate || !isLowSurrogate) { - // There shouldn't be two high surrogates in a row, nor a high surrogate which isn't followed by a low - // surrogate. If this happens, keep the pending high surrogate as a stand-alone semi-invalid character - // (technically wrong, but expected by some applications, like Windows file names). - write32.call(dst, this.highSurrogate, offset); - offset += 4; - } - else { - // Create 32-bit value from high and low surrogates; - var codepoint = (((this.highSurrogate - 0xD800) << 10) | (code - 0xDC00)) + 0x10000; - - write32.call(dst, codepoint, offset); - offset += 4; - this.highSurrogate = 0; - - continue; +/** + * @generated MessageType for protobuf message github.actions.results.api.v1.CreateArtifactResponse + */ +exports.CreateArtifactResponse = new CreateArtifactResponse$Type(); +// @generated message type with reflection information, may provide speed optimized methods +class FinalizeArtifactRequest$Type extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.FinalizeArtifactRequest", [ + { no: 1, name: "workflow_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, + { no: 2, name: "workflow_job_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, + { no: 3, name: "name", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, + { no: 4, name: "size", kind: "scalar", T: 3 /*ScalarType.INT64*/ }, + { no: 5, name: "hash", kind: "message", T: () => wrappers_2.StringValue } + ]); + } + create(value) { + const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "", size: "0" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== undefined) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* string workflow_run_backend_id */ 1: + message.workflowRunBackendId = reader.string(); + break; + case /* string workflow_job_run_backend_id */ 2: + message.workflowJobRunBackendId = reader.string(); + break; + case /* string name */ 3: + message.name = reader.string(); + break; + case /* int64 size */ 4: + message.size = reader.int64().toString(); + break; + case /* google.protobuf.StringValue hash */ 5: + message.hash = wrappers_2.StringValue.internalBinaryRead(reader, reader.uint32(), options, message.hash); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } - - if (isHighSurrogate) - this.highSurrogate = code; - else { - // Even if the current character is a low surrogate, with no previous high surrogate, we'll - // encode it as a semi-invalid stand-alone character for the same reasons expressed above for - // unpaired high surrogates. - write32.call(dst, code, offset); - offset += 4; - this.highSurrogate = 0; - } + return message; + } + internalBinaryWrite(message, writer, options) { + /* string workflow_run_backend_id = 1; */ + if (message.workflowRunBackendId !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); + /* string workflow_job_run_backend_id = 2; */ + if (message.workflowJobRunBackendId !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); + /* string name = 3; */ + if (message.name !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.name); + /* int64 size = 4; */ + if (message.size !== "0") + writer.tag(4, runtime_1.WireType.Varint).int64(message.size); + /* google.protobuf.StringValue hash = 5; */ + if (message.hash) + wrappers_2.StringValue.internalBinaryWrite(message.hash, writer.tag(5, runtime_1.WireType.LengthDelimited).fork(), options).join(); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } - - if (offset < dst.length) - dst = dst.slice(0, offset); - - return dst; -}; - -Utf32Encoder.prototype.end = function() { - // Treat any leftover high surrogate as a semi-valid independent character. - if (!this.highSurrogate) - return; - - var buf = Buffer.alloc(4); - - if (this.isLE) - buf.writeUInt32LE(this.highSurrogate, 0); - else - buf.writeUInt32BE(this.highSurrogate, 0); - - this.highSurrogate = 0; - - return buf; -}; - -// -- Decoding - -function Utf32Decoder(options, codec) { - this.isLE = codec.isLE; - this.badChar = codec.iconv.defaultCharUnicode.charCodeAt(0); - this.overflow = []; } - -Utf32Decoder.prototype.write = function(src) { - if (src.length === 0) - return ''; - - var i = 0; - var codepoint = 0; - var dst = Buffer.alloc(src.length + 4); - var offset = 0; - var isLE = this.isLE; - var overflow = this.overflow; - var badChar = this.badChar; - - if (overflow.length > 0) { - for (; i < src.length && overflow.length < 4; i++) - overflow.push(src[i]); - - if (overflow.length === 4) { - // NOTE: codepoint is a signed int32 and can be negative. - // NOTE: We copied this block from below to help V8 optimize it (it works with array, not buffer). - if (isLE) { - codepoint = overflow[i] | (overflow[i+1] << 8) | (overflow[i+2] << 16) | (overflow[i+3] << 24); - } else { - codepoint = overflow[i+3] | (overflow[i+2] << 8) | (overflow[i+1] << 16) | (overflow[i] << 24); - } - overflow.length = 0; - - offset = _writeCodepoint(dst, offset, codepoint, badChar); - } +/** + * @generated MessageType for protobuf message github.actions.results.api.v1.FinalizeArtifactRequest + */ +exports.FinalizeArtifactRequest = new FinalizeArtifactRequest$Type(); +// @generated message type with reflection information, may provide speed optimized methods +class FinalizeArtifactResponse$Type extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.FinalizeArtifactResponse", [ + { no: 1, name: "ok", kind: "scalar", T: 8 /*ScalarType.BOOL*/ }, + { no: 2, name: "artifact_id", kind: "scalar", T: 3 /*ScalarType.INT64*/ } + ]); } - - // Main loop. Should be as optimized as possible. - for (; i < src.length - 3; i += 4) { - // NOTE: codepoint is a signed int32 and can be negative. - if (isLE) { - codepoint = src[i] | (src[i+1] << 8) | (src[i+2] << 16) | (src[i+3] << 24); - } else { - codepoint = src[i+3] | (src[i+2] << 8) | (src[i+1] << 16) | (src[i] << 24); + create(value) { + const message = { ok: false, artifactId: "0" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== undefined) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* bool ok */ 1: + message.ok = reader.bool(); + break; + case /* int64 artifact_id */ 2: + message.artifactId = reader.int64().toString(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } } - offset = _writeCodepoint(dst, offset, codepoint, badChar); + return message; } - - // Keep overflowing bytes. - for (; i < src.length; i++) { - overflow.push(src[i]); + internalBinaryWrite(message, writer, options) { + /* bool ok = 1; */ + if (message.ok !== false) + writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); + /* int64 artifact_id = 2; */ + if (message.artifactId !== "0") + writer.tag(2, runtime_1.WireType.Varint).int64(message.artifactId); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } - - return dst.slice(0, offset).toString('ucs2'); -}; - -function _writeCodepoint(dst, offset, codepoint, badChar) { - // NOTE: codepoint is signed int32 and can be negative. We keep it that way to help V8 with optimizations. - if (codepoint < 0 || codepoint > 0x10FFFF) { - // Not a valid Unicode codepoint - codepoint = badChar; - } - - // Ephemeral Planes: Write high surrogate. - if (codepoint >= 0x10000) { - codepoint -= 0x10000; - - var high = 0xD800 | (codepoint >> 10); - dst[offset++] = high & 0xff; - dst[offset++] = high >> 8; - - // Low surrogate is written below. - var codepoint = 0xDC00 | (codepoint & 0x3FF); - } - - // Write BMP char or low surrogate. - dst[offset++] = codepoint & 0xff; - dst[offset++] = codepoint >> 8; - - return offset; -}; - -Utf32Decoder.prototype.end = function() { - this.overflow.length = 0; -}; - -// == UTF-32 Auto codec ============================================================= -// Decoder chooses automatically from UTF-32LE and UTF-32BE using BOM and space-based heuristic. -// Defaults to UTF-32LE. http://en.wikipedia.org/wiki/UTF-32 -// Encoder/decoder default can be changed: iconv.decode(buf, 'utf32', {defaultEncoding: 'utf-32be'}); - -// Encoder prepends BOM (which can be overridden with (addBOM: false}). - -exports.utf32 = Utf32AutoCodec; -exports.ucs4 = 'utf32'; - -function Utf32AutoCodec(options, iconv) { - this.iconv = iconv; -} - -Utf32AutoCodec.prototype.encoder = Utf32AutoEncoder; -Utf32AutoCodec.prototype.decoder = Utf32AutoDecoder; - -// -- Encoding - -function Utf32AutoEncoder(options, codec) { - options = options || {}; - - if (options.addBOM === undefined) - options.addBOM = true; - - this.encoder = codec.iconv.getEncoder(options.defaultEncoding || 'utf-32le', options); -} - -Utf32AutoEncoder.prototype.write = function(str) { - return this.encoder.write(str); -}; - -Utf32AutoEncoder.prototype.end = function() { - return this.encoder.end(); -}; - -// -- Decoding - -function Utf32AutoDecoder(options, codec) { - this.decoder = null; - this.initialBufs = []; - this.initialBufsLen = 0; - this.options = options || {}; - this.iconv = codec.iconv; } - -Utf32AutoDecoder.prototype.write = function(buf) { - if (!this.decoder) { - // Codec is not chosen yet. Accumulate initial bytes. - this.initialBufs.push(buf); - this.initialBufsLen += buf.length; - - if (this.initialBufsLen < 32) // We need more bytes to use space heuristic (see below) - return ''; - - // We have enough bytes -> detect endianness. - var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); - - var resStr = ''; - for (var i = 0; i < this.initialBufs.length; i++) - resStr += this.decoder.write(this.initialBufs[i]); - - this.initialBufs.length = this.initialBufsLen = 0; - return resStr; +/** + * @generated MessageType for protobuf message github.actions.results.api.v1.FinalizeArtifactResponse + */ +exports.FinalizeArtifactResponse = new FinalizeArtifactResponse$Type(); +// @generated message type with reflection information, may provide speed optimized methods +class ListArtifactsRequest$Type extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.ListArtifactsRequest", [ + { no: 1, name: "workflow_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, + { no: 2, name: "workflow_job_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, + { no: 3, name: "name_filter", kind: "message", T: () => wrappers_2.StringValue }, + { no: 4, name: "id_filter", kind: "message", T: () => wrappers_1.Int64Value } + ]); } - - return this.decoder.write(buf); -}; - -Utf32AutoDecoder.prototype.end = function() { - if (!this.decoder) { - var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); - - var resStr = ''; - for (var i = 0; i < this.initialBufs.length; i++) - resStr += this.decoder.write(this.initialBufs[i]); - - var trail = this.decoder.end(); - if (trail) - resStr += trail; - - this.initialBufs.length = this.initialBufsLen = 0; - return resStr; + create(value) { + const message = { workflowRunBackendId: "", workflowJobRunBackendId: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== undefined) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; } - - return this.decoder.end(); -}; - -function detectEncoding(bufs, defaultEncoding) { - var b = []; - var charsProcessed = 0; - var invalidLE = 0, invalidBE = 0; // Number of invalid chars when decoded as LE or BE. - var bmpCharsLE = 0, bmpCharsBE = 0; // Number of BMP chars when decoded as LE or BE. - - outer_loop: - for (var i = 0; i < bufs.length; i++) { - var buf = bufs[i]; - for (var j = 0; j < buf.length; j++) { - b.push(buf[j]); - if (b.length === 4) { - if (charsProcessed === 0) { - // Check BOM first. - if (b[0] === 0xFF && b[1] === 0xFE && b[2] === 0 && b[3] === 0) { - return 'utf-32le'; - } - if (b[0] === 0 && b[1] === 0 && b[2] === 0xFE && b[3] === 0xFF) { - return 'utf-32be'; - } - } - - if (b[0] !== 0 || b[1] > 0x10) invalidBE++; - if (b[3] !== 0 || b[2] > 0x10) invalidLE++; - - if (b[0] === 0 && b[1] === 0 && (b[2] !== 0 || b[3] !== 0)) bmpCharsBE++; - if ((b[0] !== 0 || b[1] !== 0) && b[2] === 0 && b[3] === 0) bmpCharsLE++; - - b.length = 0; - charsProcessed++; - - if (charsProcessed >= 100) { - break outer_loop; - } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* string workflow_run_backend_id */ 1: + message.workflowRunBackendId = reader.string(); + break; + case /* string workflow_job_run_backend_id */ 2: + message.workflowJobRunBackendId = reader.string(); + break; + case /* google.protobuf.StringValue name_filter */ 3: + message.nameFilter = wrappers_2.StringValue.internalBinaryRead(reader, reader.uint32(), options, message.nameFilter); + break; + case /* google.protobuf.Int64Value id_filter */ 4: + message.idFilter = wrappers_1.Int64Value.internalBinaryRead(reader, reader.uint32(), options, message.idFilter); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } + return message; + } + internalBinaryWrite(message, writer, options) { + /* string workflow_run_backend_id = 1; */ + if (message.workflowRunBackendId !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); + /* string workflow_job_run_backend_id = 2; */ + if (message.workflowJobRunBackendId !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); + /* google.protobuf.StringValue name_filter = 3; */ + if (message.nameFilter) + wrappers_2.StringValue.internalBinaryWrite(message.nameFilter, writer.tag(3, runtime_1.WireType.LengthDelimited).fork(), options).join(); + /* google.protobuf.Int64Value id_filter = 4; */ + if (message.idFilter) + wrappers_1.Int64Value.internalBinaryWrite(message.idFilter, writer.tag(4, runtime_1.WireType.LengthDelimited).fork(), options).join(); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } - - // Make decisions. - if (bmpCharsBE - invalidBE > bmpCharsLE - invalidLE) return 'utf-32be'; - if (bmpCharsBE - invalidBE < bmpCharsLE - invalidLE) return 'utf-32le'; - - // Couldn't decide (likely all zeros or not enough data). - return defaultEncoding || 'utf-32le'; -} - - -/***/ }), - -/***/ 49451: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -var Buffer = (__nccwpck_require__(97084).Buffer); - -// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152 -// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3 - -exports.utf7 = Utf7Codec; -exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7 -function Utf7Codec(codecOptions, iconv) { - this.iconv = iconv; -}; - -Utf7Codec.prototype.encoder = Utf7Encoder; -Utf7Codec.prototype.decoder = Utf7Decoder; -Utf7Codec.prototype.bomAware = true; - - -// -- Encoding - -var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; - -function Utf7Encoder(options, codec) { - this.iconv = codec.iconv; -} - -Utf7Encoder.prototype.write = function(str) { - // Naive implementation. - // Non-direct chars are encoded as "+-"; single "+" char is encoded as "+-". - return Buffer.from(str.replace(nonDirectChars, function(chunk) { - return "+" + (chunk === '+' ? '' : - this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) - + "-"; - }.bind(this))); -} - -Utf7Encoder.prototype.end = function() { -} - - -// -- Decoding - -function Utf7Decoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = ''; } - -var base64Regex = /[A-Za-z0-9\/+]/; -var base64Chars = []; -for (var i = 0; i < 256; i++) - base64Chars[i] = base64Regex.test(String.fromCharCode(i)); - -var plusChar = '+'.charCodeAt(0), - minusChar = '-'.charCodeAt(0), - andChar = '&'.charCodeAt(0); - -Utf7Decoder.prototype.write = function(buf) { - var res = "", lastI = 0, - inBase64 = this.inBase64, - base64Accum = this.base64Accum; - - // The decoder is more involved as we must handle chunks in stream. - - for (var i = 0; i < buf.length; i++) { - if (!inBase64) { // We're in direct mode. - // Write direct chars until '+' - if (buf[i] == plusChar) { - res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. - lastI = i+1; - inBase64 = true; - } - } else { // We decode base64. - if (!base64Chars[buf[i]]) { // Base64 ended. - if (i == lastI && buf[i] == minusChar) {// "+-" -> "+" - res += "+"; - } else { - var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i), "ascii"); - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); - } - - if (buf[i] != minusChar) // Minus is absorbed after base64. - i--; - - lastI = i+1; - inBase64 = false; - base64Accum = ''; +/** + * @generated MessageType for protobuf message github.actions.results.api.v1.ListArtifactsRequest + */ +exports.ListArtifactsRequest = new ListArtifactsRequest$Type(); +// @generated message type with reflection information, may provide speed optimized methods +class ListArtifactsResponse$Type extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.ListArtifactsResponse", [ + { no: 1, name: "artifacts", kind: "message", repeat: 1 /*RepeatType.PACKED*/, T: () => exports.ListArtifactsResponse_MonolithArtifact } + ]); + } + create(value) { + const message = { artifacts: [] }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== undefined) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* repeated github.actions.results.api.v1.ListArtifactsResponse.MonolithArtifact artifacts */ 1: + message.artifacts.push(exports.ListArtifactsResponse_MonolithArtifact.internalBinaryRead(reader, reader.uint32(), options)); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } + return message; } - - if (!inBase64) { - res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. - } else { - var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii"); - - var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. - base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. - b64str = b64str.slice(0, canBeDecoded); - - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + internalBinaryWrite(message, writer, options) { + /* repeated github.actions.results.api.v1.ListArtifactsResponse.MonolithArtifact artifacts = 1; */ + for (let i = 0; i < message.artifacts.length; i++) + exports.ListArtifactsResponse_MonolithArtifact.internalBinaryWrite(message.artifacts[i], writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } - - this.inBase64 = inBase64; - this.base64Accum = base64Accum; - - return res; -} - -Utf7Decoder.prototype.end = function() { - var res = ""; - if (this.inBase64 && this.base64Accum.length > 0) - res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); - - this.inBase64 = false; - this.base64Accum = ''; - return res; -} - - -// UTF-7-IMAP codec. -// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3) -// Differences: -// * Base64 part is started by "&" instead of "+" -// * Direct characters are 0x20-0x7E, except "&" (0x26) -// * In Base64, "," is used instead of "/" -// * Base64 must not be used to represent direct characters. -// * No implicit shift back from Base64 (should always end with '-') -// * String must end in non-shifted position. -// * "-&" while in base64 is not allowed. - - -exports.utf7imap = Utf7IMAPCodec; -function Utf7IMAPCodec(codecOptions, iconv) { - this.iconv = iconv; -}; - -Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; -Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; -Utf7IMAPCodec.prototype.bomAware = true; - - -// -- Encoding - -function Utf7IMAPEncoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = Buffer.alloc(6); - this.base64AccumIdx = 0; } - -Utf7IMAPEncoder.prototype.write = function(str) { - var inBase64 = this.inBase64, - base64Accum = this.base64Accum, - base64AccumIdx = this.base64AccumIdx, - buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0; - - for (var i = 0; i < str.length; i++) { - var uChar = str.charCodeAt(i); - if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'. - if (inBase64) { - if (base64AccumIdx > 0) { - bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); - base64AccumIdx = 0; - } - - buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. - inBase64 = false; - } - - if (!inBase64) { - buf[bufIdx++] = uChar; // Write direct character - - if (uChar === andChar) // Ampersand -> '&-' - buf[bufIdx++] = minusChar; - } - - } else { // Non-direct character - if (!inBase64) { - buf[bufIdx++] = andChar; // Write '&', then go to base64 mode. - inBase64 = true; - } - if (inBase64) { - base64Accum[base64AccumIdx++] = uChar >> 8; - base64Accum[base64AccumIdx++] = uChar & 0xFF; - - if (base64AccumIdx == base64Accum.length) { - bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx); - base64AccumIdx = 0; - } +/** + * @generated MessageType for protobuf message github.actions.results.api.v1.ListArtifactsResponse + */ +exports.ListArtifactsResponse = new ListArtifactsResponse$Type(); +// @generated message type with reflection information, may provide speed optimized methods +class ListArtifactsResponse_MonolithArtifact$Type extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.ListArtifactsResponse.MonolithArtifact", [ + { no: 1, name: "workflow_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, + { no: 2, name: "workflow_job_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, + { no: 3, name: "database_id", kind: "scalar", T: 3 /*ScalarType.INT64*/ }, + { no: 4, name: "name", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, + { no: 5, name: "size", kind: "scalar", T: 3 /*ScalarType.INT64*/ }, + { no: 6, name: "created_at", kind: "message", T: () => timestamp_1.Timestamp } + ]); + } + create(value) { + const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", databaseId: "0", name: "", size: "0" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== undefined) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* string workflow_run_backend_id */ 1: + message.workflowRunBackendId = reader.string(); + break; + case /* string workflow_job_run_backend_id */ 2: + message.workflowJobRunBackendId = reader.string(); + break; + case /* int64 database_id */ 3: + message.databaseId = reader.int64().toString(); + break; + case /* string name */ 4: + message.name = reader.string(); + break; + case /* int64 size */ 5: + message.size = reader.int64().toString(); + break; + case /* google.protobuf.Timestamp created_at */ 6: + message.createdAt = timestamp_1.Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.createdAt); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } + return message; } - - this.inBase64 = inBase64; - this.base64AccumIdx = base64AccumIdx; - - return buf.slice(0, bufIdx); -} - -Utf7IMAPEncoder.prototype.end = function() { - var buf = Buffer.alloc(10), bufIdx = 0; - if (this.inBase64) { - if (this.base64AccumIdx > 0) { - bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); - this.base64AccumIdx = 0; - } - - buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. - this.inBase64 = false; + internalBinaryWrite(message, writer, options) { + /* string workflow_run_backend_id = 1; */ + if (message.workflowRunBackendId !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); + /* string workflow_job_run_backend_id = 2; */ + if (message.workflowJobRunBackendId !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); + /* int64 database_id = 3; */ + if (message.databaseId !== "0") + writer.tag(3, runtime_1.WireType.Varint).int64(message.databaseId); + /* string name = 4; */ + if (message.name !== "") + writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.name); + /* int64 size = 5; */ + if (message.size !== "0") + writer.tag(5, runtime_1.WireType.Varint).int64(message.size); + /* google.protobuf.Timestamp created_at = 6; */ + if (message.createdAt) + timestamp_1.Timestamp.internalBinaryWrite(message.createdAt, writer.tag(6, runtime_1.WireType.LengthDelimited).fork(), options).join(); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } - - return buf.slice(0, bufIdx); -} - - -// -- Decoding - -function Utf7IMAPDecoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = ''; } - -var base64IMAPChars = base64Chars.slice(); -base64IMAPChars[','.charCodeAt(0)] = true; - -Utf7IMAPDecoder.prototype.write = function(buf) { - var res = "", lastI = 0, - inBase64 = this.inBase64, - base64Accum = this.base64Accum; - - // The decoder is more involved as we must handle chunks in stream. - // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end). - - for (var i = 0; i < buf.length; i++) { - if (!inBase64) { // We're in direct mode. - // Write direct chars until '&' - if (buf[i] == andChar) { - res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. - lastI = i+1; - inBase64 = true; - } - } else { // We decode base64. - if (!base64IMAPChars[buf[i]]) { // Base64 ended. - if (i == lastI && buf[i] == minusChar) { // "&-" -> "&" - res += "&"; - } else { - var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i), "ascii").replace(/,/g, '/'); - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); - } - - if (buf[i] != minusChar) // Minus may be absorbed after base64. - i--; - - lastI = i+1; - inBase64 = false; - base64Accum = ''; +/** + * @generated MessageType for protobuf message github.actions.results.api.v1.ListArtifactsResponse.MonolithArtifact + */ +exports.ListArtifactsResponse_MonolithArtifact = new ListArtifactsResponse_MonolithArtifact$Type(); +// @generated message type with reflection information, may provide speed optimized methods +class GetSignedArtifactURLRequest$Type extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.GetSignedArtifactURLRequest", [ + { no: 1, name: "workflow_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, + { no: 2, name: "workflow_job_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, + { no: 3, name: "name", kind: "scalar", T: 9 /*ScalarType.STRING*/ } + ]); + } + create(value) { + const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== undefined) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; + } + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* string workflow_run_backend_id */ 1: + message.workflowRunBackendId = reader.string(); + break; + case /* string workflow_job_run_backend_id */ 2: + message.workflowJobRunBackendId = reader.string(); + break; + case /* string name */ 3: + message.name = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } + return message; } - - if (!inBase64) { - res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. - } else { - var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii").replace(/,/g, '/'); - - var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. - base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. - b64str = b64str.slice(0, canBeDecoded); - - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + internalBinaryWrite(message, writer, options) { + /* string workflow_run_backend_id = 1; */ + if (message.workflowRunBackendId !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); + /* string workflow_job_run_backend_id = 2; */ + if (message.workflowJobRunBackendId !== "") + writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); + /* string name = 3; */ + if (message.name !== "") + writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.name); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } - - this.inBase64 = inBase64; - this.base64Accum = base64Accum; - - return res; -} - -Utf7IMAPDecoder.prototype.end = function() { - var res = ""; - if (this.inBase64 && this.base64Accum.length > 0) - res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); - - this.inBase64 = false; - this.base64Accum = ''; - return res; -} - - - - -/***/ }), - -/***/ 88006: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -var BOMChar = '\uFEFF'; - -exports.PrependBOM = PrependBOMWrapper -function PrependBOMWrapper(encoder, options) { - this.encoder = encoder; - this.addBOM = true; } - -PrependBOMWrapper.prototype.write = function(str) { - if (this.addBOM) { - str = BOMChar + str; - this.addBOM = false; +/** + * @generated MessageType for protobuf message github.actions.results.api.v1.GetSignedArtifactURLRequest + */ +exports.GetSignedArtifactURLRequest = new GetSignedArtifactURLRequest$Type(); +// @generated message type with reflection information, may provide speed optimized methods +class GetSignedArtifactURLResponse$Type extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.GetSignedArtifactURLResponse", [ + { no: 1, name: "signed_url", kind: "scalar", T: 9 /*ScalarType.STRING*/ } + ]); } - - return this.encoder.write(str); -} - -PrependBOMWrapper.prototype.end = function() { - return this.encoder.end(); -} - - -//------------------------------------------------------------------------------ - -exports.StripBOM = StripBOMWrapper; -function StripBOMWrapper(decoder, options) { - this.decoder = decoder; - this.pass = false; - this.options = options || {}; -} - -StripBOMWrapper.prototype.write = function(buf) { - var res = this.decoder.write(buf); - if (this.pass || !res) - return res; - - if (res[0] === BOMChar) { - res = res.slice(1); - if (typeof this.options.stripBOM === 'function') - this.options.stripBOM(); + create(value) { + const message = { signedUrl: "" }; + globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); + if (value !== undefined) + (0, runtime_3.reflectionMergePartial)(this, message, value); + return message; } - - this.pass = true; - return res; -} - -StripBOMWrapper.prototype.end = function() { - return this.decoder.end(); -} - - - -/***/ }), - -/***/ 85848: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Buffer = (__nccwpck_require__(97084).Buffer); - -var bomHandling = __nccwpck_require__(88006), - iconv = module.exports; - -// All codecs and aliases are kept here, keyed by encoding name/alias. -// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`. -iconv.encodings = null; - -// Characters emitted in case of error. -iconv.defaultCharUnicode = '�'; -iconv.defaultCharSingleByte = '?'; - -// Public API. -iconv.encode = function encode(str, encoding, options) { - str = "" + (str || ""); // Ensure string. - - var encoder = iconv.getEncoder(encoding, options); - - var res = encoder.write(str); - var trail = encoder.end(); - - return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; -} - -iconv.decode = function decode(buf, encoding, options) { - if (typeof buf === 'string') { - if (!iconv.skipDecodeWarning) { - console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding'); - iconv.skipDecodeWarning = true; + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case /* string signed_url */ 1: + message.signedUrl = reader.string(); + break; + default: + let u = options.readUnknownField; + if (u === "throw") + throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + } } - - buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer. + return message; } - - var decoder = iconv.getDecoder(encoding, options); - - var res = decoder.write(buf); - var trail = decoder.end(); - - return trail ? (res + trail) : res; -} - -iconv.encodingExists = function encodingExists(enc) { - try { - iconv.getCodec(enc); - return true; - } catch (e) { - return false; + internalBinaryWrite(message, writer, options) { + /* string signed_url = 1; */ + if (message.signedUrl !== "") + writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.signedUrl); + let u = options.writeUnknownFields; + if (u !== false) + (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); + return writer; } } +/** + * @generated MessageType for protobuf message github.actions.results.api.v1.GetSignedArtifactURLResponse + */ +exports.GetSignedArtifactURLResponse = new GetSignedArtifactURLResponse$Type(); +/** + * @generated ServiceType for protobuf service github.actions.results.api.v1.ArtifactService + */ +exports.ArtifactService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.ArtifactService", [ + { name: "CreateArtifact", options: {}, I: exports.CreateArtifactRequest, O: exports.CreateArtifactResponse }, + { name: "FinalizeArtifact", options: {}, I: exports.FinalizeArtifactRequest, O: exports.FinalizeArtifactResponse }, + { name: "ListArtifacts", options: {}, I: exports.ListArtifactsRequest, O: exports.ListArtifactsResponse }, + { name: "GetSignedArtifactURL", options: {}, I: exports.GetSignedArtifactURLRequest, O: exports.GetSignedArtifactURLResponse } +]); +//# sourceMappingURL=artifact.js.map -// Legacy aliases to convert functions -iconv.toEncoding = iconv.encode; -iconv.fromEncoding = iconv.decode; - -// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache. -iconv._codecDataCache = {}; -iconv.getCodec = function getCodec(encoding) { - if (!iconv.encodings) - iconv.encodings = __nccwpck_require__(16386); // Lazy load all encoding definitions. - - // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. - var enc = iconv._canonicalizeEncoding(encoding); - - // Traverse iconv.encodings to find actual codec. - var codecOptions = {}; - while (true) { - var codec = iconv._codecDataCache[enc]; - if (codec) - return codec; +/***/ }), - var codecDef = iconv.encodings[enc]; +/***/ 63077: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - switch (typeof codecDef) { - case "string": // Direct alias to other encoding. - enc = codecDef; - break; +"use strict"; - case "object": // Alias with options. Can be layered. - for (var key in codecDef) - codecOptions[key] = codecDef[key]; - - if (!codecOptions.encodingName) - codecOptions.encodingName = enc; - - enc = codecDef.type; - break; - - case "function": // Codec itself. - if (!codecOptions.encodingName) - codecOptions.encodingName = enc; - - // The codec function must load all tables and return object with .encoder and .decoder methods. - // It'll be called only once (for each different options object). - codec = new codecDef(codecOptions, iconv); - - iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. - return codec; - - default: - throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); - } +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createArtifactServiceServer = exports.ArtifactServiceMethodList = exports.ArtifactServiceMethod = exports.ArtifactServiceClientProtobuf = exports.ArtifactServiceClientJSON = void 0; +const twirp_ts_1 = __nccwpck_require__(66465); +const artifact_1 = __nccwpck_require__(58178); +class ArtifactServiceClientJSON { + constructor(rpc) { + this.rpc = rpc; + this.CreateArtifact.bind(this); + this.FinalizeArtifact.bind(this); + this.ListArtifacts.bind(this); + this.GetSignedArtifactURL.bind(this); + } + CreateArtifact(request) { + const data = artifact_1.CreateArtifactRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false, + }); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "CreateArtifact", "application/json", data); + return promise.then((data) => artifact_1.CreateArtifactResponse.fromJson(data, { + ignoreUnknownFields: true, + })); + } + FinalizeArtifact(request) { + const data = artifact_1.FinalizeArtifactRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false, + }); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "FinalizeArtifact", "application/json", data); + return promise.then((data) => artifact_1.FinalizeArtifactResponse.fromJson(data, { + ignoreUnknownFields: true, + })); + } + ListArtifacts(request) { + const data = artifact_1.ListArtifactsRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false, + }); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "ListArtifacts", "application/json", data); + return promise.then((data) => artifact_1.ListArtifactsResponse.fromJson(data, { ignoreUnknownFields: true })); + } + GetSignedArtifactURL(request) { + const data = artifact_1.GetSignedArtifactURLRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false, + }); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "GetSignedArtifactURL", "application/json", data); + return promise.then((data) => artifact_1.GetSignedArtifactURLResponse.fromJson(data, { + ignoreUnknownFields: true, + })); } } - -iconv._canonicalizeEncoding = function(encoding) { - // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. - return (''+encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, ""); +exports.ArtifactServiceClientJSON = ArtifactServiceClientJSON; +class ArtifactServiceClientProtobuf { + constructor(rpc) { + this.rpc = rpc; + this.CreateArtifact.bind(this); + this.FinalizeArtifact.bind(this); + this.ListArtifacts.bind(this); + this.GetSignedArtifactURL.bind(this); + } + CreateArtifact(request) { + const data = artifact_1.CreateArtifactRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "CreateArtifact", "application/protobuf", data); + return promise.then((data) => artifact_1.CreateArtifactResponse.fromBinary(data)); + } + FinalizeArtifact(request) { + const data = artifact_1.FinalizeArtifactRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "FinalizeArtifact", "application/protobuf", data); + return promise.then((data) => artifact_1.FinalizeArtifactResponse.fromBinary(data)); + } + ListArtifacts(request) { + const data = artifact_1.ListArtifactsRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "ListArtifacts", "application/protobuf", data); + return promise.then((data) => artifact_1.ListArtifactsResponse.fromBinary(data)); + } + GetSignedArtifactURL(request) { + const data = artifact_1.GetSignedArtifactURLRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "GetSignedArtifactURL", "application/protobuf", data); + return promise.then((data) => artifact_1.GetSignedArtifactURLResponse.fromBinary(data)); + } } - -iconv.getEncoder = function getEncoder(encoding, options) { - var codec = iconv.getCodec(encoding), - encoder = new codec.encoder(options, codec); - - if (codec.bomAware && options && options.addBOM) - encoder = new bomHandling.PrependBOM(encoder, options); - - return encoder; +exports.ArtifactServiceClientProtobuf = ArtifactServiceClientProtobuf; +var ArtifactServiceMethod; +(function (ArtifactServiceMethod) { + ArtifactServiceMethod["CreateArtifact"] = "CreateArtifact"; + ArtifactServiceMethod["FinalizeArtifact"] = "FinalizeArtifact"; + ArtifactServiceMethod["ListArtifacts"] = "ListArtifacts"; + ArtifactServiceMethod["GetSignedArtifactURL"] = "GetSignedArtifactURL"; +})(ArtifactServiceMethod || (exports.ArtifactServiceMethod = ArtifactServiceMethod = {})); +exports.ArtifactServiceMethodList = [ + ArtifactServiceMethod.CreateArtifact, + ArtifactServiceMethod.FinalizeArtifact, + ArtifactServiceMethod.ListArtifacts, + ArtifactServiceMethod.GetSignedArtifactURL, +]; +function createArtifactServiceServer(service) { + return new twirp_ts_1.TwirpServer({ + service, + packageName: "github.actions.results.api.v1", + serviceName: "ArtifactService", + methodList: exports.ArtifactServiceMethodList, + matchRoute: matchArtifactServiceRoute, + }); } - -iconv.getDecoder = function getDecoder(encoding, options) { - var codec = iconv.getCodec(encoding), - decoder = new codec.decoder(options, codec); - - if (codec.bomAware && !(options && options.stripBOM === false)) - decoder = new bomHandling.StripBOM(decoder, options); - - return decoder; +exports.createArtifactServiceServer = createArtifactServiceServer; +function matchArtifactServiceRoute(method, events) { + switch (method) { + case "CreateArtifact": + return (ctx, service, data, interceptors) => __awaiter(this, void 0, void 0, function* () { + ctx = Object.assign(Object.assign({}, ctx), { methodName: "CreateArtifact" }); + yield events.onMatch(ctx); + return handleArtifactServiceCreateArtifactRequest(ctx, service, data, interceptors); + }); + case "FinalizeArtifact": + return (ctx, service, data, interceptors) => __awaiter(this, void 0, void 0, function* () { + ctx = Object.assign(Object.assign({}, ctx), { methodName: "FinalizeArtifact" }); + yield events.onMatch(ctx); + return handleArtifactServiceFinalizeArtifactRequest(ctx, service, data, interceptors); + }); + case "ListArtifacts": + return (ctx, service, data, interceptors) => __awaiter(this, void 0, void 0, function* () { + ctx = Object.assign(Object.assign({}, ctx), { methodName: "ListArtifacts" }); + yield events.onMatch(ctx); + return handleArtifactServiceListArtifactsRequest(ctx, service, data, interceptors); + }); + case "GetSignedArtifactURL": + return (ctx, service, data, interceptors) => __awaiter(this, void 0, void 0, function* () { + ctx = Object.assign(Object.assign({}, ctx), { methodName: "GetSignedArtifactURL" }); + yield events.onMatch(ctx); + return handleArtifactServiceGetSignedArtifactURLRequest(ctx, service, data, interceptors); + }); + default: + events.onNotFound(); + const msg = `no handler found`; + throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.BadRoute, msg); + } } - -// Streaming API -// NOTE: Streaming API naturally depends on 'stream' module from Node.js. Unfortunately in browser environments this module can add -// up to 100Kb to the output bundle. To avoid unnecessary code bloat, we don't enable Streaming API in browser by default. -// If you would like to enable it explicitly, please add the following code to your app: -// > iconv.enableStreamingAPI(require('stream')); -iconv.enableStreamingAPI = function enableStreamingAPI(stream_module) { - if (iconv.supportsStreams) - return; - - // Dependency-inject stream module to create IconvLite stream classes. - var streams = __nccwpck_require__(58783)(stream_module); - - // Not public API yet, but expose the stream classes. - iconv.IconvLiteEncoderStream = streams.IconvLiteEncoderStream; - iconv.IconvLiteDecoderStream = streams.IconvLiteDecoderStream; - - // Streaming API. - iconv.encodeStream = function encodeStream(encoding, options) { - return new iconv.IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); +function handleArtifactServiceCreateArtifactRequest(ctx, service, data, interceptors) { + switch (ctx.contentType) { + case twirp_ts_1.TwirpContentType.JSON: + return handleArtifactServiceCreateArtifactJSON(ctx, service, data, interceptors); + case twirp_ts_1.TwirpContentType.Protobuf: + return handleArtifactServiceCreateArtifactProtobuf(ctx, service, data, interceptors); + default: + const msg = "unexpected Content-Type"; + throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.BadRoute, msg); } - - iconv.decodeStream = function decodeStream(encoding, options) { - return new iconv.IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); +} +function handleArtifactServiceFinalizeArtifactRequest(ctx, service, data, interceptors) { + switch (ctx.contentType) { + case twirp_ts_1.TwirpContentType.JSON: + return handleArtifactServiceFinalizeArtifactJSON(ctx, service, data, interceptors); + case twirp_ts_1.TwirpContentType.Protobuf: + return handleArtifactServiceFinalizeArtifactProtobuf(ctx, service, data, interceptors); + default: + const msg = "unexpected Content-Type"; + throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.BadRoute, msg); } - - iconv.supportsStreams = true; } - -// Enable Streaming API automatically if 'stream' module is available and non-empty (the majority of environments). -var stream_module; -try { - stream_module = __nccwpck_require__(12781); -} catch (e) {} - -if (stream_module && stream_module.Transform) { - iconv.enableStreamingAPI(stream_module); - -} else { - // In rare cases where 'stream' module is not available by default, throw a helpful exception. - iconv.encodeStream = iconv.decodeStream = function() { - throw new Error("iconv-lite Streaming API is not enabled. Use iconv.enableStreamingAPI(require('stream')); to enable it."); - }; +function handleArtifactServiceListArtifactsRequest(ctx, service, data, interceptors) { + switch (ctx.contentType) { + case twirp_ts_1.TwirpContentType.JSON: + return handleArtifactServiceListArtifactsJSON(ctx, service, data, interceptors); + case twirp_ts_1.TwirpContentType.Protobuf: + return handleArtifactServiceListArtifactsProtobuf(ctx, service, data, interceptors); + default: + const msg = "unexpected Content-Type"; + throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.BadRoute, msg); + } } - -if (false) {} - - -/***/ }), - -/***/ 58783: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Buffer = (__nccwpck_require__(97084).Buffer); - -// NOTE: Due to 'stream' module being pretty large (~100Kb, significant in browser environments), -// we opt to dependency-inject it instead of creating a hard dependency. -module.exports = function(stream_module) { - var Transform = stream_module.Transform; - - // == Encoder stream ======================================================= - - function IconvLiteEncoderStream(conv, options) { - this.conv = conv; - options = options || {}; - options.decodeStrings = false; // We accept only strings, so we don't need to decode them. - Transform.call(this, options); +function handleArtifactServiceGetSignedArtifactURLRequest(ctx, service, data, interceptors) { + switch (ctx.contentType) { + case twirp_ts_1.TwirpContentType.JSON: + return handleArtifactServiceGetSignedArtifactURLJSON(ctx, service, data, interceptors); + case twirp_ts_1.TwirpContentType.Protobuf: + return handleArtifactServiceGetSignedArtifactURLProtobuf(ctx, service, data, interceptors); + default: + const msg = "unexpected Content-Type"; + throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.BadRoute, msg); } - - IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteEncoderStream } - }); - - IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { - if (typeof chunk != 'string') - return done(new Error("Iconv encoding stream needs strings as its input.")); +} +function handleArtifactServiceCreateArtifactJSON(ctx, service, data, interceptors) { + return __awaiter(this, void 0, void 0, function* () { + let request; + let response; try { - var res = this.conv.write(chunk); - if (res && res.length) this.push(res); - done(); + const body = JSON.parse(data.toString() || "{}"); + request = artifact_1.CreateArtifactRequest.fromJson(body, { + ignoreUnknownFields: true, + }); } catch (e) { - done(e); + if (e instanceof Error) { + const msg = "the json request could not be decoded"; + throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true); + } } - } - - IconvLiteEncoderStream.prototype._flush = function(done) { + if (interceptors && interceptors.length > 0) { + const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors); + response = yield interceptor(ctx, request, (ctx, inputReq) => { + return service.CreateArtifact(ctx, inputReq); + }); + } + else { + response = yield service.CreateArtifact(ctx, request); + } + return JSON.stringify(artifact_1.CreateArtifactResponse.toJson(response, { + useProtoFieldName: true, + emitDefaultValues: false, + })); + }); +} +function handleArtifactServiceFinalizeArtifactJSON(ctx, service, data, interceptors) { + return __awaiter(this, void 0, void 0, function* () { + let request; + let response; try { - var res = this.conv.end(); - if (res && res.length) this.push(res); - done(); + const body = JSON.parse(data.toString() || "{}"); + request = artifact_1.FinalizeArtifactRequest.fromJson(body, { + ignoreUnknownFields: true, + }); } catch (e) { - done(e); + if (e instanceof Error) { + const msg = "the json request could not be decoded"; + throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true); + } } - } - - IconvLiteEncoderStream.prototype.collect = function(cb) { - var chunks = []; - this.on('error', cb); - this.on('data', function(chunk) { chunks.push(chunk); }); - this.on('end', function() { - cb(null, Buffer.concat(chunks)); - }); - return this; - } - - - // == Decoder stream ======================================================= - - function IconvLiteDecoderStream(conv, options) { - this.conv = conv; - options = options || {}; - options.encoding = this.encoding = 'utf8'; // We output strings. - Transform.call(this, options); - } - - IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteDecoderStream } + if (interceptors && interceptors.length > 0) { + const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors); + response = yield interceptor(ctx, request, (ctx, inputReq) => { + return service.FinalizeArtifact(ctx, inputReq); + }); + } + else { + response = yield service.FinalizeArtifact(ctx, request); + } + return JSON.stringify(artifact_1.FinalizeArtifactResponse.toJson(response, { + useProtoFieldName: true, + emitDefaultValues: false, + })); }); - - IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { - if (!Buffer.isBuffer(chunk) && !(chunk instanceof Uint8Array)) - return done(new Error("Iconv decoding stream needs buffers as its input.")); +} +function handleArtifactServiceListArtifactsJSON(ctx, service, data, interceptors) { + return __awaiter(this, void 0, void 0, function* () { + let request; + let response; try { - var res = this.conv.write(chunk); - if (res && res.length) this.push(res, this.encoding); - done(); + const body = JSON.parse(data.toString() || "{}"); + request = artifact_1.ListArtifactsRequest.fromJson(body, { + ignoreUnknownFields: true, + }); } catch (e) { - done(e); + if (e instanceof Error) { + const msg = "the json request could not be decoded"; + throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true); + } } - } - - IconvLiteDecoderStream.prototype._flush = function(done) { + if (interceptors && interceptors.length > 0) { + const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors); + response = yield interceptor(ctx, request, (ctx, inputReq) => { + return service.ListArtifacts(ctx, inputReq); + }); + } + else { + response = yield service.ListArtifacts(ctx, request); + } + return JSON.stringify(artifact_1.ListArtifactsResponse.toJson(response, { + useProtoFieldName: true, + emitDefaultValues: false, + })); + }); +} +function handleArtifactServiceGetSignedArtifactURLJSON(ctx, service, data, interceptors) { + return __awaiter(this, void 0, void 0, function* () { + let request; + let response; try { - var res = this.conv.end(); - if (res && res.length) this.push(res, this.encoding); - done(); + const body = JSON.parse(data.toString() || "{}"); + request = artifact_1.GetSignedArtifactURLRequest.fromJson(body, { + ignoreUnknownFields: true, + }); } catch (e) { - done(e); + if (e instanceof Error) { + const msg = "the json request could not be decoded"; + throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true); + } } - } - - IconvLiteDecoderStream.prototype.collect = function(cb) { - var res = ''; - this.on('error', cb); - this.on('data', function(chunk) { res += chunk; }); - this.on('end', function() { - cb(null, res); - }); - return this; - } - - return { - IconvLiteEncoderStream: IconvLiteEncoderStream, - IconvLiteDecoderStream: IconvLiteDecoderStream, - }; -}; - - -/***/ }), - -/***/ 97084: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/* eslint-disable node/no-deprecated-api */ - - - -var buffer = __nccwpck_require__(14300) -var Buffer = buffer.Buffer - -var safer = {} - -var key - -for (key in buffer) { - if (!buffer.hasOwnProperty(key)) continue - if (key === 'SlowBuffer' || key === 'Buffer') continue - safer[key] = buffer[key] -} - -var Safer = safer.Buffer = {} -for (key in Buffer) { - if (!Buffer.hasOwnProperty(key)) continue - if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue - Safer[key] = Buffer[key] + if (interceptors && interceptors.length > 0) { + const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors); + response = yield interceptor(ctx, request, (ctx, inputReq) => { + return service.GetSignedArtifactURL(ctx, inputReq); + }); + } + else { + response = yield service.GetSignedArtifactURL(ctx, request); + } + return JSON.stringify(artifact_1.GetSignedArtifactURLResponse.toJson(response, { + useProtoFieldName: true, + emitDefaultValues: false, + })); + }); } - -safer.Buffer.prototype = Buffer.prototype - -if (!Safer.from || Safer.from === Uint8Array.from) { - Safer.from = function (value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value) - } - if (value && typeof value.length === 'undefined') { - throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value) - } - return Buffer(value, encodingOrOffset, length) - } +function handleArtifactServiceCreateArtifactProtobuf(ctx, service, data, interceptors) { + return __awaiter(this, void 0, void 0, function* () { + let request; + let response; + try { + request = artifact_1.CreateArtifactRequest.fromBinary(data); + } + catch (e) { + if (e instanceof Error) { + const msg = "the protobuf request could not be decoded"; + throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true); + } + } + if (interceptors && interceptors.length > 0) { + const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors); + response = yield interceptor(ctx, request, (ctx, inputReq) => { + return service.CreateArtifact(ctx, inputReq); + }); + } + else { + response = yield service.CreateArtifact(ctx, request); + } + return Buffer.from(artifact_1.CreateArtifactResponse.toBinary(response)); + }); } - -if (!Safer.alloc) { - Safer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) - } - if (size < 0 || size >= 2 * (1 << 30)) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } - var buf = Buffer(size) - if (!fill || fill.length === 0) { - buf.fill(0) - } else if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - return buf - } +function handleArtifactServiceFinalizeArtifactProtobuf(ctx, service, data, interceptors) { + return __awaiter(this, void 0, void 0, function* () { + let request; + let response; + try { + request = artifact_1.FinalizeArtifactRequest.fromBinary(data); + } + catch (e) { + if (e instanceof Error) { + const msg = "the protobuf request could not be decoded"; + throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true); + } + } + if (interceptors && interceptors.length > 0) { + const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors); + response = yield interceptor(ctx, request, (ctx, inputReq) => { + return service.FinalizeArtifact(ctx, inputReq); + }); + } + else { + response = yield service.FinalizeArtifact(ctx, request); + } + return Buffer.from(artifact_1.FinalizeArtifactResponse.toBinary(response)); + }); } - -if (!safer.kStringMaxLength) { - try { - safer.kStringMaxLength = process.binding('buffer').kStringMaxLength - } catch (e) { - // we can't determine kStringMaxLength in environments where process.binding - // is unsupported, so let's not set it - } +function handleArtifactServiceListArtifactsProtobuf(ctx, service, data, interceptors) { + return __awaiter(this, void 0, void 0, function* () { + let request; + let response; + try { + request = artifact_1.ListArtifactsRequest.fromBinary(data); + } + catch (e) { + if (e instanceof Error) { + const msg = "the protobuf request could not be decoded"; + throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true); + } + } + if (interceptors && interceptors.length > 0) { + const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors); + response = yield interceptor(ctx, request, (ctx, inputReq) => { + return service.ListArtifacts(ctx, inputReq); + }); + } + else { + response = yield service.ListArtifacts(ctx, request); + } + return Buffer.from(artifact_1.ListArtifactsResponse.toBinary(response)); + }); } - -if (!safer.constants) { - safer.constants = { - MAX_LENGTH: safer.kMaxLength - } - if (safer.kStringMaxLength) { - safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength - } +function handleArtifactServiceGetSignedArtifactURLProtobuf(ctx, service, data, interceptors) { + return __awaiter(this, void 0, void 0, function* () { + let request; + let response; + try { + request = artifact_1.GetSignedArtifactURLRequest.fromBinary(data); + } + catch (e) { + if (e instanceof Error) { + const msg = "the protobuf request could not be decoded"; + throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true); + } + } + if (interceptors && interceptors.length > 0) { + const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors); + response = yield interceptor(ctx, request, (ctx, inputReq) => { + return service.GetSignedArtifactURL(ctx, inputReq); + }); + } + else { + response = yield service.GetSignedArtifactURL(ctx, request); + } + return Buffer.from(artifact_1.GetSignedArtifactURLResponse.toBinary(response)); + }); } - -module.exports = safer - +//# sourceMappingURL=artifact.twirp.js.map /***/ }), -/***/ 99860: +/***/ 46190: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const client_1 = __nccwpck_require__(23955); -__exportStar(__nccwpck_require__(2538), exports); -__exportStar(__nccwpck_require__(69398), exports); -__exportStar(__nccwpck_require__(23955), exports); -const client = new client_1.DefaultArtifactClient(); -exports["default"] = client; -//# sourceMappingURL=artifact.js.map - -/***/ }), - -/***/ 68066: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DefaultArtifactClient = void 0; +const core_1 = __nccwpck_require__(42186); +const config_1 = __nccwpck_require__(74610); +const upload_artifact_1 = __nccwpck_require__(42578); +const download_artifact_1 = __nccwpck_require__(73555); +const get_artifact_1 = __nccwpck_require__(29491); +const list_artifacts_1 = __nccwpck_require__(44141); +const errors_1 = __nccwpck_require__(38182); +/** + * The default artifact client that is used by the artifact action(s). + */ +class DefaultArtifactClient { + uploadArtifact(name, files, rootDirectory, options) { + return __awaiter(this, void 0, void 0, function* () { + try { + if ((0, config_1.isGhes)()) { + throw new errors_1.GHESNotSupportedError(); + } + return (0, upload_artifact_1.uploadArtifact)(name, files, rootDirectory, options); + } + catch (error) { + (0, core_1.warning)(`Artifact upload failed with error: ${error}. -"use strict"; +Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Timestamp = void 0; -const runtime_1 = __nccwpck_require__(90076); -const runtime_2 = __nccwpck_require__(90076); -const runtime_3 = __nccwpck_require__(90076); -const runtime_4 = __nccwpck_require__(90076); -const runtime_5 = __nccwpck_require__(90076); -const runtime_6 = __nccwpck_require__(90076); -const runtime_7 = __nccwpck_require__(90076); -// @generated message type with reflection information, may provide speed optimized methods -class Timestamp$Type extends runtime_7.MessageType { - constructor() { - super("google.protobuf.Timestamp", [ - { no: 1, name: "seconds", kind: "scalar", T: 3 /*ScalarType.INT64*/ }, - { no: 2, name: "nanos", kind: "scalar", T: 5 /*ScalarType.INT32*/ } - ]); - } - /** - * Creates a new `Timestamp` for the current time. - */ - now() { - const msg = this.create(); - const ms = Date.now(); - msg.seconds = runtime_6.PbLong.from(Math.floor(ms / 1000)).toString(); - msg.nanos = (ms % 1000) * 1000000; - return msg; - } - /** - * Converts a `Timestamp` to a JavaScript Date. - */ - toDate(message) { - return new Date(runtime_6.PbLong.from(message.seconds).toNumber() * 1000 + Math.ceil(message.nanos / 1000000)); - } - /** - * Converts a JavaScript Date to a `Timestamp`. - */ - fromDate(date) { - const msg = this.create(); - const ms = date.getTime(); - msg.seconds = runtime_6.PbLong.from(Math.floor(ms / 1000)).toString(); - msg.nanos = (ms % 1000) * 1000000; - return msg; - } - /** - * In JSON format, the `Timestamp` type is encoded as a string - * in the RFC 3339 format. - */ - internalJsonWrite(message, options) { - let ms = runtime_6.PbLong.from(message.seconds).toNumber() * 1000; - if (ms < Date.parse("0001-01-01T00:00:00Z") || ms > Date.parse("9999-12-31T23:59:59Z")) - throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive."); - if (message.nanos < 0) - throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative."); - let z = "Z"; - if (message.nanos > 0) { - let nanosStr = (message.nanos + 1000000000).toString().substring(1); - if (nanosStr.substring(3) === "000000") - z = "." + nanosStr.substring(0, 3) + "Z"; - else if (nanosStr.substring(6) === "000") - z = "." + nanosStr.substring(0, 6) + "Z"; - else - z = "." + nanosStr + "Z"; - } - return new Date(ms).toISOString().replace(".000Z", z); - } - /** - * In JSON format, the `Timestamp` type is encoded as a string - * in the RFC 3339 format. - */ - internalJsonRead(json, options, target) { - if (typeof json !== "string") - throw new Error("Unable to parse Timestamp from JSON " + (0, runtime_5.typeofJsonValue)(json) + "."); - let matches = json.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/); - if (!matches) - throw new Error("Unable to parse Timestamp from JSON. Invalid format."); - let ms = Date.parse(matches[1] + "-" + matches[2] + "-" + matches[3] + "T" + matches[4] + ":" + matches[5] + ":" + matches[6] + (matches[8] ? matches[8] : "Z")); - if (Number.isNaN(ms)) - throw new Error("Unable to parse Timestamp from JSON. Invalid value."); - if (ms < Date.parse("0001-01-01T00:00:00Z") || ms > Date.parse("9999-12-31T23:59:59Z")) - throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive."); - if (!target) - target = this.create(); - target.seconds = runtime_6.PbLong.from(ms / 1000).toString(); - target.nanos = 0; - if (matches[7]) - target.nanos = (parseInt("1" + matches[7] + "0".repeat(9 - matches[7].length)) - 1000000000); - return target; +If the error persists, please check whether Actions is operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); + throw error; + } + }); } - create(value) { - const message = { seconds: "0", nanos: 0 }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== undefined) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + downloadArtifact(artifactId, options) { + return __awaiter(this, void 0, void 0, function* () { + try { + if ((0, config_1.isGhes)()) { + throw new errors_1.GHESNotSupportedError(); + } + if (options === null || options === void 0 ? void 0 : options.findBy) { + const { findBy: { repositoryOwner, repositoryName, token } } = options, downloadOptions = __rest(options, ["findBy"]); + return (0, download_artifact_1.downloadArtifactPublic)(artifactId, repositoryOwner, repositoryName, token, downloadOptions); + } + return (0, download_artifact_1.downloadArtifactInternal)(artifactId, options); + } + catch (error) { + (0, core_1.warning)(`Download Artifact failed with error: ${error}. + +Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. + +If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); + throw error; + } + }); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* int64 seconds */ 1: - message.seconds = reader.int64().toString(); - break; - case /* int32 nanos */ 2: - message.nanos = reader.int32(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + listArtifacts(options) { + return __awaiter(this, void 0, void 0, function* () { + try { + if ((0, config_1.isGhes)()) { + throw new errors_1.GHESNotSupportedError(); + } + if (options === null || options === void 0 ? void 0 : options.findBy) { + const { findBy: { workflowRunId, repositoryOwner, repositoryName, token } } = options; + return (0, list_artifacts_1.listArtifactsPublic)(workflowRunId, repositoryOwner, repositoryName, token, options === null || options === void 0 ? void 0 : options.latest); + } + return (0, list_artifacts_1.listArtifactsInternal)(options === null || options === void 0 ? void 0 : options.latest); } - } - return message; + catch (error) { + (0, core_1.warning)(`Listing Artifacts failed with error: ${error}. + +Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. + +If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); + throw error; + } + }); } - internalBinaryWrite(message, writer, options) { - /* int64 seconds = 1; */ - if (message.seconds !== "0") - writer.tag(1, runtime_1.WireType.Varint).int64(message.seconds); - /* int32 nanos = 2; */ - if (message.nanos !== 0) - writer.tag(2, runtime_1.WireType.Varint).int32(message.nanos); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + getArtifact(artifactName, options) { + return __awaiter(this, void 0, void 0, function* () { + try { + if ((0, config_1.isGhes)()) { + throw new errors_1.GHESNotSupportedError(); + } + if (options === null || options === void 0 ? void 0 : options.findBy) { + const { findBy: { workflowRunId, repositoryOwner, repositoryName, token } } = options; + return (0, get_artifact_1.getArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token); + } + return (0, get_artifact_1.getArtifactInternal)(artifactName); + } + catch (error) { + (0, core_1.warning)(`Get Artifact failed with error: ${error}. + +Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. + +If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); + throw error; + } + }); } } -/** - * @generated MessageType for protobuf message google.protobuf.Timestamp - */ -exports.Timestamp = new Timestamp$Type(); -//# sourceMappingURL=timestamp.js.map +exports.DefaultArtifactClient = DefaultArtifactClient; +//# sourceMappingURL=client.js.map /***/ }), -/***/ 97610: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 73555: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BytesValue = exports.StringValue = exports.BoolValue = exports.UInt32Value = exports.Int32Value = exports.UInt64Value = exports.Int64Value = exports.FloatValue = exports.DoubleValue = void 0; -// @generated by protobuf-ts 2.9.1 with parameter long_type_string,client_none,generate_dependencies -// @generated from protobuf file "google/protobuf/wrappers.proto" (package "google.protobuf", syntax proto3) -// tslint:disable -// -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// -// Wrappers for primitive (non-message) types. These types are useful -// for embedding primitives in the `google.protobuf.Any` type and for places -// where we need to distinguish between the absence of a primitive -// typed field and its default value. -// -const runtime_1 = __nccwpck_require__(90076); -const runtime_2 = __nccwpck_require__(90076); -const runtime_3 = __nccwpck_require__(90076); -const runtime_4 = __nccwpck_require__(90076); -const runtime_5 = __nccwpck_require__(90076); -const runtime_6 = __nccwpck_require__(90076); -const runtime_7 = __nccwpck_require__(90076); -// @generated message type with reflection information, may provide speed optimized methods -class DoubleValue$Type extends runtime_7.MessageType { - constructor() { - super("google.protobuf.DoubleValue", [ - { no: 1, name: "value", kind: "scalar", T: 1 /*ScalarType.DOUBLE*/ } - ]); - } - /** - * Encode `DoubleValue` to JSON number. - */ - internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(2, message.value, "value", false, true); - } - /** - * Decode `DoubleValue` from JSON number. - */ - internalJsonRead(json, options, target) { - if (!target) - target = this.create(); - target.value = this.refJsonReader.scalar(json, 1, undefined, "value"); - return target; - } - create(value) { - const message = { value: 0 }; - globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== undefined) - (0, runtime_5.reflectionMergePartial)(this, message, value); - return message; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* double value */ 1: - message.value = reader.double(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.downloadArtifactInternal = exports.downloadArtifactPublic = void 0; +const promises_1 = __importDefault(__nccwpck_require__(73292)); +const github = __importStar(__nccwpck_require__(95438)); +const core = __importStar(__nccwpck_require__(42186)); +const httpClient = __importStar(__nccwpck_require__(96255)); +const unzip_stream_1 = __importDefault(__nccwpck_require__(69340)); +const user_agent_1 = __nccwpck_require__(85164); +const config_1 = __nccwpck_require__(74610); +const artifact_twirp_client_1 = __nccwpck_require__(12312); +const generated_1 = __nccwpck_require__(49960); +const util_1 = __nccwpck_require__(63062); +const errors_1 = __nccwpck_require__(38182); +const scrubQueryParameters = (url) => { + const parsed = new URL(url); + parsed.search = ''; + return parsed.toString(); +}; +function exists(path) { + return __awaiter(this, void 0, void 0, function* () { + try { + yield promises_1.default.access(path); + return true; + } + catch (error) { + if (error.code === 'ENOENT') { + return false; + } + else { + throw error; } } - return message; - } - internalBinaryWrite(message, writer, options) { - /* double value = 1; */ - if (message.value !== 0) - writer.tag(1, runtime_3.WireType.Bit64).double(message.value); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; - } + }); } -/** - * @generated MessageType for protobuf message google.protobuf.DoubleValue - */ -exports.DoubleValue = new DoubleValue$Type(); -// @generated message type with reflection information, may provide speed optimized methods -class FloatValue$Type extends runtime_7.MessageType { - constructor() { - super("google.protobuf.FloatValue", [ - { no: 1, name: "value", kind: "scalar", T: 2 /*ScalarType.FLOAT*/ } - ]); - } - /** - * Encode `FloatValue` to JSON number. - */ - internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(1, message.value, "value", false, true); - } - /** - * Decode `FloatValue` from JSON number. - */ - internalJsonRead(json, options, target) { - if (!target) - target = this.create(); - target.value = this.refJsonReader.scalar(json, 1, undefined, "value"); - return target; - } - create(value) { - const message = { value: 0 }; - globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== undefined) - (0, runtime_5.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* float value */ 1: - message.value = reader.float(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); +function streamExtract(url, directory) { + return __awaiter(this, void 0, void 0, function* () { + const client = new httpClient.HttpClient((0, user_agent_1.getUserAgentString)()); + const response = yield client.get(url); + if (response.message.statusCode !== 200) { + throw new Error(`Unexpected HTTP response from blob storage: ${response.message.statusCode} ${response.message.statusMessage}`); + } + return new Promise((resolve, reject) => { + response.message + .pipe(unzip_stream_1.default.Extract({ path: directory })) + .on('close', resolve) + .on('error', reject); + }); + }); +} +function downloadArtifactPublic(artifactId, repositoryOwner, repositoryName, token, options) { + return __awaiter(this, void 0, void 0, function* () { + const downloadPath = yield resolveOrCreateDirectory(options === null || options === void 0 ? void 0 : options.path); + const api = github.getOctokit(token); + core.info(`Downloading artifact '${artifactId}' from '${repositoryOwner}/${repositoryName}'`); + const { headers, status } = yield api.rest.actions.downloadArtifact({ + owner: repositoryOwner, + repo: repositoryName, + artifact_id: artifactId, + archive_format: 'zip', + request: { + redirect: 'manual' } + }); + if (status !== 302) { + throw new Error(`Unable to download artifact. Unexpected status: ${status}`); } - return message; - } - internalBinaryWrite(message, writer, options) { - /* float value = 1; */ - if (message.value !== 0) - writer.tag(1, runtime_3.WireType.Bit32).float(message.value); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; - } + const { location } = headers; + if (!location) { + throw new Error(`Unable to redirect to artifact download url`); + } + core.info(`Redirecting to blob download url: ${scrubQueryParameters(location)}`); + try { + core.info(`Starting download of artifact to: ${downloadPath}`); + yield streamExtract(location, downloadPath); + core.info(`Artifact download completed successfully.`); + } + catch (error) { + throw new Error(`Unable to download and extract artifact: ${error.message}`); + } + return { downloadPath }; + }); } -/** - * @generated MessageType for protobuf message google.protobuf.FloatValue - */ -exports.FloatValue = new FloatValue$Type(); -// @generated message type with reflection information, may provide speed optimized methods -class Int64Value$Type extends runtime_7.MessageType { - constructor() { - super("google.protobuf.Int64Value", [ - { no: 1, name: "value", kind: "scalar", T: 3 /*ScalarType.INT64*/ } - ]); - } - /** - * Encode `Int64Value` to JSON string. - */ - internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(runtime_1.ScalarType.INT64, message.value, "value", false, true); - } - /** - * Decode `Int64Value` from JSON string. - */ - internalJsonRead(json, options, target) { - if (!target) - target = this.create(); - target.value = this.refJsonReader.scalar(json, runtime_1.ScalarType.INT64, runtime_2.LongType.STRING, "value"); - return target; - } - create(value) { - const message = { value: "0" }; - globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== undefined) - (0, runtime_5.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* int64 value */ 1: - message.value = reader.int64().toString(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; - } - internalBinaryWrite(message, writer, options) { - /* int64 value = 1; */ - if (message.value !== "0") - writer.tag(1, runtime_3.WireType.Varint).int64(message.value); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; - } -} -/** - * @generated MessageType for protobuf message google.protobuf.Int64Value - */ -exports.Int64Value = new Int64Value$Type(); -// @generated message type with reflection information, may provide speed optimized methods -class UInt64Value$Type extends runtime_7.MessageType { - constructor() { - super("google.protobuf.UInt64Value", [ - { no: 1, name: "value", kind: "scalar", T: 4 /*ScalarType.UINT64*/ } - ]); - } - /** - * Encode `UInt64Value` to JSON string. - */ - internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(runtime_1.ScalarType.UINT64, message.value, "value", false, true); - } - /** - * Decode `UInt64Value` from JSON string. - */ - internalJsonRead(json, options, target) { - if (!target) - target = this.create(); - target.value = this.refJsonReader.scalar(json, runtime_1.ScalarType.UINT64, runtime_2.LongType.STRING, "value"); - return target; - } - create(value) { - const message = { value: "0" }; - globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== undefined) - (0, runtime_5.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* uint64 value */ 1: - message.value = reader.uint64().toString(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } +exports.downloadArtifactPublic = downloadArtifactPublic; +function downloadArtifactInternal(artifactId, options) { + return __awaiter(this, void 0, void 0, function* () { + const downloadPath = yield resolveOrCreateDirectory(options === null || options === void 0 ? void 0 : options.path); + const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); + const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)(); + const listReq = { + workflowRunBackendId, + workflowJobRunBackendId, + idFilter: generated_1.Int64Value.create({ value: artifactId.toString() }) + }; + const { artifacts } = yield artifactClient.ListArtifacts(listReq); + if (artifacts.length === 0) { + throw new errors_1.ArtifactNotFoundError(`No artifacts found for ID: ${artifactId}\nAre you trying to download from a different run? Try specifying a github-token with \`actions:read\` scope.`); } - return message; - } - internalBinaryWrite(message, writer, options) { - /* uint64 value = 1; */ - if (message.value !== "0") - writer.tag(1, runtime_3.WireType.Varint).uint64(message.value); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; - } -} -/** - * @generated MessageType for protobuf message google.protobuf.UInt64Value - */ -exports.UInt64Value = new UInt64Value$Type(); -// @generated message type with reflection information, may provide speed optimized methods -class Int32Value$Type extends runtime_7.MessageType { - constructor() { - super("google.protobuf.Int32Value", [ - { no: 1, name: "value", kind: "scalar", T: 5 /*ScalarType.INT32*/ } - ]); - } - /** - * Encode `Int32Value` to JSON string. - */ - internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(5, message.value, "value", false, true); - } - /** - * Decode `Int32Value` from JSON string. - */ - internalJsonRead(json, options, target) { - if (!target) - target = this.create(); - target.value = this.refJsonReader.scalar(json, 5, undefined, "value"); - return target; - } - create(value) { - const message = { value: 0 }; - globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== undefined) - (0, runtime_5.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* int32 value */ 1: - message.value = reader.int32(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } + if (artifacts.length > 1) { + core.warning('Multiple artifacts found, defaulting to first.'); } - return message; - } - internalBinaryWrite(message, writer, options) { - /* int32 value = 1; */ - if (message.value !== 0) - writer.tag(1, runtime_3.WireType.Varint).int32(message.value); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; - } -} -/** - * @generated MessageType for protobuf message google.protobuf.Int32Value - */ -exports.Int32Value = new Int32Value$Type(); -// @generated message type with reflection information, may provide speed optimized methods -class UInt32Value$Type extends runtime_7.MessageType { - constructor() { - super("google.protobuf.UInt32Value", [ - { no: 1, name: "value", kind: "scalar", T: 13 /*ScalarType.UINT32*/ } - ]); - } - /** - * Encode `UInt32Value` to JSON string. - */ - internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(13, message.value, "value", false, true); - } - /** - * Decode `UInt32Value` from JSON string. - */ - internalJsonRead(json, options, target) { - if (!target) - target = this.create(); - target.value = this.refJsonReader.scalar(json, 13, undefined, "value"); - return target; - } - create(value) { - const message = { value: 0 }; - globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== undefined) - (0, runtime_5.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* uint32 value */ 1: - message.value = reader.uint32(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } + const signedReq = { + workflowRunBackendId: artifacts[0].workflowRunBackendId, + workflowJobRunBackendId: artifacts[0].workflowJobRunBackendId, + name: artifacts[0].name + }; + const { signedUrl } = yield artifactClient.GetSignedArtifactURL(signedReq); + core.info(`Redirecting to blob download url: ${scrubQueryParameters(signedUrl)}`); + try { + core.info(`Starting download of artifact to: ${downloadPath}`); + yield streamExtract(signedUrl, downloadPath); + core.info(`Artifact download completed successfully.`); } - return message; - } - internalBinaryWrite(message, writer, options) { - /* uint32 value = 1; */ - if (message.value !== 0) - writer.tag(1, runtime_3.WireType.Varint).uint32(message.value); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; - } -} -/** - * @generated MessageType for protobuf message google.protobuf.UInt32Value - */ -exports.UInt32Value = new UInt32Value$Type(); -// @generated message type with reflection information, may provide speed optimized methods -class BoolValue$Type extends runtime_7.MessageType { - constructor() { - super("google.protobuf.BoolValue", [ - { no: 1, name: "value", kind: "scalar", T: 8 /*ScalarType.BOOL*/ } - ]); - } - /** - * Encode `BoolValue` to JSON bool. - */ - internalJsonWrite(message, options) { - return message.value; - } - /** - * Decode `BoolValue` from JSON bool. - */ - internalJsonRead(json, options, target) { - if (!target) - target = this.create(); - target.value = this.refJsonReader.scalar(json, 8, undefined, "value"); - return target; - } - create(value) { - const message = { value: false }; - globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== undefined) - (0, runtime_5.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool value */ 1: - message.value = reader.bool(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } + catch (error) { + throw new Error(`Unable to download and extract artifact: ${error.message}`); } - return message; - } - internalBinaryWrite(message, writer, options) { - /* bool value = 1; */ - if (message.value !== false) - writer.tag(1, runtime_3.WireType.Varint).bool(message.value); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; - } + return { downloadPath }; + }); } -/** - * @generated MessageType for protobuf message google.protobuf.BoolValue - */ -exports.BoolValue = new BoolValue$Type(); -// @generated message type with reflection information, may provide speed optimized methods -class StringValue$Type extends runtime_7.MessageType { - constructor() { - super("google.protobuf.StringValue", [ - { no: 1, name: "value", kind: "scalar", T: 9 /*ScalarType.STRING*/ } - ]); - } - /** - * Encode `StringValue` to JSON string. - */ - internalJsonWrite(message, options) { - return message.value; - } - /** - * Decode `StringValue` from JSON string. - */ - internalJsonRead(json, options, target) { - if (!target) - target = this.create(); - target.value = this.refJsonReader.scalar(json, 9, undefined, "value"); - return target; - } - create(value) { - const message = { value: "" }; - globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== undefined) - (0, runtime_5.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string value */ 1: - message.value = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } +exports.downloadArtifactInternal = downloadArtifactInternal; +function resolveOrCreateDirectory(downloadPath = (0, config_1.getGitHubWorkspaceDir)()) { + return __awaiter(this, void 0, void 0, function* () { + if (!(yield exists(downloadPath))) { + core.debug(`Artifact destination folder does not exist, creating: ${downloadPath}`); + yield promises_1.default.mkdir(downloadPath, { recursive: true }); } - return message; - } - internalBinaryWrite(message, writer, options) { - /* string value = 1; */ - if (message.value !== "") - writer.tag(1, runtime_3.WireType.LengthDelimited).string(message.value); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; - } -} -/** - * @generated MessageType for protobuf message google.protobuf.StringValue - */ -exports.StringValue = new StringValue$Type(); -// @generated message type with reflection information, may provide speed optimized methods -class BytesValue$Type extends runtime_7.MessageType { - constructor() { - super("google.protobuf.BytesValue", [ - { no: 1, name: "value", kind: "scalar", T: 12 /*ScalarType.BYTES*/ } - ]); - } - /** - * Encode `BytesValue` to JSON string. - */ - internalJsonWrite(message, options) { - return this.refJsonWriter.scalar(12, message.value, "value", false, true); - } - /** - * Decode `BytesValue` from JSON string. - */ - internalJsonRead(json, options, target) { - if (!target) - target = this.create(); - target.value = this.refJsonReader.scalar(json, 12, undefined, "value"); - return target; - } - create(value) { - const message = { value: new Uint8Array(0) }; - globalThis.Object.defineProperty(message, runtime_6.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== undefined) - (0, runtime_5.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bytes value */ 1: - message.value = reader.bytes(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_4.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } + else { + core.debug(`Artifact destination folder already exists: ${downloadPath}`); } - return message; - } - internalBinaryWrite(message, writer, options) { - /* bytes value = 1; */ - if (message.value.length) - writer.tag(1, runtime_3.WireType.LengthDelimited).bytes(message.value); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_4.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; - } + return downloadPath; + }); } -/** - * @generated MessageType for protobuf message google.protobuf.BytesValue - */ -exports.BytesValue = new BytesValue$Type(); -//# sourceMappingURL=wrappers.js.map +//# sourceMappingURL=download-artifact.js.map /***/ }), -/***/ 90265: +/***/ 29491: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -3938,1041 +2155,763 @@ var __createBinding = (this && this.__createBinding) || (Object.create ? (functi if (k2 === undefined) k2 = k; o[k2] = m[k]; })); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -__exportStar(__nccwpck_require__(68066), exports); -__exportStar(__nccwpck_require__(97610), exports); -__exportStar(__nccwpck_require__(76025), exports); -__exportStar(__nccwpck_require__(84701), exports); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 76025: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ArtifactService = exports.GetSignedArtifactURLResponse = exports.GetSignedArtifactURLRequest = exports.ListArtifactsResponse_MonolithArtifact = exports.ListArtifactsResponse = exports.ListArtifactsRequest = exports.FinalizeArtifactResponse = exports.FinalizeArtifactRequest = exports.CreateArtifactResponse = exports.CreateArtifactRequest = void 0; -// @generated by protobuf-ts 2.9.1 with parameter long_type_string,client_none,generate_dependencies -// @generated from protobuf file "results/api/v1/artifact.proto" (package "github.actions.results.api.v1", syntax proto3) -// tslint:disable -const runtime_rpc_1 = __nccwpck_require__(81745); -const runtime_1 = __nccwpck_require__(90076); -const runtime_2 = __nccwpck_require__(90076); -const runtime_3 = __nccwpck_require__(90076); -const runtime_4 = __nccwpck_require__(90076); -const runtime_5 = __nccwpck_require__(90076); -const wrappers_1 = __nccwpck_require__(97610); -const wrappers_2 = __nccwpck_require__(97610); -const timestamp_1 = __nccwpck_require__(68066); -// @generated message type with reflection information, may provide speed optimized methods -class CreateArtifactRequest$Type extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.CreateArtifactRequest", [ - { no: 1, name: "workflow_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, - { no: 2, name: "workflow_job_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, - { no: 3, name: "name", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, - { no: 4, name: "expires_at", kind: "message", T: () => timestamp_1.Timestamp }, - { no: 5, name: "version", kind: "scalar", T: 5 /*ScalarType.INT32*/ } - ]); - } - create(value) { - const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "", version: 0 }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== undefined) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string workflow_run_backend_id */ 1: - message.workflowRunBackendId = reader.string(); - break; - case /* string workflow_job_run_backend_id */ 2: - message.workflowJobRunBackendId = reader.string(); - break; - case /* string name */ 3: - message.name = reader.string(); - break; - case /* google.protobuf.Timestamp expires_at */ 4: - message.expiresAt = timestamp_1.Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.expiresAt); - break; - case /* int32 version */ 5: - message.version = reader.int32(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); +exports.getArtifactInternal = exports.getArtifactPublic = void 0; +const github_1 = __nccwpck_require__(95438); +const plugin_retry_1 = __nccwpck_require__(86298); +const core = __importStar(__nccwpck_require__(42186)); +const utils_1 = __nccwpck_require__(73030); +const retry_options_1 = __nccwpck_require__(64597); +const plugin_request_log_1 = __nccwpck_require__(68883); +const util_1 = __nccwpck_require__(63062); +const user_agent_1 = __nccwpck_require__(85164); +const artifact_twirp_client_1 = __nccwpck_require__(12312); +const generated_1 = __nccwpck_require__(49960); +const errors_1 = __nccwpck_require__(38182); +function getArtifactPublic(artifactName, workflowRunId, repositoryOwner, repositoryName, token) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults); + const opts = { + log: undefined, + userAgent: (0, user_agent_1.getUserAgentString)(), + previews: undefined, + retry: retryOpts, + request: requestOpts + }; + const github = (0, github_1.getOctokit)(token, opts, plugin_retry_1.retry, plugin_request_log_1.requestLog); + const getArtifactResp = yield github.request('GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts{?name}', { + owner: repositoryOwner, + repo: repositoryName, + run_id: workflowRunId, + name: artifactName + }); + if (getArtifactResp.status !== 200) { + throw new errors_1.InvalidResponseError(`Invalid response from GitHub API: ${getArtifactResp.status} (${(_a = getArtifactResp === null || getArtifactResp === void 0 ? void 0 : getArtifactResp.headers) === null || _a === void 0 ? void 0 : _a['x-github-request-id']})`); + } + if (getArtifactResp.data.artifacts.length === 0) { + throw new errors_1.ArtifactNotFoundError(`Artifact not found for name: ${artifactName}`); + } + let artifact = getArtifactResp.data.artifacts[0]; + if (getArtifactResp.data.artifacts.length > 1) { + artifact = getArtifactResp.data.artifacts.sort((a, b) => b.id - a.id)[0]; + core.debug(`More than one artifact found for a single name, returning newest (id: ${artifact.id})`); + } + return { + artifact: { + name: artifact.name, + id: artifact.id, + size: artifact.size_in_bytes, + createdAt: artifact.created_at ? new Date(artifact.created_at) : undefined } + }; + }); +} +exports.getArtifactPublic = getArtifactPublic; +function getArtifactInternal(artifactName) { + return __awaiter(this, void 0, void 0, function* () { + const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); + const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)(); + const req = { + workflowRunBackendId, + workflowJobRunBackendId, + nameFilter: generated_1.StringValue.create({ value: artifactName }) + }; + const res = yield artifactClient.ListArtifacts(req); + if (res.artifacts.length === 0) { + throw new errors_1.ArtifactNotFoundError(`Artifact not found for name: ${artifactName}`); } - return message; - } - internalBinaryWrite(message, writer, options) { - /* string workflow_run_backend_id = 1; */ - if (message.workflowRunBackendId !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); - /* string workflow_job_run_backend_id = 2; */ - if (message.workflowJobRunBackendId !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); - /* string name = 3; */ - if (message.name !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.name); - /* google.protobuf.Timestamp expires_at = 4; */ - if (message.expiresAt) - timestamp_1.Timestamp.internalBinaryWrite(message.expiresAt, writer.tag(4, runtime_1.WireType.LengthDelimited).fork(), options).join(); - /* int32 version = 5; */ - if (message.version !== 0) - writer.tag(5, runtime_1.WireType.Varint).int32(message.version); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; - } + let artifact = res.artifacts[0]; + if (res.artifacts.length > 1) { + artifact = res.artifacts.sort((a, b) => Number(b.databaseId) - Number(a.databaseId))[0]; + core.debug(`More than one artifact found for a single name, returning newest (id: ${artifact.databaseId})`); + } + return { + artifact: { + name: artifact.name, + id: Number(artifact.databaseId), + size: Number(artifact.size), + createdAt: artifact.createdAt + ? generated_1.Timestamp.toDate(artifact.createdAt) + : undefined + } + }; + }); } -/** - * @generated MessageType for protobuf message github.actions.results.api.v1.CreateArtifactRequest - */ -exports.CreateArtifactRequest = new CreateArtifactRequest$Type(); -// @generated message type with reflection information, may provide speed optimized methods -class CreateArtifactResponse$Type extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.CreateArtifactResponse", [ - { no: 1, name: "ok", kind: "scalar", T: 8 /*ScalarType.BOOL*/ }, - { no: 2, name: "signed_upload_url", kind: "scalar", T: 9 /*ScalarType.STRING*/ } - ]); - } - create(value) { - const message = { ok: false, signedUploadUrl: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== undefined) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ 1: - message.ok = reader.bool(); - break; - case /* string signed_upload_url */ 2: - message.signedUploadUrl = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); +exports.getArtifactInternal = getArtifactInternal; +//# sourceMappingURL=get-artifact.js.map + +/***/ }), + +/***/ 44141: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.listArtifactsInternal = exports.listArtifactsPublic = void 0; +const core_1 = __nccwpck_require__(42186); +const github_1 = __nccwpck_require__(95438); +const user_agent_1 = __nccwpck_require__(85164); +const retry_options_1 = __nccwpck_require__(64597); +const utils_1 = __nccwpck_require__(73030); +const plugin_request_log_1 = __nccwpck_require__(68883); +const plugin_retry_1 = __nccwpck_require__(86298); +const artifact_twirp_client_1 = __nccwpck_require__(12312); +const util_1 = __nccwpck_require__(63062); +const generated_1 = __nccwpck_require__(49960); +// Limiting to 1000 for perf reasons +const maximumArtifactCount = 1000; +const paginationCount = 100; +const maxNumberOfPages = maximumArtifactCount / paginationCount; +function listArtifactsPublic(workflowRunId, repositoryOwner, repositoryName, token, latest = false) { + return __awaiter(this, void 0, void 0, function* () { + (0, core_1.info)(`Fetching artifact list for workflow run ${workflowRunId} in repository ${repositoryOwner}/${repositoryName}`); + let artifacts = []; + const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults); + const opts = { + log: undefined, + userAgent: (0, user_agent_1.getUserAgentString)(), + previews: undefined, + retry: retryOpts, + request: requestOpts + }; + const github = (0, github_1.getOctokit)(token, opts, plugin_retry_1.retry, plugin_request_log_1.requestLog); + let currentPageNumber = 1; + const { data: listArtifactResponse } = yield github.rest.actions.listWorkflowRunArtifacts({ + owner: repositoryOwner, + repo: repositoryName, + run_id: workflowRunId, + per_page: paginationCount, + page: currentPageNumber + }); + let numberOfPages = Math.ceil(listArtifactResponse.total_count / paginationCount); + const totalArtifactCount = listArtifactResponse.total_count; + if (totalArtifactCount > maximumArtifactCount) { + (0, core_1.warning)(`Workflow run ${workflowRunId} has more than 1000 artifacts. Results will be incomplete as only the first ${maximumArtifactCount} artifacts will be returned`); + numberOfPages = maxNumberOfPages; + } + // Iterate over the first page + for (const artifact of listArtifactResponse.artifacts) { + artifacts.push({ + name: artifact.name, + id: artifact.id, + size: artifact.size_in_bytes, + createdAt: artifact.created_at ? new Date(artifact.created_at) : undefined + }); + } + // Iterate over any remaining pages + for (currentPageNumber; currentPageNumber < numberOfPages; currentPageNumber++) { + currentPageNumber++; + (0, core_1.debug)(`Fetching page ${currentPageNumber} of artifact list`); + const { data: listArtifactResponse } = yield github.rest.actions.listWorkflowRunArtifacts({ + owner: repositoryOwner, + repo: repositoryName, + run_id: workflowRunId, + per_page: paginationCount, + page: currentPageNumber + }); + for (const artifact of listArtifactResponse.artifacts) { + artifacts.push({ + name: artifact.name, + id: artifact.id, + size: artifact.size_in_bytes, + createdAt: artifact.created_at + ? new Date(artifact.created_at) + : undefined + }); } } - return message; - } - internalBinaryWrite(message, writer, options) { - /* bool ok = 1; */ - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - /* string signed_upload_url = 2; */ - if (message.signedUploadUrl !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedUploadUrl); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; - } + if (latest) { + artifacts = filterLatest(artifacts); + } + (0, core_1.info)(`Found ${artifacts.length} artifact(s)`); + return { + artifacts + }; + }); } -/** - * @generated MessageType for protobuf message github.actions.results.api.v1.CreateArtifactResponse - */ -exports.CreateArtifactResponse = new CreateArtifactResponse$Type(); -// @generated message type with reflection information, may provide speed optimized methods -class FinalizeArtifactRequest$Type extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.FinalizeArtifactRequest", [ - { no: 1, name: "workflow_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, - { no: 2, name: "workflow_job_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, - { no: 3, name: "name", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, - { no: 4, name: "size", kind: "scalar", T: 3 /*ScalarType.INT64*/ }, - { no: 5, name: "hash", kind: "message", T: () => wrappers_2.StringValue } - ]); - } - create(value) { - const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "", size: "0" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== undefined) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string workflow_run_backend_id */ 1: - message.workflowRunBackendId = reader.string(); - break; - case /* string workflow_job_run_backend_id */ 2: - message.workflowJobRunBackendId = reader.string(); - break; - case /* string name */ 3: - message.name = reader.string(); - break; - case /* int64 size */ 4: - message.size = reader.int64().toString(); - break; - case /* google.protobuf.StringValue hash */ 5: - message.hash = wrappers_2.StringValue.internalBinaryRead(reader, reader.uint32(), options, message.hash); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } +exports.listArtifactsPublic = listArtifactsPublic; +function listArtifactsInternal(latest = false) { + return __awaiter(this, void 0, void 0, function* () { + const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); + const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)(); + const req = { + workflowRunBackendId, + workflowJobRunBackendId + }; + const res = yield artifactClient.ListArtifacts(req); + let artifacts = res.artifacts.map(artifact => ({ + name: artifact.name, + id: Number(artifact.databaseId), + size: Number(artifact.size), + createdAt: artifact.createdAt + ? generated_1.Timestamp.toDate(artifact.createdAt) + : undefined + })); + if (latest) { + artifacts = filterLatest(artifacts); } - return message; - } - internalBinaryWrite(message, writer, options) { - /* string workflow_run_backend_id = 1; */ - if (message.workflowRunBackendId !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); - /* string workflow_job_run_backend_id = 2; */ - if (message.workflowJobRunBackendId !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); - /* string name = 3; */ - if (message.name !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.name); - /* int64 size = 4; */ - if (message.size !== "0") - writer.tag(4, runtime_1.WireType.Varint).int64(message.size); - /* google.protobuf.StringValue hash = 5; */ - if (message.hash) - wrappers_2.StringValue.internalBinaryWrite(message.hash, writer.tag(5, runtime_1.WireType.LengthDelimited).fork(), options).join(); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; - } + (0, core_1.info)(`Found ${artifacts.length} artifact(s)`); + return { + artifacts + }; + }); } +exports.listArtifactsInternal = listArtifactsInternal; /** - * @generated MessageType for protobuf message github.actions.results.api.v1.FinalizeArtifactRequest + * Filters a list of artifacts to only include the latest artifact for each name + * @param artifacts The artifacts to filter + * @returns The filtered list of artifacts */ -exports.FinalizeArtifactRequest = new FinalizeArtifactRequest$Type(); -// @generated message type with reflection information, may provide speed optimized methods -class FinalizeArtifactResponse$Type extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.FinalizeArtifactResponse", [ - { no: 1, name: "ok", kind: "scalar", T: 8 /*ScalarType.BOOL*/ }, - { no: 2, name: "artifact_id", kind: "scalar", T: 3 /*ScalarType.INT64*/ } - ]); +function filterLatest(artifacts) { + artifacts.sort((a, b) => b.id - a.id); + const latestArtifacts = []; + const seenArtifactNames = new Set(); + for (const artifact of artifacts) { + if (!seenArtifactNames.has(artifact.name)) { + latestArtifacts.push(artifact); + seenArtifactNames.add(artifact.name); + } } - create(value) { - const message = { ok: false, artifactId: "0" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== undefined) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + return latestArtifacts; +} +//# sourceMappingURL=list-artifacts.js.map + +/***/ }), + +/***/ 64597: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* bool ok */ 1: - message.ok = reader.bool(); - break; - case /* int64 artifact_id */ 2: - message.artifactId = reader.int64().toString(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getRetryOptions = void 0; +const core = __importStar(__nccwpck_require__(42186)); +// Defaults for fetching artifacts +const defaultMaxRetryNumber = 5; +const defaultExemptStatusCodes = [400, 401, 403, 404, 422]; // https://github.com/octokit/plugin-retry.js/blob/9a2443746c350b3beedec35cf26e197ea318a261/src/index.ts#L14 +function getRetryOptions(defaultOptions, retries = defaultMaxRetryNumber, exemptStatusCodes = defaultExemptStatusCodes) { + var _a; + if (retries <= 0) { + return [{ enabled: false }, defaultOptions.request]; } - internalBinaryWrite(message, writer, options) { - /* bool ok = 1; */ - if (message.ok !== false) - writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); - /* int64 artifact_id = 2; */ - if (message.artifactId !== "0") - writer.tag(2, runtime_1.WireType.Varint).int64(message.artifactId); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + const retryOptions = { + enabled: true + }; + if (exemptStatusCodes.length > 0) { + retryOptions.doNotRetry = exemptStatusCodes; } + // The GitHub type has some defaults for `options.request` + // see: https://github.com/actions/toolkit/blob/4fbc5c941a57249b19562015edbd72add14be93d/packages/github/src/utils.ts#L15 + // We pass these in here so they are not overridden. + const requestOptions = Object.assign(Object.assign({}, defaultOptions.request), { retries }); + core.debug(`GitHub client configured with: (retries: ${requestOptions.retries}, retry-exempt-status-code: ${(_a = retryOptions.doNotRetry) !== null && _a !== void 0 ? _a : 'octokit default: [400, 401, 403, 404, 422]'})`); + return [retryOptions, requestOptions]; } -/** - * @generated MessageType for protobuf message github.actions.results.api.v1.FinalizeArtifactResponse - */ -exports.FinalizeArtifactResponse = new FinalizeArtifactResponse$Type(); -// @generated message type with reflection information, may provide speed optimized methods -class ListArtifactsRequest$Type extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.ListArtifactsRequest", [ - { no: 1, name: "workflow_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, - { no: 2, name: "workflow_job_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, - { no: 3, name: "name_filter", kind: "message", T: () => wrappers_2.StringValue }, - { no: 4, name: "id_filter", kind: "message", T: () => wrappers_1.Int64Value } +exports.getRetryOptions = getRetryOptions; +//# sourceMappingURL=retry-options.js.map + +/***/ }), + +/***/ 12312: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.internalArtifactTwirpClient = void 0; +const http_client_1 = __nccwpck_require__(96255); +const auth_1 = __nccwpck_require__(35526); +const core_1 = __nccwpck_require__(42186); +const generated_1 = __nccwpck_require__(49960); +const config_1 = __nccwpck_require__(74610); +const user_agent_1 = __nccwpck_require__(85164); +const errors_1 = __nccwpck_require__(38182); +class ArtifactHttpClient { + constructor(userAgent, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) { + this.maxAttempts = 5; + this.baseRetryIntervalMilliseconds = 3000; + this.retryMultiplier = 1.5; + const token = (0, config_1.getRuntimeToken)(); + this.baseUrl = (0, config_1.getResultsServiceUrl)(); + if (maxAttempts) { + this.maxAttempts = maxAttempts; + } + if (baseRetryIntervalMilliseconds) { + this.baseRetryIntervalMilliseconds = baseRetryIntervalMilliseconds; + } + if (retryMultiplier) { + this.retryMultiplier = retryMultiplier; + } + this.httpClient = new http_client_1.HttpClient(userAgent, [ + new auth_1.BearerCredentialHandler(token) ]); } - create(value) { - const message = { workflowRunBackendId: "", workflowJobRunBackendId: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== undefined) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + // This function satisfies the Rpc interface. It is compatible with the JSON + // JSON generated client. + request(service, method, contentType, data) { + return __awaiter(this, void 0, void 0, function* () { + const url = new URL(`/twirp/${service}/${method}`, this.baseUrl).href; + (0, core_1.debug)(`[Request] ${method} ${url}`); + const headers = { + 'Content-Type': contentType + }; + try { + const { body } = yield this.retryableRequest(() => __awaiter(this, void 0, void 0, function* () { return this.httpClient.post(url, JSON.stringify(data), headers); })); + return body; + } + catch (error) { + throw new Error(`Failed to ${method}: ${error.message}`); + } + }); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string workflow_run_backend_id */ 1: - message.workflowRunBackendId = reader.string(); - break; - case /* string workflow_job_run_backend_id */ 2: - message.workflowJobRunBackendId = reader.string(); - break; - case /* google.protobuf.StringValue name_filter */ 3: - message.nameFilter = wrappers_2.StringValue.internalBinaryRead(reader, reader.uint32(), options, message.nameFilter); - break; - case /* google.protobuf.Int64Value id_filter */ 4: - message.idFilter = wrappers_1.Int64Value.internalBinaryRead(reader, reader.uint32(), options, message.idFilter); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); + retryableRequest(operation) { + return __awaiter(this, void 0, void 0, function* () { + let attempt = 0; + let errorMessage = ''; + let rawBody = ''; + while (attempt < this.maxAttempts) { + let isRetryable = false; + try { + const response = yield operation(); + const statusCode = response.message.statusCode; + rawBody = yield response.readBody(); + (0, core_1.debug)(`[Response] - ${response.message.statusCode}`); + (0, core_1.debug)(`Headers: ${JSON.stringify(response.message.headers, null, 2)}`); + const body = JSON.parse(rawBody); + (0, core_1.debug)(`Body: ${JSON.stringify(body, null, 2)}`); + if (this.isSuccessStatusCode(statusCode)) { + return { response, body }; + } + isRetryable = this.isRetryableHttpStatusCode(statusCode); + errorMessage = `Failed request: (${statusCode}) ${response.message.statusMessage}`; + if (body.msg) { + if (errors_1.UsageError.isUsageErrorMessage(body.msg)) { + throw new errors_1.UsageError(); + } + errorMessage = `${errorMessage}: ${body.msg}`; + } + } + catch (error) { + if (error instanceof SyntaxError) { + (0, core_1.debug)(`Raw Body: ${rawBody}`); + throw error; + } + if (error instanceof errors_1.UsageError) { + throw error; + } + if (errors_1.NetworkError.isNetworkErrorCode(error === null || error === void 0 ? void 0 : error.code)) { + throw new errors_1.NetworkError(error === null || error === void 0 ? void 0 : error.code); + } + isRetryable = true; + errorMessage = error.message; + } + if (!isRetryable) { + throw new Error(`Received non-retryable error: ${errorMessage}`); + } + if (attempt + 1 === this.maxAttempts) { + throw new Error(`Failed to make request after ${this.maxAttempts} attempts: ${errorMessage}`); + } + const retryTimeMilliseconds = this.getExponentialRetryTimeMilliseconds(attempt); + (0, core_1.info)(`Attempt ${attempt + 1} of ${this.maxAttempts} failed with error: ${errorMessage}. Retrying request in ${retryTimeMilliseconds} ms...`); + yield this.sleep(retryTimeMilliseconds); + attempt++; } - } - return message; + throw new Error(`Request failed`); + }); } - internalBinaryWrite(message, writer, options) { - /* string workflow_run_backend_id = 1; */ - if (message.workflowRunBackendId !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); - /* string workflow_job_run_backend_id = 2; */ - if (message.workflowJobRunBackendId !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); - /* google.protobuf.StringValue name_filter = 3; */ - if (message.nameFilter) - wrappers_2.StringValue.internalBinaryWrite(message.nameFilter, writer.tag(3, runtime_1.WireType.LengthDelimited).fork(), options).join(); - /* google.protobuf.Int64Value id_filter = 4; */ - if (message.idFilter) - wrappers_1.Int64Value.internalBinaryWrite(message.idFilter, writer.tag(4, runtime_1.WireType.LengthDelimited).fork(), options).join(); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + isSuccessStatusCode(statusCode) { + if (!statusCode) + return false; + return statusCode >= 200 && statusCode < 300; } -} -/** - * @generated MessageType for protobuf message github.actions.results.api.v1.ListArtifactsRequest - */ -exports.ListArtifactsRequest = new ListArtifactsRequest$Type(); -// @generated message type with reflection information, may provide speed optimized methods -class ListArtifactsResponse$Type extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.ListArtifactsResponse", [ - { no: 1, name: "artifacts", kind: "message", repeat: 1 /*RepeatType.PACKED*/, T: () => exports.ListArtifactsResponse_MonolithArtifact } - ]); + isRetryableHttpStatusCode(statusCode) { + if (!statusCode) + return false; + const retryableStatusCodes = [ + http_client_1.HttpCodes.BadGateway, + http_client_1.HttpCodes.GatewayTimeout, + http_client_1.HttpCodes.InternalServerError, + http_client_1.HttpCodes.ServiceUnavailable, + http_client_1.HttpCodes.TooManyRequests + ]; + return retryableStatusCodes.includes(statusCode); } - create(value) { - const message = { artifacts: [] }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== undefined) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + sleep(milliseconds) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise(resolve => setTimeout(resolve, milliseconds)); + }); } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* repeated github.actions.results.api.v1.ListArtifactsResponse.MonolithArtifact artifacts */ 1: - message.artifacts.push(exports.ListArtifactsResponse_MonolithArtifact.internalBinaryRead(reader, reader.uint32(), options)); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } + getExponentialRetryTimeMilliseconds(attempt) { + if (attempt < 0) { + throw new Error('attempt should be a positive integer'); } - return message; - } - internalBinaryWrite(message, writer, options) { - /* repeated github.actions.results.api.v1.ListArtifactsResponse.MonolithArtifact artifacts = 1; */ - for (let i = 0; i < message.artifacts.length; i++) - exports.ListArtifactsResponse_MonolithArtifact.internalBinaryWrite(message.artifacts[i], writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + if (attempt === 0) { + return this.baseRetryIntervalMilliseconds; + } + const minTime = this.baseRetryIntervalMilliseconds * Math.pow(this.retryMultiplier, attempt); + const maxTime = minTime * this.retryMultiplier; + // returns a random number between minTime and maxTime (exclusive) + return Math.trunc(Math.random() * (maxTime - minTime) + minTime); } } -/** - * @generated MessageType for protobuf message github.actions.results.api.v1.ListArtifactsResponse - */ -exports.ListArtifactsResponse = new ListArtifactsResponse$Type(); -// @generated message type with reflection information, may provide speed optimized methods -class ListArtifactsResponse_MonolithArtifact$Type extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.ListArtifactsResponse.MonolithArtifact", [ - { no: 1, name: "workflow_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, - { no: 2, name: "workflow_job_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, - { no: 3, name: "database_id", kind: "scalar", T: 3 /*ScalarType.INT64*/ }, - { no: 4, name: "name", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, - { no: 5, name: "size", kind: "scalar", T: 3 /*ScalarType.INT64*/ }, - { no: 6, name: "created_at", kind: "message", T: () => timestamp_1.Timestamp } - ]); - } - create(value) { - const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", databaseId: "0", name: "", size: "0" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== undefined) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; - } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string workflow_run_backend_id */ 1: - message.workflowRunBackendId = reader.string(); - break; - case /* string workflow_job_run_backend_id */ 2: - message.workflowJobRunBackendId = reader.string(); - break; - case /* int64 database_id */ 3: - message.databaseId = reader.int64().toString(); - break; - case /* string name */ 4: - message.name = reader.string(); - break; - case /* int64 size */ 5: - message.size = reader.int64().toString(); - break; - case /* google.protobuf.Timestamp created_at */ 6: - message.createdAt = timestamp_1.Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.createdAt); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; +function internalArtifactTwirpClient(options) { + const client = new ArtifactHttpClient((0, user_agent_1.getUserAgentString)(), options === null || options === void 0 ? void 0 : options.maxAttempts, options === null || options === void 0 ? void 0 : options.retryIntervalMs, options === null || options === void 0 ? void 0 : options.retryMultiplier); + return new generated_1.ArtifactServiceClientJSON(client); +} +exports.internalArtifactTwirpClient = internalArtifactTwirpClient; +//# sourceMappingURL=artifact-twirp-client.js.map + +/***/ }), + +/***/ 74610: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getConcurrency = exports.getGitHubWorkspaceDir = exports.isGhes = exports.getResultsServiceUrl = exports.getRuntimeToken = exports.getUploadChunkSize = void 0; +const os_1 = __importDefault(__nccwpck_require__(22037)); +// Used for controlling the highWaterMark value of the zip that is being streamed +// The same value is used as the chunk size that is use during upload to blob storage +function getUploadChunkSize() { + return 8 * 1024 * 1024; // 8 MB Chunks +} +exports.getUploadChunkSize = getUploadChunkSize; +function getRuntimeToken() { + const token = process.env['ACTIONS_RUNTIME_TOKEN']; + if (!token) { + throw new Error('Unable to get the ACTIONS_RUNTIME_TOKEN env variable'); } - internalBinaryWrite(message, writer, options) { - /* string workflow_run_backend_id = 1; */ - if (message.workflowRunBackendId !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); - /* string workflow_job_run_backend_id = 2; */ - if (message.workflowJobRunBackendId !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); - /* int64 database_id = 3; */ - if (message.databaseId !== "0") - writer.tag(3, runtime_1.WireType.Varint).int64(message.databaseId); - /* string name = 4; */ - if (message.name !== "") - writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.name); - /* int64 size = 5; */ - if (message.size !== "0") - writer.tag(5, runtime_1.WireType.Varint).int64(message.size); - /* google.protobuf.Timestamp created_at = 6; */ - if (message.createdAt) - timestamp_1.Timestamp.internalBinaryWrite(message.createdAt, writer.tag(6, runtime_1.WireType.LengthDelimited).fork(), options).join(); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; + return token; +} +exports.getRuntimeToken = getRuntimeToken; +function getResultsServiceUrl() { + const resultsUrl = process.env['ACTIONS_RESULTS_URL']; + if (!resultsUrl) { + throw new Error('Unable to get the ACTIONS_RESULTS_URL env variable'); } + return new URL(resultsUrl).origin; } -/** - * @generated MessageType for protobuf message github.actions.results.api.v1.ListArtifactsResponse.MonolithArtifact - */ -exports.ListArtifactsResponse_MonolithArtifact = new ListArtifactsResponse_MonolithArtifact$Type(); -// @generated message type with reflection information, may provide speed optimized methods -class GetSignedArtifactURLRequest$Type extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.GetSignedArtifactURLRequest", [ - { no: 1, name: "workflow_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, - { no: 2, name: "workflow_job_run_backend_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, - { no: 3, name: "name", kind: "scalar", T: 9 /*ScalarType.STRING*/ } - ]); +exports.getResultsServiceUrl = getResultsServiceUrl; +function isGhes() { + const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com'); + return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'; +} +exports.isGhes = isGhes; +function getGitHubWorkspaceDir() { + const ghWorkspaceDir = process.env['GITHUB_WORKSPACE']; + if (!ghWorkspaceDir) { + throw new Error('Unable to get the GITHUB_WORKSPACE env variable'); } - create(value) { - const message = { workflowRunBackendId: "", workflowJobRunBackendId: "", name: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== undefined) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; + return ghWorkspaceDir; +} +exports.getGitHubWorkspaceDir = getGitHubWorkspaceDir; +// Mimics behavior of azcopy: https://learn.microsoft.com/en-us/azure/storage/common/storage-use-azcopy-optimize +// If your machine has fewer than 5 CPUs, then the value of this variable is set to 32. +// Otherwise, the default value is equal to 16 multiplied by the number of CPUs. The maximum value of this variable is 300. +function getConcurrency() { + const numCPUs = os_1.default.cpus().length; + if (numCPUs <= 4) { + return 32; } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string workflow_run_backend_id */ 1: - message.workflowRunBackendId = reader.string(); - break; - case /* string workflow_job_run_backend_id */ 2: - message.workflowJobRunBackendId = reader.string(); - break; - case /* string name */ 3: - message.name = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } + const concurrency = 16 * numCPUs; + return concurrency > 300 ? 300 : concurrency; +} +exports.getConcurrency = getConcurrency; +//# sourceMappingURL=config.js.map + +/***/ }), + +/***/ 38182: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.UsageError = exports.NetworkError = exports.GHESNotSupportedError = exports.ArtifactNotFoundError = exports.InvalidResponseError = exports.FilesNotFoundError = void 0; +class FilesNotFoundError extends Error { + constructor(files = []) { + let message = 'No files were found to upload'; + if (files.length > 0) { + message += `: ${files.join(', ')}`; } - return message; + super(message); + this.files = files; + this.name = 'FilesNotFoundError'; } - internalBinaryWrite(message, writer, options) { - /* string workflow_run_backend_id = 1; */ - if (message.workflowRunBackendId !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.workflowRunBackendId); - /* string workflow_job_run_backend_id = 2; */ - if (message.workflowJobRunBackendId !== "") - writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.workflowJobRunBackendId); - /* string name = 3; */ - if (message.name !== "") - writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.name); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; +} +exports.FilesNotFoundError = FilesNotFoundError; +class InvalidResponseError extends Error { + constructor(message) { + super(message); + this.name = 'InvalidResponseError'; } } -/** - * @generated MessageType for protobuf message github.actions.results.api.v1.GetSignedArtifactURLRequest - */ -exports.GetSignedArtifactURLRequest = new GetSignedArtifactURLRequest$Type(); -// @generated message type with reflection information, may provide speed optimized methods -class GetSignedArtifactURLResponse$Type extends runtime_5.MessageType { - constructor() { - super("github.actions.results.api.v1.GetSignedArtifactURLResponse", [ - { no: 1, name: "signed_url", kind: "scalar", T: 9 /*ScalarType.STRING*/ } - ]); +exports.InvalidResponseError = InvalidResponseError; +class ArtifactNotFoundError extends Error { + constructor(message = 'Artifact not found') { + super(message); + this.name = 'ArtifactNotFoundError'; } - create(value) { - const message = { signedUrl: "" }; - globalThis.Object.defineProperty(message, runtime_4.MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== undefined) - (0, runtime_3.reflectionMergePartial)(this, message, value); - return message; +} +exports.ArtifactNotFoundError = ArtifactNotFoundError; +class GHESNotSupportedError extends Error { + constructor(message = '@actions/artifact v2.0.0+, upload-artifact@v4+ and download-artifact@v4+ are not currently supported on GHES.') { + super(message); + this.name = 'GHESNotSupportedError'; } - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* string signed_url */ 1: - message.signedUrl = reader.string(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; +} +exports.GHESNotSupportedError = GHESNotSupportedError; +class NetworkError extends Error { + constructor(code) { + const message = `Unable to make request: ${code}\nIf you are using self-hosted runners, please make sure your runner has access to all GitHub endpoints: https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/about-self-hosted-runners#communication-between-self-hosted-runners-and-github`; + super(message); + this.code = code; + this.name = 'NetworkError'; } - internalBinaryWrite(message, writer, options) { - /* string signed_url = 1; */ - if (message.signedUrl !== "") - writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.signedUrl); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? runtime_2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; +} +exports.NetworkError = NetworkError; +NetworkError.isNetworkErrorCode = (code) => { + if (!code) + return false; + return [ + 'ECONNRESET', + 'ENOTFOUND', + 'ETIMEDOUT', + 'ECONNREFUSED', + 'EHOSTUNREACH' + ].includes(code); +}; +class UsageError extends Error { + constructor() { + const message = `Artifact storage quota has been hit. Unable to upload any new artifacts. Usage is recalculated every 6-12 hours.\nMore info on storage limits: https://docs.github.com/en/billing/managing-billing-for-github-actions/about-billing-for-github-actions#calculating-minute-and-storage-spending`; + super(message); + this.name = 'UsageError'; } } +exports.UsageError = UsageError; +UsageError.isUsageErrorMessage = (msg) => { + if (!msg) + return false; + return msg.includes('insufficient usage'); +}; +//# sourceMappingURL=errors.js.map + +/***/ }), + +/***/ 15769: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=interfaces.js.map + +/***/ }), + +/***/ 85164: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getUserAgentString = void 0; +// eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports +const packageJson = __nccwpck_require__(39839); /** - * @generated MessageType for protobuf message github.actions.results.api.v1.GetSignedArtifactURLResponse - */ -exports.GetSignedArtifactURLResponse = new GetSignedArtifactURLResponse$Type(); -/** - * @generated ServiceType for protobuf service github.actions.results.api.v1.ArtifactService + * Ensure that this User Agent String is used in all HTTP calls so that we can monitor telemetry between different versions of this package */ -exports.ArtifactService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.ArtifactService", [ - { name: "CreateArtifact", options: {}, I: exports.CreateArtifactRequest, O: exports.CreateArtifactResponse }, - { name: "FinalizeArtifact", options: {}, I: exports.FinalizeArtifactRequest, O: exports.FinalizeArtifactResponse }, - { name: "ListArtifacts", options: {}, I: exports.ListArtifactsRequest, O: exports.ListArtifactsResponse }, - { name: "GetSignedArtifactURL", options: {}, I: exports.GetSignedArtifactURLRequest, O: exports.GetSignedArtifactURLResponse } -]); -//# sourceMappingURL=artifact.js.map +function getUserAgentString() { + return `@actions/artifact-${packageJson.version}`; +} +exports.getUserAgentString = getUserAgentString; +//# sourceMappingURL=user-agent.js.map /***/ }), -/***/ 84701: +/***/ 63062: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createArtifactServiceServer = exports.ArtifactServiceMethodList = exports.ArtifactServiceMethod = exports.ArtifactServiceClientProtobuf = exports.ArtifactServiceClientJSON = void 0; -const twirp_ts_1 = __nccwpck_require__(68053); -const artifact_1 = __nccwpck_require__(76025); -class ArtifactServiceClientJSON { - constructor(rpc) { - this.rpc = rpc; - this.CreateArtifact.bind(this); - this.FinalizeArtifact.bind(this); - this.ListArtifacts.bind(this); - this.GetSignedArtifactURL.bind(this); - } - CreateArtifact(request) { - const data = artifact_1.CreateArtifactRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false, - }); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "CreateArtifact", "application/json", data); - return promise.then((data) => artifact_1.CreateArtifactResponse.fromJson(data, { - ignoreUnknownFields: true, - })); - } - FinalizeArtifact(request) { - const data = artifact_1.FinalizeArtifactRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false, - }); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "FinalizeArtifact", "application/json", data); - return promise.then((data) => artifact_1.FinalizeArtifactResponse.fromJson(data, { - ignoreUnknownFields: true, - })); - } - ListArtifacts(request) { - const data = artifact_1.ListArtifactsRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false, - }); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "ListArtifacts", "application/json", data); - return promise.then((data) => artifact_1.ListArtifactsResponse.fromJson(data, { ignoreUnknownFields: true })); - } - GetSignedArtifactURL(request) { - const data = artifact_1.GetSignedArtifactURLRequest.toJson(request, { - useProtoFieldName: true, - emitDefaultValues: false, - }); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "GetSignedArtifactURL", "application/json", data); - return promise.then((data) => artifact_1.GetSignedArtifactURLResponse.fromJson(data, { - ignoreUnknownFields: true, - })); - } -} -exports.ArtifactServiceClientJSON = ArtifactServiceClientJSON; -class ArtifactServiceClientProtobuf { - constructor(rpc) { - this.rpc = rpc; - this.CreateArtifact.bind(this); - this.FinalizeArtifact.bind(this); - this.ListArtifacts.bind(this); - this.GetSignedArtifactURL.bind(this); - } - CreateArtifact(request) { - const data = artifact_1.CreateArtifactRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "CreateArtifact", "application/protobuf", data); - return promise.then((data) => artifact_1.CreateArtifactResponse.fromBinary(data)); - } - FinalizeArtifact(request) { - const data = artifact_1.FinalizeArtifactRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "FinalizeArtifact", "application/protobuf", data); - return promise.then((data) => artifact_1.FinalizeArtifactResponse.fromBinary(data)); - } - ListArtifacts(request) { - const data = artifact_1.ListArtifactsRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "ListArtifacts", "application/protobuf", data); - return promise.then((data) => artifact_1.ListArtifactsResponse.fromBinary(data)); - } - GetSignedArtifactURL(request) { - const data = artifact_1.GetSignedArtifactURLRequest.toBinary(request); - const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "GetSignedArtifactURL", "application/protobuf", data); - return promise.then((data) => artifact_1.GetSignedArtifactURLResponse.fromBinary(data)); - } -} -exports.ArtifactServiceClientProtobuf = ArtifactServiceClientProtobuf; -var ArtifactServiceMethod; -(function (ArtifactServiceMethod) { - ArtifactServiceMethod["CreateArtifact"] = "CreateArtifact"; - ArtifactServiceMethod["FinalizeArtifact"] = "FinalizeArtifact"; - ArtifactServiceMethod["ListArtifacts"] = "ListArtifacts"; - ArtifactServiceMethod["GetSignedArtifactURL"] = "GetSignedArtifactURL"; -})(ArtifactServiceMethod || (exports.ArtifactServiceMethod = ArtifactServiceMethod = {})); -exports.ArtifactServiceMethodList = [ - ArtifactServiceMethod.CreateArtifact, - ArtifactServiceMethod.FinalizeArtifact, - ArtifactServiceMethod.ListArtifacts, - ArtifactServiceMethod.GetSignedArtifactURL, -]; -function createArtifactServiceServer(service) { - return new twirp_ts_1.TwirpServer({ - service, - packageName: "github.actions.results.api.v1", - serviceName: "ArtifactService", - methodList: exports.ArtifactServiceMethodList, - matchRoute: matchArtifactServiceRoute, - }); -} -exports.createArtifactServiceServer = createArtifactServiceServer; -function matchArtifactServiceRoute(method, events) { - switch (method) { - case "CreateArtifact": - return (ctx, service, data, interceptors) => __awaiter(this, void 0, void 0, function* () { - ctx = Object.assign(Object.assign({}, ctx), { methodName: "CreateArtifact" }); - yield events.onMatch(ctx); - return handleArtifactServiceCreateArtifactRequest(ctx, service, data, interceptors); - }); - case "FinalizeArtifact": - return (ctx, service, data, interceptors) => __awaiter(this, void 0, void 0, function* () { - ctx = Object.assign(Object.assign({}, ctx), { methodName: "FinalizeArtifact" }); - yield events.onMatch(ctx); - return handleArtifactServiceFinalizeArtifactRequest(ctx, service, data, interceptors); - }); - case "ListArtifacts": - return (ctx, service, data, interceptors) => __awaiter(this, void 0, void 0, function* () { - ctx = Object.assign(Object.assign({}, ctx), { methodName: "ListArtifacts" }); - yield events.onMatch(ctx); - return handleArtifactServiceListArtifactsRequest(ctx, service, data, interceptors); - }); - case "GetSignedArtifactURL": - return (ctx, service, data, interceptors) => __awaiter(this, void 0, void 0, function* () { - ctx = Object.assign(Object.assign({}, ctx), { methodName: "GetSignedArtifactURL" }); - yield events.onMatch(ctx); - return handleArtifactServiceGetSignedArtifactURLRequest(ctx, service, data, interceptors); - }); - default: - events.onNotFound(); - const msg = `no handler found`; - throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.BadRoute, msg); - } -} -function handleArtifactServiceCreateArtifactRequest(ctx, service, data, interceptors) { - switch (ctx.contentType) { - case twirp_ts_1.TwirpContentType.JSON: - return handleArtifactServiceCreateArtifactJSON(ctx, service, data, interceptors); - case twirp_ts_1.TwirpContentType.Protobuf: - return handleArtifactServiceCreateArtifactProtobuf(ctx, service, data, interceptors); - default: - const msg = "unexpected Content-Type"; - throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.BadRoute, msg); - } -} -function handleArtifactServiceFinalizeArtifactRequest(ctx, service, data, interceptors) { - switch (ctx.contentType) { - case twirp_ts_1.TwirpContentType.JSON: - return handleArtifactServiceFinalizeArtifactJSON(ctx, service, data, interceptors); - case twirp_ts_1.TwirpContentType.Protobuf: - return handleArtifactServiceFinalizeArtifactProtobuf(ctx, service, data, interceptors); - default: - const msg = "unexpected Content-Type"; - throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.BadRoute, msg); +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; } -} -function handleArtifactServiceListArtifactsRequest(ctx, service, data, interceptors) { - switch (ctx.contentType) { - case twirp_ts_1.TwirpContentType.JSON: - return handleArtifactServiceListArtifactsJSON(ctx, service, data, interceptors); - case twirp_ts_1.TwirpContentType.Protobuf: - return handleArtifactServiceListArtifactsProtobuf(ctx, service, data, interceptors); - default: - const msg = "unexpected Content-Type"; - throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.BadRoute, msg); + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getBackendIdsFromToken = void 0; +const core = __importStar(__nccwpck_require__(42186)); +const config_1 = __nccwpck_require__(74610); +const jwt_decode_1 = __importDefault(__nccwpck_require__(84329)); +const InvalidJwtError = new Error('Failed to get backend IDs: The provided JWT token is invalid and/or missing claims'); +// uses the JWT token claims to get the +// workflow run and workflow job run backend ids +function getBackendIdsFromToken() { + const token = (0, config_1.getRuntimeToken)(); + const decoded = (0, jwt_decode_1.default)(token); + if (!decoded.scp) { + throw InvalidJwtError; } -} -function handleArtifactServiceGetSignedArtifactURLRequest(ctx, service, data, interceptors) { - switch (ctx.contentType) { - case twirp_ts_1.TwirpContentType.JSON: - return handleArtifactServiceGetSignedArtifactURLJSON(ctx, service, data, interceptors); - case twirp_ts_1.TwirpContentType.Protobuf: - return handleArtifactServiceGetSignedArtifactURLProtobuf(ctx, service, data, interceptors); - default: - const msg = "unexpected Content-Type"; - throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.BadRoute, msg); + /* + * example decoded: + * { + * scp: "Actions.ExampleScope Actions.Results:ce7f54c7-61c7-4aae-887f-30da475f5f1a:ca395085-040a-526b-2ce8-bdc85f692774" + * } + */ + const scpParts = decoded.scp.split(' '); + if (scpParts.length === 0) { + throw InvalidJwtError; } -} -function handleArtifactServiceCreateArtifactJSON(ctx, service, data, interceptors) { - return __awaiter(this, void 0, void 0, function* () { - let request; - let response; - try { - const body = JSON.parse(data.toString() || "{}"); - request = artifact_1.CreateArtifactRequest.fromJson(body, { - ignoreUnknownFields: true, - }); - } - catch (e) { - if (e instanceof Error) { - const msg = "the json request could not be decoded"; - throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true); - } - } - if (interceptors && interceptors.length > 0) { - const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors); - response = yield interceptor(ctx, request, (ctx, inputReq) => { - return service.CreateArtifact(ctx, inputReq); - }); - } - else { - response = yield service.CreateArtifact(ctx, request); - } - return JSON.stringify(artifact_1.CreateArtifactResponse.toJson(response, { - useProtoFieldName: true, - emitDefaultValues: false, - })); - }); -} -function handleArtifactServiceFinalizeArtifactJSON(ctx, service, data, interceptors) { - return __awaiter(this, void 0, void 0, function* () { - let request; - let response; - try { - const body = JSON.parse(data.toString() || "{}"); - request = artifact_1.FinalizeArtifactRequest.fromJson(body, { - ignoreUnknownFields: true, - }); - } - catch (e) { - if (e instanceof Error) { - const msg = "the json request could not be decoded"; - throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true); - } - } - if (interceptors && interceptors.length > 0) { - const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors); - response = yield interceptor(ctx, request, (ctx, inputReq) => { - return service.FinalizeArtifact(ctx, inputReq); - }); - } - else { - response = yield service.FinalizeArtifact(ctx, request); - } - return JSON.stringify(artifact_1.FinalizeArtifactResponse.toJson(response, { - useProtoFieldName: true, - emitDefaultValues: false, - })); - }); -} -function handleArtifactServiceListArtifactsJSON(ctx, service, data, interceptors) { - return __awaiter(this, void 0, void 0, function* () { - let request; - let response; - try { - const body = JSON.parse(data.toString() || "{}"); - request = artifact_1.ListArtifactsRequest.fromJson(body, { - ignoreUnknownFields: true, - }); - } - catch (e) { - if (e instanceof Error) { - const msg = "the json request could not be decoded"; - throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true); - } - } - if (interceptors && interceptors.length > 0) { - const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors); - response = yield interceptor(ctx, request, (ctx, inputReq) => { - return service.ListArtifacts(ctx, inputReq); - }); - } - else { - response = yield service.ListArtifacts(ctx, request); - } - return JSON.stringify(artifact_1.ListArtifactsResponse.toJson(response, { - useProtoFieldName: true, - emitDefaultValues: false, - })); - }); -} -function handleArtifactServiceGetSignedArtifactURLJSON(ctx, service, data, interceptors) { - return __awaiter(this, void 0, void 0, function* () { - let request; - let response; - try { - const body = JSON.parse(data.toString() || "{}"); - request = artifact_1.GetSignedArtifactURLRequest.fromJson(body, { - ignoreUnknownFields: true, - }); - } - catch (e) { - if (e instanceof Error) { - const msg = "the json request could not be decoded"; - throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true); - } - } - if (interceptors && interceptors.length > 0) { - const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors); - response = yield interceptor(ctx, request, (ctx, inputReq) => { - return service.GetSignedArtifactURL(ctx, inputReq); - }); - } - else { - response = yield service.GetSignedArtifactURL(ctx, request); - } - return JSON.stringify(artifact_1.GetSignedArtifactURLResponse.toJson(response, { - useProtoFieldName: true, - emitDefaultValues: false, - })); - }); -} -function handleArtifactServiceCreateArtifactProtobuf(ctx, service, data, interceptors) { - return __awaiter(this, void 0, void 0, function* () { - let request; - let response; - try { - request = artifact_1.CreateArtifactRequest.fromBinary(data); - } - catch (e) { - if (e instanceof Error) { - const msg = "the protobuf request could not be decoded"; - throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true); - } - } - if (interceptors && interceptors.length > 0) { - const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors); - response = yield interceptor(ctx, request, (ctx, inputReq) => { - return service.CreateArtifact(ctx, inputReq); - }); - } - else { - response = yield service.CreateArtifact(ctx, request); - } - return Buffer.from(artifact_1.CreateArtifactResponse.toBinary(response)); - }); -} -function handleArtifactServiceFinalizeArtifactProtobuf(ctx, service, data, interceptors) { - return __awaiter(this, void 0, void 0, function* () { - let request; - let response; - try { - request = artifact_1.FinalizeArtifactRequest.fromBinary(data); - } - catch (e) { - if (e instanceof Error) { - const msg = "the protobuf request could not be decoded"; - throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true); - } - } - if (interceptors && interceptors.length > 0) { - const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors); - response = yield interceptor(ctx, request, (ctx, inputReq) => { - return service.FinalizeArtifact(ctx, inputReq); - }); - } - else { - response = yield service.FinalizeArtifact(ctx, request); - } - return Buffer.from(artifact_1.FinalizeArtifactResponse.toBinary(response)); - }); -} -function handleArtifactServiceListArtifactsProtobuf(ctx, service, data, interceptors) { - return __awaiter(this, void 0, void 0, function* () { - let request; - let response; - try { - request = artifact_1.ListArtifactsRequest.fromBinary(data); - } - catch (e) { - if (e instanceof Error) { - const msg = "the protobuf request could not be decoded"; - throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true); - } - } - if (interceptors && interceptors.length > 0) { - const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors); - response = yield interceptor(ctx, request, (ctx, inputReq) => { - return service.ListArtifacts(ctx, inputReq); - }); - } - else { - response = yield service.ListArtifacts(ctx, request); - } - return Buffer.from(artifact_1.ListArtifactsResponse.toBinary(response)); - }); -} -function handleArtifactServiceGetSignedArtifactURLProtobuf(ctx, service, data, interceptors) { - return __awaiter(this, void 0, void 0, function* () { - let request; - let response; - try { - request = artifact_1.GetSignedArtifactURLRequest.fromBinary(data); - } - catch (e) { - if (e instanceof Error) { - const msg = "the protobuf request could not be decoded"; - throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.Malformed, msg).withCause(e, true); - } - } - if (interceptors && interceptors.length > 0) { - const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors); - response = yield interceptor(ctx, request, (ctx, inputReq) => { - return service.GetSignedArtifactURL(ctx, inputReq); - }); + /* + * example scpParts: + * ["Actions.ExampleScope", "Actions.Results:ce7f54c7-61c7-4aae-887f-30da475f5f1a:ca395085-040a-526b-2ce8-bdc85f692774"] + */ + for (const scopes of scpParts) { + const scopeParts = scopes.split(':'); + if ((scopeParts === null || scopeParts === void 0 ? void 0 : scopeParts[0]) !== 'Actions.Results') { + // not the Actions.Results scope + continue; } - else { - response = yield service.GetSignedArtifactURL(ctx, request); + /* + * example scopeParts: + * ["Actions.Results", "ce7f54c7-61c7-4aae-887f-30da475f5f1a", "ca395085-040a-526b-2ce8-bdc85f692774"] + */ + if (scopeParts.length !== 3) { + // missing expected number of claims + throw InvalidJwtError; } - return Buffer.from(artifact_1.GetSignedArtifactURLResponse.toBinary(response)); - }); + const ids = { + workflowRunBackendId: scopeParts[1], + workflowJobRunBackendId: scopeParts[2] + }; + core.debug(`Workflow Run Backend ID: ${ids.workflowRunBackendId}`); + core.debug(`Workflow Job Run Backend ID: ${ids.workflowJobRunBackendId}`); + return ids; + } + throw InvalidJwtError; } -//# sourceMappingURL=artifact.twirp.js.map +exports.getBackendIdsFromToken = getBackendIdsFromToken; +//# sourceMappingURL=util.js.map /***/ }), -/***/ 23955: +/***/ 7246: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { @@ -4982,121 +2921,199 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; -var __rest = (this && this.__rest) || function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; -}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DefaultArtifactClient = void 0; -const core_1 = __nccwpck_require__(66526); -const config_1 = __nccwpck_require__(95042); -const upload_artifact_1 = __nccwpck_require__(86278); -const download_artifact_1 = __nccwpck_require__(17306); -const get_artifact_1 = __nccwpck_require__(56218); -const list_artifacts_1 = __nccwpck_require__(64033); -const errors_1 = __nccwpck_require__(69398); -/** - * The default artifact client that is used by the artifact action(s). - */ -class DefaultArtifactClient { - uploadArtifact(name, files, rootDirectory, options) { - return __awaiter(this, void 0, void 0, function* () { - try { - if ((0, config_1.isGhes)()) { - throw new errors_1.GHESNotSupportedError(); - } - return (0, upload_artifact_1.uploadArtifact)(name, files, rootDirectory, options); - } - catch (error) { - (0, core_1.warning)(`Artifact upload failed with error: ${error}. - -Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. - -If the error persists, please check whether Actions is operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); - throw error; - } - }); - } - downloadArtifact(artifactId, options) { - return __awaiter(this, void 0, void 0, function* () { - try { - if ((0, config_1.isGhes)()) { - throw new errors_1.GHESNotSupportedError(); - } - if (options === null || options === void 0 ? void 0 : options.findBy) { - const { findBy: { repositoryOwner, repositoryName, token } } = options, downloadOptions = __rest(options, ["findBy"]); - return (0, download_artifact_1.downloadArtifactPublic)(artifactId, repositoryOwner, repositoryName, token, downloadOptions); - } - return (0, download_artifact_1.downloadArtifactInternal)(artifactId, options); +exports.uploadZipToBlobStorage = void 0; +const storage_blob_1 = __nccwpck_require__(84100); +const config_1 = __nccwpck_require__(74610); +const core = __importStar(__nccwpck_require__(42186)); +const crypto = __importStar(__nccwpck_require__(6113)); +const stream = __importStar(__nccwpck_require__(12781)); +const errors_1 = __nccwpck_require__(38182); +function uploadZipToBlobStorage(authenticatedUploadURL, zipUploadStream) { + return __awaiter(this, void 0, void 0, function* () { + let uploadByteCount = 0; + const maxConcurrency = (0, config_1.getConcurrency)(); + const bufferSize = (0, config_1.getUploadChunkSize)(); + const blobClient = new storage_blob_1.BlobClient(authenticatedUploadURL); + const blockBlobClient = blobClient.getBlockBlobClient(); + core.debug(`Uploading artifact zip to blob storage with maxConcurrency: ${maxConcurrency}, bufferSize: ${bufferSize}`); + const uploadCallback = (progress) => { + core.info(`Uploaded bytes ${progress.loadedBytes}`); + uploadByteCount = progress.loadedBytes; + }; + const options = { + blobHTTPHeaders: { blobContentType: 'zip' }, + onProgress: uploadCallback + }; + let sha256Hash = undefined; + const uploadStream = new stream.PassThrough(); + const hashStream = crypto.createHash('sha256'); + zipUploadStream.pipe(uploadStream); // This stream is used for the upload + zipUploadStream.pipe(hashStream).setEncoding('hex'); // This stream is used to compute a hash of the zip content that gets used. Integrity check + core.info('Beginning upload of artifact content to blob storage'); + try { + yield blockBlobClient.uploadStream(uploadStream, bufferSize, maxConcurrency, options); + } + catch (error) { + if (errors_1.NetworkError.isNetworkErrorCode(error === null || error === void 0 ? void 0 : error.code)) { + throw new errors_1.NetworkError(error === null || error === void 0 ? void 0 : error.code); } - catch (error) { - (0, core_1.warning)(`Download Artifact failed with error: ${error}. + throw error; + } + core.info('Finished uploading artifact content to blob storage!'); + hashStream.end(); + sha256Hash = hashStream.read(); + core.info(`SHA256 hash of uploaded artifact zip is ${sha256Hash}`); + if (uploadByteCount === 0) { + core.warning(`No data was uploaded to blob storage. Reported upload byte count is 0.`); + } + return { + uploadSize: uploadByteCount, + sha256Hash + }; + }); +} +exports.uploadZipToBlobStorage = uploadZipToBlobStorage; +//# sourceMappingURL=blob-upload.js.map -Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. +/***/ }), -If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); - throw error; - } - }); - } - listArtifacts(options) { - return __awaiter(this, void 0, void 0, function* () { - try { - if ((0, config_1.isGhes)()) { - throw new errors_1.GHESNotSupportedError(); - } - if (options === null || options === void 0 ? void 0 : options.findBy) { - const { findBy: { workflowRunId, repositoryOwner, repositoryName, token } } = options; - return (0, list_artifacts_1.listArtifactsPublic)(workflowRunId, repositoryOwner, repositoryName, token, options === null || options === void 0 ? void 0 : options.latest); - } - return (0, list_artifacts_1.listArtifactsInternal)(options === null || options === void 0 ? void 0 : options.latest); - } - catch (error) { - (0, core_1.warning)(`Listing Artifacts failed with error: ${error}. +/***/ 63219: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. +"use strict"; -If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); - throw error; - } - }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.validateFilePath = exports.validateArtifactName = void 0; +const core_1 = __nccwpck_require__(42186); +/** + * Invalid characters that cannot be in the artifact name or an uploaded file. Will be rejected + * from the server if attempted to be sent over. These characters are not allowed due to limitations with certain + * file systems such as NTFS. To maintain platform-agnostic behavior, all characters that are not supported by an + * individual filesystem/platform will not be supported on all fileSystems/platforms + * + * FilePaths can include characters such as \ and / which are not permitted in the artifact name alone + */ +const invalidArtifactFilePathCharacters = new Map([ + ['"', ' Double quote "'], + [':', ' Colon :'], + ['<', ' Less than <'], + ['>', ' Greater than >'], + ['|', ' Vertical bar |'], + ['*', ' Asterisk *'], + ['?', ' Question mark ?'], + ['\r', ' Carriage return \\r'], + ['\n', ' Line feed \\n'] +]); +const invalidArtifactNameCharacters = new Map([ + ...invalidArtifactFilePathCharacters, + ['\\', ' Backslash \\'], + ['/', ' Forward slash /'] +]); +/** + * Validates the name of the artifact to check to make sure there are no illegal characters + */ +function validateArtifactName(name) { + if (!name) { + throw new Error(`Provided artifact name input during validation is empty`); } - getArtifact(artifactName, options) { - return __awaiter(this, void 0, void 0, function* () { - try { - if ((0, config_1.isGhes)()) { - throw new errors_1.GHESNotSupportedError(); - } - if (options === null || options === void 0 ? void 0 : options.findBy) { - const { findBy: { workflowRunId, repositoryOwner, repositoryName, token } } = options; - return (0, get_artifact_1.getArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token); - } - return (0, get_artifact_1.getArtifactInternal)(artifactName); - } - catch (error) { - (0, core_1.warning)(`Get Artifact failed with error: ${error}. + for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactNameCharacters) { + if (name.includes(invalidCharacterKey)) { + throw new Error(`The artifact name is not valid: ${name}. Contains the following character: ${errorMessageForCharacter} + +Invalid characters include: ${Array.from(invalidArtifactNameCharacters.values()).toString()} + +These characters are not allowed in the artifact name due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems.`); + } + } + (0, core_1.info)(`Artifact name is valid!`); +} +exports.validateArtifactName = validateArtifactName; +/** + * Validates file paths to check for any illegal characters that can cause problems on different file systems + */ +function validateFilePath(path) { + if (!path) { + throw new Error(`Provided file path input during validation is empty`); + } + for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactFilePathCharacters) { + if (path.includes(invalidCharacterKey)) { + throw new Error(`The path for one of the files in artifact is not valid: ${path}. Contains the following character: ${errorMessageForCharacter} + +Invalid characters include: ${Array.from(invalidArtifactFilePathCharacters.values()).toString()} + +The following characters are not allowed in files that are uploaded due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems. + `); + } + } +} +exports.validateFilePath = validateFilePath; +//# sourceMappingURL=path-and-artifact-name-validation.js.map -Errors can be temporary, so please try again and optionally run the action with debug mode enabled for more information. +/***/ }), -If the error persists, please check whether Actions and API requests are operating normally at [https://githubstatus.com](https://www.githubstatus.com).`); - throw error; - } - }); +/***/ 3231: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getExpiration = void 0; +const generated_1 = __nccwpck_require__(49960); +const core = __importStar(__nccwpck_require__(42186)); +function getExpiration(retentionDays) { + if (!retentionDays) { + return undefined; + } + const maxRetentionDays = getRetentionDays(); + if (maxRetentionDays && maxRetentionDays < retentionDays) { + core.warning(`Retention days cannot be greater than the maximum allowed retention set within the repository. Using ${maxRetentionDays} instead.`); + retentionDays = maxRetentionDays; } + const expirationDate = new Date(); + expirationDate.setDate(expirationDate.getDate() + retentionDays); + return generated_1.Timestamp.fromDate(expirationDate); } -exports.DefaultArtifactClient = DefaultArtifactClient; -//# sourceMappingURL=client.js.map +exports.getExpiration = getExpiration; +function getRetentionDays() { + const retentionDays = process.env['GITHUB_RETENTION_DAYS']; + if (!retentionDays) { + return undefined; + } + const days = parseInt(retentionDays); + if (isNaN(days)) { + return undefined; + } + return days; +} +//# sourceMappingURL=retention.js.map /***/ }), -/***/ 17306: +/***/ 42578: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -5133,140 +3150,200 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.downloadArtifactInternal = exports.downloadArtifactPublic = void 0; -const promises_1 = __importDefault(__nccwpck_require__(73292)); -const github = __importStar(__nccwpck_require__(51132)); -const core = __importStar(__nccwpck_require__(66526)); -const httpClient = __importStar(__nccwpck_require__(52932)); -const unzipper_1 = __importDefault(__nccwpck_require__(80686)); -const user_agent_1 = __nccwpck_require__(79681); -const config_1 = __nccwpck_require__(95042); -const artifact_twirp_client_1 = __nccwpck_require__(63550); -const generated_1 = __nccwpck_require__(90265); -const util_1 = __nccwpck_require__(80565); -const errors_1 = __nccwpck_require__(69398); -const scrubQueryParameters = (url) => { - const parsed = new URL(url); - parsed.search = ''; - return parsed.toString(); -}; -function exists(path) { - return __awaiter(this, void 0, void 0, function* () { - try { - yield promises_1.default.access(path); - return true; - } - catch (error) { - if (error.code === 'ENOENT') { - return false; - } - else { - throw error; - } - } - }); -} -function streamExtract(url, directory) { - return __awaiter(this, void 0, void 0, function* () { - const client = new httpClient.HttpClient((0, user_agent_1.getUserAgentString)()); - const response = yield client.get(url); - if (response.message.statusCode !== 200) { - throw new Error(`Unexpected HTTP response from blob storage: ${response.message.statusCode} ${response.message.statusMessage}`); - } - return response.message.pipe(unzipper_1.default.Extract({ path: directory })).promise(); - }); -} -function downloadArtifactPublic(artifactId, repositoryOwner, repositoryName, token, options) { +exports.uploadArtifact = void 0; +const core = __importStar(__nccwpck_require__(42186)); +const retention_1 = __nccwpck_require__(3231); +const path_and_artifact_name_validation_1 = __nccwpck_require__(63219); +const artifact_twirp_client_1 = __nccwpck_require__(12312); +const upload_zip_specification_1 = __nccwpck_require__(17837); +const util_1 = __nccwpck_require__(63062); +const blob_upload_1 = __nccwpck_require__(7246); +const zip_1 = __nccwpck_require__(69186); +const generated_1 = __nccwpck_require__(49960); +const errors_1 = __nccwpck_require__(38182); +function uploadArtifact(name, files, rootDirectory, options) { return __awaiter(this, void 0, void 0, function* () { - const downloadPath = yield resolveOrCreateDirectory(options === null || options === void 0 ? void 0 : options.path); - const api = github.getOctokit(token); - core.info(`Downloading artifact '${artifactId}' from '${repositoryOwner}/${repositoryName}'`); - const { headers, status } = yield api.rest.actions.downloadArtifact({ - owner: repositoryOwner, - repo: repositoryName, - artifact_id: artifactId, - archive_format: 'zip', - request: { - redirect: 'manual' - } - }); - if (status !== 302) { - throw new Error(`Unable to download artifact. Unexpected status: ${status}`); - } - const { location } = headers; - if (!location) { - throw new Error(`Unable to redirect to artifact download url`); - } - core.info(`Redirecting to blob download url: ${scrubQueryParameters(location)}`); - try { - core.info(`Starting download of artifact to: ${downloadPath}`); - yield streamExtract(location, downloadPath); - core.info(`Artifact download completed successfully.`); - } - catch (error) { - throw new Error(`Unable to download and extract artifact: ${error.message}`); + (0, path_and_artifact_name_validation_1.validateArtifactName)(name); + (0, upload_zip_specification_1.validateRootDirectory)(rootDirectory); + const zipSpecification = (0, upload_zip_specification_1.getUploadZipSpecification)(files, rootDirectory); + if (zipSpecification.length === 0) { + throw new errors_1.FilesNotFoundError(zipSpecification.flatMap(s => (s.sourcePath ? [s.sourcePath] : []))); } - return { downloadPath }; - }); -} -exports.downloadArtifactPublic = downloadArtifactPublic; -function downloadArtifactInternal(artifactId, options) { - return __awaiter(this, void 0, void 0, function* () { - const downloadPath = yield resolveOrCreateDirectory(options === null || options === void 0 ? void 0 : options.path); + // get the IDs needed for the artifact creation + const backendIds = (0, util_1.getBackendIdsFromToken)(); + // create the artifact client const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); - const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)(); - const listReq = { - workflowRunBackendId, - workflowJobRunBackendId, - idFilter: generated_1.Int64Value.create({ value: artifactId.toString() }) + // create the artifact + const createArtifactReq = { + workflowRunBackendId: backendIds.workflowRunBackendId, + workflowJobRunBackendId: backendIds.workflowJobRunBackendId, + name, + version: 4 }; - const { artifacts } = yield artifactClient.ListArtifacts(listReq); - if (artifacts.length === 0) { - throw new errors_1.ArtifactNotFoundError(`No artifacts found for ID: ${artifactId}\nAre you trying to download from a different run? Try specifying a github-token with \`actions:read\` scope.`); + // if there is a retention period, add it to the request + const expiresAt = (0, retention_1.getExpiration)(options === null || options === void 0 ? void 0 : options.retentionDays); + if (expiresAt) { + createArtifactReq.expiresAt = expiresAt; } - if (artifacts.length > 1) { - core.warning('Multiple artifacts found, defaulting to first.'); + const createArtifactResp = yield artifactClient.CreateArtifact(createArtifactReq); + if (!createArtifactResp.ok) { + throw new errors_1.InvalidResponseError('CreateArtifact: response from backend was not ok'); } - const signedReq = { - workflowRunBackendId: artifacts[0].workflowRunBackendId, - workflowJobRunBackendId: artifacts[0].workflowJobRunBackendId, - name: artifacts[0].name + const zipUploadStream = yield (0, zip_1.createZipUploadStream)(zipSpecification, options === null || options === void 0 ? void 0 : options.compressionLevel); + // Upload zip to blob storage + const uploadResult = yield (0, blob_upload_1.uploadZipToBlobStorage)(createArtifactResp.signedUploadUrl, zipUploadStream); + // finalize the artifact + const finalizeArtifactReq = { + workflowRunBackendId: backendIds.workflowRunBackendId, + workflowJobRunBackendId: backendIds.workflowJobRunBackendId, + name, + size: uploadResult.uploadSize ? uploadResult.uploadSize.toString() : '0' }; - const { signedUrl } = yield artifactClient.GetSignedArtifactURL(signedReq); - core.info(`Redirecting to blob download url: ${scrubQueryParameters(signedUrl)}`); - try { - core.info(`Starting download of artifact to: ${downloadPath}`); - yield streamExtract(signedUrl, downloadPath); - core.info(`Artifact download completed successfully.`); + if (uploadResult.sha256Hash) { + finalizeArtifactReq.hash = generated_1.StringValue.create({ + value: `sha256:${uploadResult.sha256Hash}` + }); } - catch (error) { - throw new Error(`Unable to download and extract artifact: ${error.message}`); + core.info(`Finalizing artifact upload`); + const finalizeArtifactResp = yield artifactClient.FinalizeArtifact(finalizeArtifactReq); + if (!finalizeArtifactResp.ok) { + throw new errors_1.InvalidResponseError('FinalizeArtifact: response from backend was not ok'); } - return { downloadPath }; + const artifactId = BigInt(finalizeArtifactResp.artifactId); + core.info(`Artifact ${name}.zip successfully finalized. Artifact ID ${artifactId}`); + return { + size: uploadResult.uploadSize, + id: Number(artifactId) + }; }); } -exports.downloadArtifactInternal = downloadArtifactInternal; -function resolveOrCreateDirectory(downloadPath = (0, config_1.getGitHubWorkspaceDir)()) { - return __awaiter(this, void 0, void 0, function* () { - if (!(yield exists(downloadPath))) { - core.debug(`Artifact destination folder does not exist, creating: ${downloadPath}`); - yield promises_1.default.mkdir(downloadPath, { recursive: true }); +exports.uploadArtifact = uploadArtifact; +//# sourceMappingURL=upload-artifact.js.map + +/***/ }), + +/***/ 17837: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getUploadZipSpecification = exports.validateRootDirectory = void 0; +const fs = __importStar(__nccwpck_require__(57147)); +const core_1 = __nccwpck_require__(42186); +const path_1 = __nccwpck_require__(71017); +const path_and_artifact_name_validation_1 = __nccwpck_require__(63219); +/** + * Checks if a root directory exists and is valid + * @param rootDirectory an absolute root directory path common to all input files that that will be trimmed from the final zip structure + */ +function validateRootDirectory(rootDirectory) { + if (!fs.existsSync(rootDirectory)) { + throw new Error(`The provided rootDirectory ${rootDirectory} does not exist`); + } + if (!fs.statSync(rootDirectory).isDirectory()) { + throw new Error(`The provided rootDirectory ${rootDirectory} is not a valid directory`); + } + (0, core_1.info)(`Root directory input is valid!`); +} +exports.validateRootDirectory = validateRootDirectory; +/** + * Creates a specification that describes how a zip file will be created for a set of input files + * @param filesToZip a list of file that should be included in the zip + * @param rootDirectory an absolute root directory path common to all input files that that will be trimmed from the final zip structure + */ +function getUploadZipSpecification(filesToZip, rootDirectory) { + const specification = []; + // Normalize and resolve, this allows for either absolute or relative paths to be used + rootDirectory = (0, path_1.normalize)(rootDirectory); + rootDirectory = (0, path_1.resolve)(rootDirectory); + /* + Example + + Input: + rootDirectory: '/home/user/files/plz-upload' + artifactFiles: [ + '/home/user/files/plz-upload/file1.txt', + '/home/user/files/plz-upload/file2.txt', + '/home/user/files/plz-upload/dir/file3.txt' + ] + + Output: + specifications: [ + ['/home/user/files/plz-upload/file1.txt', '/file1.txt'], + ['/home/user/files/plz-upload/file1.txt', '/file2.txt'], + ['/home/user/files/plz-upload/file1.txt', '/dir/file3.txt'] + ] + + The final zip that is later uploaded will look like this: + + my-artifact.zip + - file.txt + - file2.txt + - dir/ + - file3.txt + */ + for (let file of filesToZip) { + if (!fs.existsSync(file)) { + throw new Error(`File ${file} does not exist`); + } + if (!fs.statSync(file).isDirectory()) { + // Normalize and resolve, this allows for either absolute or relative paths to be used + file = (0, path_1.normalize)(file); + file = (0, path_1.resolve)(file); + if (!file.startsWith(rootDirectory)) { + throw new Error(`The rootDirectory: ${rootDirectory} is not a parent directory of the file: ${file}`); + } + // Check for forbidden characters in file paths that may cause ambiguous behavior if downloaded on different file systems + const uploadPath = file.replace(rootDirectory, ''); + (0, path_and_artifact_name_validation_1.validateFilePath)(uploadPath); + specification.push({ + sourcePath: file, + destinationPath: uploadPath + }); } else { - core.debug(`Artifact destination folder already exists: ${downloadPath}`); + // Empty directory + const directoryPath = file.replace(rootDirectory, ''); + (0, path_and_artifact_name_validation_1.validateFilePath)(directoryPath); + specification.push({ + sourcePath: null, + destinationPath: directoryPath + }); } - return downloadPath; - }); + } + return specification; } -//# sourceMappingURL=download-artifact.js.map +exports.getUploadZipSpecification = getUploadZipSpecification; +//# sourceMappingURL=upload-zip-specification.js.map /***/ }), -/***/ 56218: +/***/ 69186: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -5304,251 +3381,96 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getArtifactInternal = exports.getArtifactPublic = void 0; -const github_1 = __nccwpck_require__(51132); -const plugin_retry_1 = __nccwpck_require__(69980); -const core = __importStar(__nccwpck_require__(66526)); -const utils_1 = __nccwpck_require__(43129); -const retry_options_1 = __nccwpck_require__(80722); -const plugin_request_log_1 = __nccwpck_require__(73665); -const util_1 = __nccwpck_require__(80565); -const user_agent_1 = __nccwpck_require__(79681); -const artifact_twirp_client_1 = __nccwpck_require__(63550); -const generated_1 = __nccwpck_require__(90265); -const errors_1 = __nccwpck_require__(69398); -function getArtifactPublic(artifactName, workflowRunId, repositoryOwner, repositoryName, token) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults); - const opts = { - log: undefined, - userAgent: (0, user_agent_1.getUserAgentString)(), - previews: undefined, - retry: retryOpts, - request: requestOpts - }; - const github = (0, github_1.getOctokit)(token, opts, plugin_retry_1.retry, plugin_request_log_1.requestLog); - const getArtifactResp = yield github.request('GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts{?name}', { - owner: repositoryOwner, - repo: repositoryName, - run_id: workflowRunId, - name: artifactName +exports.createZipUploadStream = exports.ZipUploadStream = exports.DEFAULT_COMPRESSION_LEVEL = void 0; +const stream = __importStar(__nccwpck_require__(12781)); +const archiver = __importStar(__nccwpck_require__(43084)); +const core = __importStar(__nccwpck_require__(42186)); +const fs_1 = __nccwpck_require__(57147); +const config_1 = __nccwpck_require__(74610); +exports.DEFAULT_COMPRESSION_LEVEL = 6; +// Custom stream transformer so we can set the highWaterMark property +// See https://github.com/nodejs/node/issues/8855 +class ZipUploadStream extends stream.Transform { + constructor(bufferSize) { + super({ + highWaterMark: bufferSize }); - if (getArtifactResp.status !== 200) { - throw new errors_1.InvalidResponseError(`Invalid response from GitHub API: ${getArtifactResp.status} (${(_a = getArtifactResp === null || getArtifactResp === void 0 ? void 0 : getArtifactResp.headers) === null || _a === void 0 ? void 0 : _a['x-github-request-id']})`); - } - if (getArtifactResp.data.artifacts.length === 0) { - throw new errors_1.ArtifactNotFoundError(`Artifact not found for name: ${artifactName}`); - } - let artifact = getArtifactResp.data.artifacts[0]; - if (getArtifactResp.data.artifacts.length > 1) { - artifact = getArtifactResp.data.artifacts.sort((a, b) => b.id - a.id)[0]; - core.debug(`More than one artifact found for a single name, returning newest (id: ${artifact.id})`); - } - return { - artifact: { - name: artifact.name, - id: artifact.id, - size: artifact.size_in_bytes, - createdAt: artifact.created_at ? new Date(artifact.created_at) : undefined - } - }; - }); -} -exports.getArtifactPublic = getArtifactPublic; -function getArtifactInternal(artifactName) { - return __awaiter(this, void 0, void 0, function* () { - const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); - const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)(); - const req = { - workflowRunBackendId, - workflowJobRunBackendId, - nameFilter: generated_1.StringValue.create({ value: artifactName }) - }; - const res = yield artifactClient.ListArtifacts(req); - if (res.artifacts.length === 0) { - throw new errors_1.ArtifactNotFoundError(`Artifact not found for name: ${artifactName}`); - } - let artifact = res.artifacts[0]; - if (res.artifacts.length > 1) { - artifact = res.artifacts.sort((a, b) => Number(b.databaseId) - Number(a.databaseId))[0]; - core.debug(`More than one artifact found for a single name, returning newest (id: ${artifact.databaseId})`); - } - return { - artifact: { - name: artifact.name, - id: Number(artifact.databaseId), - size: Number(artifact.size), - createdAt: artifact.createdAt - ? generated_1.Timestamp.toDate(artifact.createdAt) - : undefined - } - }; - }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + _transform(chunk, enc, cb) { + cb(null, chunk); + } } -exports.getArtifactInternal = getArtifactInternal; -//# sourceMappingURL=get-artifact.js.map - -/***/ }), - -/***/ 64033: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.listArtifactsInternal = exports.listArtifactsPublic = void 0; -const core_1 = __nccwpck_require__(66526); -const github_1 = __nccwpck_require__(51132); -const user_agent_1 = __nccwpck_require__(79681); -const retry_options_1 = __nccwpck_require__(80722); -const utils_1 = __nccwpck_require__(43129); -const plugin_request_log_1 = __nccwpck_require__(73665); -const plugin_retry_1 = __nccwpck_require__(69980); -const artifact_twirp_client_1 = __nccwpck_require__(63550); -const util_1 = __nccwpck_require__(80565); -const generated_1 = __nccwpck_require__(90265); -// Limiting to 1000 for perf reasons -const maximumArtifactCount = 1000; -const paginationCount = 100; -const maxNumberOfPages = maximumArtifactCount / paginationCount; -function listArtifactsPublic(workflowRunId, repositoryOwner, repositoryName, token, latest = false) { +exports.ZipUploadStream = ZipUploadStream; +function createZipUploadStream(uploadSpecification, compressionLevel = exports.DEFAULT_COMPRESSION_LEVEL) { return __awaiter(this, void 0, void 0, function* () { - (0, core_1.info)(`Fetching artifact list for workflow run ${workflowRunId} in repository ${repositoryOwner}/${repositoryName}`); - let artifacts = []; - const [retryOpts, requestOpts] = (0, retry_options_1.getRetryOptions)(utils_1.defaults); - const opts = { - log: undefined, - userAgent: (0, user_agent_1.getUserAgentString)(), - previews: undefined, - retry: retryOpts, - request: requestOpts - }; - const github = (0, github_1.getOctokit)(token, opts, plugin_retry_1.retry, plugin_request_log_1.requestLog); - let currentPageNumber = 1; - const { data: listArtifactResponse } = yield github.rest.actions.listWorkflowRunArtifacts({ - owner: repositoryOwner, - repo: repositoryName, - run_id: workflowRunId, - per_page: paginationCount, - page: currentPageNumber + core.debug(`Creating Artifact archive with compressionLevel: ${compressionLevel}`); + const zip = archiver.create('zip', { + highWaterMark: (0, config_1.getUploadChunkSize)(), + zlib: { level: compressionLevel } }); - let numberOfPages = Math.ceil(listArtifactResponse.total_count / paginationCount); - const totalArtifactCount = listArtifactResponse.total_count; - if (totalArtifactCount > maximumArtifactCount) { - (0, core_1.warning)(`Workflow run ${workflowRunId} has more than 1000 artifacts. Results will be incomplete as only the first ${maximumArtifactCount} artifacts will be returned`); - numberOfPages = maxNumberOfPages; - } - // Iterate over the first page - for (const artifact of listArtifactResponse.artifacts) { - artifacts.push({ - name: artifact.name, - id: artifact.id, - size: artifact.size_in_bytes, - createdAt: artifact.created_at ? new Date(artifact.created_at) : undefined - }); - } - // Iterate over any remaining pages - for (currentPageNumber; currentPageNumber < numberOfPages; currentPageNumber++) { - currentPageNumber++; - (0, core_1.debug)(`Fetching page ${currentPageNumber} of artifact list`); - const { data: listArtifactResponse } = yield github.rest.actions.listWorkflowRunArtifacts({ - owner: repositoryOwner, - repo: repositoryName, - run_id: workflowRunId, - per_page: paginationCount, - page: currentPageNumber - }); - for (const artifact of listArtifactResponse.artifacts) { - artifacts.push({ - name: artifact.name, - id: artifact.id, - size: artifact.size_in_bytes, - createdAt: artifact.created_at - ? new Date(artifact.created_at) - : undefined + // register callbacks for various events during the zip lifecycle + zip.on('error', zipErrorCallback); + zip.on('warning', zipWarningCallback); + zip.on('finish', zipFinishCallback); + zip.on('end', zipEndCallback); + for (const file of uploadSpecification) { + if (file.sourcePath !== null) { + // Add a normal file to the zip + zip.append((0, fs_1.createReadStream)(file.sourcePath), { + name: file.destinationPath }); } + else { + // Add a directory to the zip + zip.append('', { name: file.destinationPath }); + } } - if (latest) { - artifacts = filterLatest(artifacts); - } - (0, core_1.info)(`Found ${artifacts.length} artifact(s)`); - return { - artifacts - }; - }); -} -exports.listArtifactsPublic = listArtifactsPublic; -function listArtifactsInternal(latest = false) { - return __awaiter(this, void 0, void 0, function* () { - const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); - const { workflowRunBackendId, workflowJobRunBackendId } = (0, util_1.getBackendIdsFromToken)(); - const req = { - workflowRunBackendId, - workflowJobRunBackendId - }; - const res = yield artifactClient.ListArtifacts(req); - let artifacts = res.artifacts.map(artifact => ({ - name: artifact.name, - id: Number(artifact.databaseId), - size: Number(artifact.size), - createdAt: artifact.createdAt - ? generated_1.Timestamp.toDate(artifact.createdAt) - : undefined - })); - if (latest) { - artifacts = filterLatest(artifacts); - } - (0, core_1.info)(`Found ${artifacts.length} artifact(s)`); - return { - artifacts - }; + const bufferSize = (0, config_1.getUploadChunkSize)(); + const zipUploadStream = new ZipUploadStream(bufferSize); + core.debug(`Zip write high watermark value ${zipUploadStream.writableHighWaterMark}`); + core.debug(`Zip read high watermark value ${zipUploadStream.readableHighWaterMark}`); + zip.pipe(zipUploadStream); + zip.finalize(); + return zipUploadStream; }); } -exports.listArtifactsInternal = listArtifactsInternal; -/** - * Filters a list of artifacts to only include the latest artifact for each name - * @param artifacts The artifacts to filter - * @returns The filtered list of artifacts - */ -function filterLatest(artifacts) { - artifacts.sort((a, b) => b.id - a.id); - const latestArtifacts = []; - const seenArtifactNames = new Set(); - for (const artifact of artifacts) { - if (!seenArtifactNames.has(artifact.name)) { - latestArtifacts.push(artifact); - seenArtifactNames.add(artifact.name); - } +exports.createZipUploadStream = createZipUploadStream; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const zipErrorCallback = (error) => { + core.error('An error has occurred while creating the zip file for upload'); + core.info(error); + throw new Error('An error has occurred during zip creation for the artifact'); +}; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const zipWarningCallback = (error) => { + if (error.code === 'ENOENT') { + core.warning('ENOENT warning during artifact zip creation. No such file or directory'); + core.info(error); } - return latestArtifacts; -} -//# sourceMappingURL=list-artifacts.js.map + else { + core.warning(`A non-blocking warning has occurred during artifact zip creation: ${error.code}`); + core.info(error); + } +}; +const zipFinishCallback = () => { + core.debug('Zip stream for upload has finished.'); +}; +const zipEndCallback = () => { + core.debug('Zip stream for upload has ended.'); +}; +//# sourceMappingURL=zip.js.map /***/ }), -/***/ 80722: +/***/ 87351: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -5561,44 +3483,109 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getRetryOptions = void 0; -const core = __importStar(__nccwpck_require__(66526)); -// Defaults for fetching artifacts -const defaultMaxRetryNumber = 5; -const defaultExemptStatusCodes = [400, 401, 403, 404, 422]; // https://github.com/octokit/plugin-retry.js/blob/9a2443746c350b3beedec35cf26e197ea318a261/src/index.ts#L14 -function getRetryOptions(defaultOptions, retries = defaultMaxRetryNumber, exemptStatusCodes = defaultExemptStatusCodes) { - var _a; - if (retries <= 0) { - return [{ enabled: false }, defaultOptions.request]; +exports.issue = exports.issueCommand = void 0; +const os = __importStar(__nccwpck_require__(22037)); +const utils_1 = __nccwpck_require__(5278); +/** + * Commands + * + * Command Format: + * ::name key=value,key=value::message + * + * Examples: + * ::warning::This is the message + * ::set-env name=MY_VAR::some value + */ +function issueCommand(command, properties, message) { + const cmd = new Command(command, properties, message); + process.stdout.write(cmd.toString() + os.EOL); +} +exports.issueCommand = issueCommand; +function issue(name, message = '') { + issueCommand(name, {}, message); +} +exports.issue = issue; +const CMD_STRING = '::'; +class Command { + constructor(command, properties, message) { + if (!command) { + command = 'missing.command'; + } + this.command = command; + this.properties = properties; + this.message = message; } - const retryOptions = { - enabled: true - }; - if (exemptStatusCodes.length > 0) { - retryOptions.doNotRetry = exemptStatusCodes; + toString() { + let cmdStr = CMD_STRING + this.command; + if (this.properties && Object.keys(this.properties).length > 0) { + cmdStr += ' '; + let first = true; + for (const key in this.properties) { + if (this.properties.hasOwnProperty(key)) { + const val = this.properties[key]; + if (val) { + if (first) { + first = false; + } + else { + cmdStr += ','; + } + cmdStr += `${key}=${escapeProperty(val)}`; + } + } + } + } + cmdStr += `${CMD_STRING}${escapeData(this.message)}`; + return cmdStr; } - // The GitHub type has some defaults for `options.request` - // see: https://github.com/actions/toolkit/blob/4fbc5c941a57249b19562015edbd72add14be93d/packages/github/src/utils.ts#L15 - // We pass these in here so they are not overridden. - const requestOptions = Object.assign(Object.assign({}, defaultOptions.request), { retries }); - core.debug(`GitHub client configured with: (retries: ${requestOptions.retries}, retry-exempt-status-code: ${(_a = retryOptions.doNotRetry) !== null && _a !== void 0 ? _a : 'octokit default: [400, 401, 403, 404, 422]'})`); - return [retryOptions, requestOptions]; } -exports.getRetryOptions = getRetryOptions; -//# sourceMappingURL=retry-options.js.map +function escapeData(s) { + return utils_1.toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A'); +} +function escapeProperty(s) { + return utils_1.toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A') + .replace(/:/g, '%3A') + .replace(/,/g, '%2C'); +} +//# sourceMappingURL=command.js.map /***/ }), -/***/ 63550: +/***/ 42186: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { @@ -5609,284 +3596,324 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.internalArtifactTwirpClient = void 0; -const http_client_1 = __nccwpck_require__(52932); -const auth_1 = __nccwpck_require__(40903); -const core_1 = __nccwpck_require__(66526); -const generated_1 = __nccwpck_require__(90265); -const config_1 = __nccwpck_require__(95042); -const user_agent_1 = __nccwpck_require__(79681); -class ArtifactHttpClient { - constructor(userAgent, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) { - this.maxAttempts = 5; - this.baseRetryIntervalMilliseconds = 3000; - this.retryMultiplier = 1.5; - const token = (0, config_1.getRuntimeToken)(); - this.baseUrl = (0, config_1.getResultsServiceUrl)(); - if (maxAttempts) { - this.maxAttempts = maxAttempts; - } - if (baseRetryIntervalMilliseconds) { - this.baseRetryIntervalMilliseconds = baseRetryIntervalMilliseconds; - } - if (retryMultiplier) { - this.retryMultiplier = retryMultiplier; - } - this.httpClient = new http_client_1.HttpClient(userAgent, [ - new auth_1.BearerCredentialHandler(token) - ]); - } - // This function satisfies the Rpc interface. It is compatible with the JSON - // JSON generated client. - request(service, method, contentType, data) { - return __awaiter(this, void 0, void 0, function* () { - const url = new URL(`/twirp/${service}/${method}`, this.baseUrl).href; - (0, core_1.debug)(`[Request] ${method} ${url}`); - const headers = { - 'Content-Type': contentType - }; - try { - const { body } = yield this.retryableRequest(() => __awaiter(this, void 0, void 0, function* () { return this.httpClient.post(url, JSON.stringify(data), headers); })); - return JSON.parse(body); - } - catch (error) { - throw new Error(`Failed to ${method}: ${error.message}`); - } - }); +exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; +const command_1 = __nccwpck_require__(87351); +const file_command_1 = __nccwpck_require__(717); +const utils_1 = __nccwpck_require__(5278); +const os = __importStar(__nccwpck_require__(22037)); +const path = __importStar(__nccwpck_require__(71017)); +const oidc_utils_1 = __nccwpck_require__(98041); +/** + * The code to exit an action + */ +var ExitCode; +(function (ExitCode) { + /** + * A code indicating that the action was successful + */ + ExitCode[ExitCode["Success"] = 0] = "Success"; + /** + * A code indicating that the action was a failure + */ + ExitCode[ExitCode["Failure"] = 1] = "Failure"; +})(ExitCode = exports.ExitCode || (exports.ExitCode = {})); +//----------------------------------------------------------------------- +// Variables +//----------------------------------------------------------------------- +/** + * Sets env variable for this action and future actions in the job + * @param name the name of the variable to set + * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function exportVariable(name, val) { + const convertedVal = utils_1.toCommandValue(val); + process.env[name] = convertedVal; + const filePath = process.env['GITHUB_ENV'] || ''; + if (filePath) { + return file_command_1.issueFileCommand('ENV', file_command_1.prepareKeyValueMessage(name, val)); } - retryableRequest(operation) { - return __awaiter(this, void 0, void 0, function* () { - let attempt = 0; - let errorMessage = ''; - while (attempt < this.maxAttempts) { - let isRetryable = false; - try { - const response = yield operation(); - const statusCode = response.message.statusCode; - const body = yield response.readBody(); - (0, core_1.debug)(`[Response] - ${response.message.statusCode}`); - (0, core_1.debug)(`Headers: ${JSON.stringify(response.message.headers, null, 2)}`); - (0, core_1.debug)(`Body: ${body}`); - if (this.isSuccessStatusCode(statusCode)) { - return { response, body }; - } - isRetryable = this.isRetryableHttpStatusCode(statusCode); - errorMessage = `Failed request: (${statusCode}) ${response.message.statusMessage}`; - const responseMessage = JSON.parse(body).msg; - if (responseMessage) { - errorMessage = `${errorMessage}: ${responseMessage}`; - } - } - catch (error) { - isRetryable = true; - errorMessage = error.message; - } - if (!isRetryable) { - throw new Error(`Received non-retryable error: ${errorMessage}`); - } - if (attempt + 1 === this.maxAttempts) { - throw new Error(`Failed to make request after ${this.maxAttempts} attempts: ${errorMessage}`); - } - const retryTimeMilliseconds = this.getExponentialRetryTimeMilliseconds(attempt); - (0, core_1.info)(`Attempt ${attempt + 1} of ${this.maxAttempts} failed with error: ${errorMessage}. Retrying request in ${retryTimeMilliseconds} ms...`); - yield this.sleep(retryTimeMilliseconds); - attempt++; - } - throw new Error(`Request failed`); - }); + command_1.issueCommand('set-env', { name }, convertedVal); +} +exports.exportVariable = exportVariable; +/** + * Registers a secret which will get masked from logs + * @param secret value of the secret + */ +function setSecret(secret) { + command_1.issueCommand('add-mask', {}, secret); +} +exports.setSecret = setSecret; +/** + * Prepends inputPath to the PATH (for this action and future actions) + * @param inputPath + */ +function addPath(inputPath) { + const filePath = process.env['GITHUB_PATH'] || ''; + if (filePath) { + file_command_1.issueFileCommand('PATH', inputPath); } - isSuccessStatusCode(statusCode) { - if (!statusCode) - return false; - return statusCode >= 200 && statusCode < 300; + else { + command_1.issueCommand('add-path', {}, inputPath); } - isRetryableHttpStatusCode(statusCode) { - if (!statusCode) - return false; - const retryableStatusCodes = [ - http_client_1.HttpCodes.BadGateway, - http_client_1.HttpCodes.GatewayTimeout, - http_client_1.HttpCodes.InternalServerError, - http_client_1.HttpCodes.ServiceUnavailable, - http_client_1.HttpCodes.TooManyRequests - ]; - return retryableStatusCodes.includes(statusCode); - } - sleep(milliseconds) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise(resolve => setTimeout(resolve, milliseconds)); - }); + process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; +} +exports.addPath = addPath; +/** + * Gets the value of an input. + * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. + * Returns an empty string if the value is not defined. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string + */ +function getInput(name, options) { + const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; + if (options && options.required && !val) { + throw new Error(`Input required and not supplied: ${name}`); } - getExponentialRetryTimeMilliseconds(attempt) { - if (attempt < 0) { - throw new Error('attempt should be a positive integer'); - } - if (attempt === 0) { - return this.baseRetryIntervalMilliseconds; - } - const minTime = this.baseRetryIntervalMilliseconds * Math.pow(this.retryMultiplier, attempt); - const maxTime = minTime * this.retryMultiplier; - // returns a random number between minTime and maxTime (exclusive) - return Math.trunc(Math.random() * (maxTime - minTime) + minTime); + if (options && options.trimWhitespace === false) { + return val; } + return val.trim(); } -function internalArtifactTwirpClient(options) { - const client = new ArtifactHttpClient((0, user_agent_1.getUserAgentString)(), options === null || options === void 0 ? void 0 : options.maxAttempts, options === null || options === void 0 ? void 0 : options.retryIntervalMs, options === null || options === void 0 ? void 0 : options.retryMultiplier); - return new generated_1.ArtifactServiceClientJSON(client); +exports.getInput = getInput; +/** + * Gets the values of an multiline input. Each value is also trimmed. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string[] + * + */ +function getMultilineInput(name, options) { + const inputs = getInput(name, options) + .split('\n') + .filter(x => x !== ''); + if (options && options.trimWhitespace === false) { + return inputs; + } + return inputs.map(input => input.trim()); } -exports.internalArtifactTwirpClient = internalArtifactTwirpClient; -//# sourceMappingURL=artifact-twirp-client.js.map - -/***/ }), - -/***/ 95042: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getConcurrency = exports.getGitHubWorkspaceDir = exports.isGhes = exports.getResultsServiceUrl = exports.getRuntimeToken = exports.getUploadChunkSize = void 0; -const os_1 = __importDefault(__nccwpck_require__(22037)); -// Used for controlling the highWaterMark value of the zip that is being streamed -// The same value is used as the chunk size that is use during upload to blob storage -function getUploadChunkSize() { - return 8 * 1024 * 1024; // 8 MB Chunks +exports.getMultilineInput = getMultilineInput; +/** + * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. + * Support boolean input list: `true | True | TRUE | false | False | FALSE` . + * The return value is also in boolean type. + * ref: https://yaml.org/spec/1.2/spec.html#id2804923 + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns boolean + */ +function getBooleanInput(name, options) { + const trueValue = ['true', 'True', 'TRUE']; + const falseValue = ['false', 'False', 'FALSE']; + const val = getInput(name, options); + if (trueValue.includes(val)) + return true; + if (falseValue.includes(val)) + return false; + throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + + `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); } -exports.getUploadChunkSize = getUploadChunkSize; -function getRuntimeToken() { - const token = process.env['ACTIONS_RUNTIME_TOKEN']; - if (!token) { - throw new Error('Unable to get the ACTIONS_RUNTIME_TOKEN env variable'); +exports.getBooleanInput = getBooleanInput; +/** + * Sets the value of an output. + * + * @param name name of the output to set + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function setOutput(name, value) { + const filePath = process.env['GITHUB_OUTPUT'] || ''; + if (filePath) { + return file_command_1.issueFileCommand('OUTPUT', file_command_1.prepareKeyValueMessage(name, value)); } - return token; + process.stdout.write(os.EOL); + command_1.issueCommand('set-output', { name }, utils_1.toCommandValue(value)); } -exports.getRuntimeToken = getRuntimeToken; -function getResultsServiceUrl() { - const resultsUrl = process.env['ACTIONS_RESULTS_URL']; - if (!resultsUrl) { - throw new Error('Unable to get the ACTIONS_RESULTS_URL env variable'); - } - return new URL(resultsUrl).origin; +exports.setOutput = setOutput; +/** + * Enables or disables the echoing of commands into stdout for the rest of the step. + * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. + * + */ +function setCommandEcho(enabled) { + command_1.issue('echo', enabled ? 'on' : 'off'); } -exports.getResultsServiceUrl = getResultsServiceUrl; -function isGhes() { - const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com'); - return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'; +exports.setCommandEcho = setCommandEcho; +//----------------------------------------------------------------------- +// Results +//----------------------------------------------------------------------- +/** + * Sets the action status to failed. + * When the action exits it will be with an exit code of 1 + * @param message add error issue message + */ +function setFailed(message) { + process.exitCode = ExitCode.Failure; + error(message); } -exports.isGhes = isGhes; -function getGitHubWorkspaceDir() { - const ghWorkspaceDir = process.env['GITHUB_WORKSPACE']; - if (!ghWorkspaceDir) { - throw new Error('Unable to get the GITHUB_WORKSPACE env variable'); - } - return ghWorkspaceDir; +exports.setFailed = setFailed; +//----------------------------------------------------------------------- +// Logging Commands +//----------------------------------------------------------------------- +/** + * Gets whether Actions Step Debug is on or not + */ +function isDebug() { + return process.env['RUNNER_DEBUG'] === '1'; } -exports.getGitHubWorkspaceDir = getGitHubWorkspaceDir; -// Mimics behavior of azcopy: https://learn.microsoft.com/en-us/azure/storage/common/storage-use-azcopy-optimize -// If your machine has fewer than 5 CPUs, then the value of this variable is set to 32. -// Otherwise, the default value is equal to 16 multiplied by the number of CPUs. The maximum value of this variable is 300. -function getConcurrency() { - const numCPUs = os_1.default.cpus().length; - if (numCPUs <= 4) { - return 32; - } - const concurrency = 16 * numCPUs; - return concurrency > 300 ? 300 : concurrency; +exports.isDebug = isDebug; +/** + * Writes debug message to user log + * @param message debug message + */ +function debug(message) { + command_1.issueCommand('debug', {}, message); } -exports.getConcurrency = getConcurrency; -//# sourceMappingURL=config.js.map - -/***/ }), - -/***/ 69398: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.GHESNotSupportedError = exports.ArtifactNotFoundError = exports.InvalidResponseError = exports.FilesNotFoundError = void 0; -class FilesNotFoundError extends Error { - constructor(files = []) { - let message = 'No files were found to upload'; - if (files.length > 0) { - message += `: ${files.join(', ')}`; - } - super(message); - this.files = files; - this.name = 'FilesNotFoundError'; - } +exports.debug = debug; +/** + * Adds an error issue + * @param message error issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function error(message, properties = {}) { + command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); } -exports.FilesNotFoundError = FilesNotFoundError; -class InvalidResponseError extends Error { - constructor(message) { - super(message); - this.name = 'InvalidResponseError'; - } +exports.error = error; +/** + * Adds a warning issue + * @param message warning issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function warning(message, properties = {}) { + command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); } -exports.InvalidResponseError = InvalidResponseError; -class ArtifactNotFoundError extends Error { - constructor(message = 'Artifact not found') { - super(message); - this.name = 'ArtifactNotFoundError'; - } +exports.warning = warning; +/** + * Adds a notice issue + * @param message notice issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function notice(message, properties = {}) { + command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); } -exports.ArtifactNotFoundError = ArtifactNotFoundError; -class GHESNotSupportedError extends Error { - constructor(message = '@actions/artifact v2.0.0+, upload-artifact@v4+ and download-artifact@v4+ are not currently supported on GHES.') { - super(message); - this.name = 'GHESNotSupportedError'; +exports.notice = notice; +/** + * Writes info to log with console.log. + * @param message info message + */ +function info(message) { + process.stdout.write(message + os.EOL); +} +exports.info = info; +/** + * Begin an output group. + * + * Output until the next `groupEnd` will be foldable in this group + * + * @param name The name of the output group + */ +function startGroup(name) { + command_1.issue('group', name); +} +exports.startGroup = startGroup; +/** + * End an output group. + */ +function endGroup() { + command_1.issue('endgroup'); +} +exports.endGroup = endGroup; +/** + * Wrap an asynchronous function call in a group. + * + * Returns the same type as the function itself. + * + * @param name The name of the group + * @param fn The function to wrap in the group + */ +function group(name, fn) { + return __awaiter(this, void 0, void 0, function* () { + startGroup(name); + let result; + try { + result = yield fn(); + } + finally { + endGroup(); + } + return result; + }); +} +exports.group = group; +//----------------------------------------------------------------------- +// Wrapper action state +//----------------------------------------------------------------------- +/** + * Saves state for current action, the state can only be retrieved by this action's post job execution. + * + * @param name name of the state to store + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function saveState(name, value) { + const filePath = process.env['GITHUB_STATE'] || ''; + if (filePath) { + return file_command_1.issueFileCommand('STATE', file_command_1.prepareKeyValueMessage(name, value)); } + command_1.issueCommand('save-state', { name }, utils_1.toCommandValue(value)); } -exports.GHESNotSupportedError = GHESNotSupportedError; -//# sourceMappingURL=errors.js.map - -/***/ }), - -/***/ 2538: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=interfaces.js.map - -/***/ }), - -/***/ 79681: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getUserAgentString = void 0; -// eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports -const packageJson = __nccwpck_require__(9303); +exports.saveState = saveState; /** - * Ensure that this User Agent String is used in all HTTP calls so that we can monitor telemetry between different versions of this package + * Gets the value of an state set by this action's main execution. + * + * @param name name of the state to get + * @returns string */ -function getUserAgentString() { - return `@actions/artifact-${packageJson.version}`; +function getState(name) { + return process.env[`STATE_${name}`] || ''; } -exports.getUserAgentString = getUserAgentString; -//# sourceMappingURL=user-agent.js.map +exports.getState = getState; +function getIDToken(aud) { + return __awaiter(this, void 0, void 0, function* () { + return yield oidc_utils_1.OidcClient.getIDToken(aud); + }); +} +exports.getIDToken = getIDToken; +/** + * Summary exports + */ +var summary_1 = __nccwpck_require__(81327); +Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); +/** + * @deprecated use core.summary + */ +var summary_2 = __nccwpck_require__(81327); +Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); +/** + * Path exports + */ +var path_utils_1 = __nccwpck_require__(2981); +Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } })); +Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } })); +Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } })); +//# sourceMappingURL=core.js.map /***/ }), -/***/ 80565: +/***/ 717: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +// For internal use, subject to change. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -5899,98 +3926,55 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getBackendIdsFromToken = void 0; -const core = __importStar(__nccwpck_require__(66526)); -const config_1 = __nccwpck_require__(95042); -const jwt_decode_1 = __importDefault(__nccwpck_require__(25582)); -const InvalidJwtError = new Error('Failed to get backend IDs: The provided JWT token is invalid and/or missing claims'); -// uses the JWT token claims to get the -// workflow run and workflow job run backend ids -function getBackendIdsFromToken() { - const token = (0, config_1.getRuntimeToken)(); - const decoded = (0, jwt_decode_1.default)(token); - if (!decoded.scp) { - throw InvalidJwtError; +exports.prepareKeyValueMessage = exports.issueFileCommand = void 0; +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ +const fs = __importStar(__nccwpck_require__(57147)); +const os = __importStar(__nccwpck_require__(22037)); +const uuid_1 = __nccwpck_require__(75840); +const utils_1 = __nccwpck_require__(5278); +function issueFileCommand(command, message) { + const filePath = process.env[`GITHUB_${command}`]; + if (!filePath) { + throw new Error(`Unable to find environment variable for file command ${command}`); } - /* - * example decoded: - * { - * scp: "Actions.ExampleScope Actions.Results:ce7f54c7-61c7-4aae-887f-30da475f5f1a:ca395085-040a-526b-2ce8-bdc85f692774" - * } - */ - const scpParts = decoded.scp.split(' '); - if (scpParts.length === 0) { - throw InvalidJwtError; + if (!fs.existsSync(filePath)) { + throw new Error(`Missing file at path: ${filePath}`); } - /* - * example scpParts: - * ["Actions.ExampleScope", "Actions.Results:ce7f54c7-61c7-4aae-887f-30da475f5f1a:ca395085-040a-526b-2ce8-bdc85f692774"] - */ - for (const scopes of scpParts) { - const scopeParts = scopes.split(':'); - if ((scopeParts === null || scopeParts === void 0 ? void 0 : scopeParts[0]) !== 'Actions.Results') { - // not the Actions.Results scope - continue; - } - /* - * example scopeParts: - * ["Actions.Results", "ce7f54c7-61c7-4aae-887f-30da475f5f1a", "ca395085-040a-526b-2ce8-bdc85f692774"] - */ - if (scopeParts.length !== 3) { - // missing expected number of claims - throw InvalidJwtError; - } - const ids = { - workflowRunBackendId: scopeParts[1], - workflowJobRunBackendId: scopeParts[2] - }; - core.debug(`Workflow Run Backend ID: ${ids.workflowRunBackendId}`); - core.debug(`Workflow Job Run Backend ID: ${ids.workflowJobRunBackendId}`); - return ids; + fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, { + encoding: 'utf8' + }); +} +exports.issueFileCommand = issueFileCommand; +function prepareKeyValueMessage(key, value) { + const delimiter = `ghadelimiter_${uuid_1.v4()}`; + const convertedValue = utils_1.toCommandValue(value); + // These should realistically never happen, but just in case someone finds a + // way to exploit uuid generation let's not allow keys or values that contain + // the delimiter. + if (key.includes(delimiter)) { + throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); } - throw InvalidJwtError; + if (convertedValue.includes(delimiter)) { + throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); + } + return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; } -exports.getBackendIdsFromToken = getBackendIdsFromToken; -//# sourceMappingURL=util.js.map +exports.prepareKeyValueMessage = prepareKeyValueMessage; +//# sourceMappingURL=file-command.js.map /***/ }), -/***/ 63311: +/***/ 98041: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { @@ -6001,200 +3985,83 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.uploadZipToBlobStorage = void 0; -const storage_blob_1 = __nccwpck_require__(18061); -const config_1 = __nccwpck_require__(95042); -const core = __importStar(__nccwpck_require__(66526)); -const crypto = __importStar(__nccwpck_require__(6113)); -const stream = __importStar(__nccwpck_require__(12781)); -function uploadZipToBlobStorage(authenticatedUploadURL, zipUploadStream) { - return __awaiter(this, void 0, void 0, function* () { - let uploadByteCount = 0; - const maxConcurrency = (0, config_1.getConcurrency)(); - const bufferSize = (0, config_1.getUploadChunkSize)(); - const blobClient = new storage_blob_1.BlobClient(authenticatedUploadURL); - const blockBlobClient = blobClient.getBlockBlobClient(); - core.debug(`Uploading artifact zip to blob storage with maxConcurrency: ${maxConcurrency}, bufferSize: ${bufferSize}`); - const uploadCallback = (progress) => { - core.info(`Uploaded bytes ${progress.loadedBytes}`); - uploadByteCount = progress.loadedBytes; - }; - const options = { - blobHTTPHeaders: { blobContentType: 'zip' }, - onProgress: uploadCallback +exports.OidcClient = void 0; +const http_client_1 = __nccwpck_require__(96255); +const auth_1 = __nccwpck_require__(35526); +const core_1 = __nccwpck_require__(42186); +class OidcClient { + static createHttpClient(allowRetry = true, maxRetry = 10) { + const requestOptions = { + allowRetries: allowRetry, + maxRetries: maxRetry }; - let sha256Hash = undefined; - const uploadStream = new stream.PassThrough(); - const hashStream = crypto.createHash('sha256'); - zipUploadStream.pipe(uploadStream); // This stream is used for the upload - zipUploadStream.pipe(hashStream).setEncoding('hex'); // This stream is used to compute a hash of the zip content that gets used. Integrity check - core.info('Beginning upload of artifact content to blob storage'); - yield blockBlobClient.uploadStream(uploadStream, bufferSize, maxConcurrency, options); - core.info('Finished uploading artifact content to blob storage!'); - hashStream.end(); - sha256Hash = hashStream.read(); - core.info(`SHA256 hash of uploaded artifact zip is ${sha256Hash}`); - if (uploadByteCount === 0) { - core.warning(`No data was uploaded to blob storage. Reported upload byte count is 0.`); - } - return { - uploadSize: uploadByteCount, - sha256Hash - }; - }); -} -exports.uploadZipToBlobStorage = uploadZipToBlobStorage; -//# sourceMappingURL=blob-upload.js.map - -/***/ }), - -/***/ 4913: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.validateFilePath = exports.validateArtifactName = void 0; -const core_1 = __nccwpck_require__(66526); -/** - * Invalid characters that cannot be in the artifact name or an uploaded file. Will be rejected - * from the server if attempted to be sent over. These characters are not allowed due to limitations with certain - * file systems such as NTFS. To maintain platform-agnostic behavior, all characters that are not supported by an - * individual filesystem/platform will not be supported on all fileSystems/platforms - * - * FilePaths can include characters such as \ and / which are not permitted in the artifact name alone - */ -const invalidArtifactFilePathCharacters = new Map([ - ['"', ' Double quote "'], - [':', ' Colon :'], - ['<', ' Less than <'], - ['>', ' Greater than >'], - ['|', ' Vertical bar |'], - ['*', ' Asterisk *'], - ['?', ' Question mark ?'], - ['\r', ' Carriage return \\r'], - ['\n', ' Line feed \\n'] -]); -const invalidArtifactNameCharacters = new Map([ - ...invalidArtifactFilePathCharacters, - ['\\', ' Backslash \\'], - ['/', ' Forward slash /'] -]); -/** - * Validates the name of the artifact to check to make sure there are no illegal characters - */ -function validateArtifactName(name) { - if (!name) { - throw new Error(`Provided artifact name input during validation is empty`); + return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions); } - for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactNameCharacters) { - if (name.includes(invalidCharacterKey)) { - throw new Error(`The artifact name is not valid: ${name}. Contains the following character: ${errorMessageForCharacter} - -Invalid characters include: ${Array.from(invalidArtifactNameCharacters.values()).toString()} - -These characters are not allowed in the artifact name due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems.`); + static getRequestToken() { + const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN']; + if (!token) { + throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable'); } + return token; } - (0, core_1.info)(`Artifact name is valid!`); -} -exports.validateArtifactName = validateArtifactName; -/** - * Validates file paths to check for any illegal characters that can cause problems on different file systems - */ -function validateFilePath(path) { - if (!path) { - throw new Error(`Provided file path input during validation is empty`); - } - for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactFilePathCharacters) { - if (path.includes(invalidCharacterKey)) { - throw new Error(`The path for one of the files in artifact is not valid: ${path}. Contains the following character: ${errorMessageForCharacter} - -Invalid characters include: ${Array.from(invalidArtifactFilePathCharacters.values()).toString()} - -The following characters are not allowed in files that are uploaded due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems. - `); + static getIDTokenUrl() { + const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL']; + if (!runtimeUrl) { + throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable'); } + return runtimeUrl; } -} -exports.validateFilePath = validateFilePath; -//# sourceMappingURL=path-and-artifact-name-validation.js.map - -/***/ }), - -/***/ 79245: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getExpiration = void 0; -const generated_1 = __nccwpck_require__(90265); -const core = __importStar(__nccwpck_require__(66526)); -function getExpiration(retentionDays) { - if (!retentionDays) { - return undefined; - } - const maxRetentionDays = getRetentionDays(); - if (maxRetentionDays && maxRetentionDays < retentionDays) { - core.warning(`Retention days cannot be greater than the maximum allowed retention set within the repository. Using ${maxRetentionDays} instead.`); - retentionDays = maxRetentionDays; - } - const expirationDate = new Date(); - expirationDate.setDate(expirationDate.getDate() + retentionDays); - return generated_1.Timestamp.fromDate(expirationDate); -} -exports.getExpiration = getExpiration; -function getRetentionDays() { - const retentionDays = process.env['GITHUB_RETENTION_DAYS']; - if (!retentionDays) { - return undefined; + static getCall(id_token_url) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const httpclient = OidcClient.createHttpClient(); + const res = yield httpclient + .getJson(id_token_url) + .catch(error => { + throw new Error(`Failed to get ID Token. \n + Error Code : ${error.statusCode}\n + Error Message: ${error.result.message}`); + }); + const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; + if (!id_token) { + throw new Error('Response json body do not have ID Token field'); + } + return id_token; + }); } - const days = parseInt(retentionDays); - if (isNaN(days)) { - return undefined; + static getIDToken(audience) { + return __awaiter(this, void 0, void 0, function* () { + try { + // New ID Token is requested from action service + let id_token_url = OidcClient.getIDTokenUrl(); + if (audience) { + const encodedAudience = encodeURIComponent(audience); + id_token_url = `${id_token_url}&audience=${encodedAudience}`; + } + core_1.debug(`ID token url is ${id_token_url}`); + const id_token = yield OidcClient.getCall(id_token_url); + core_1.setSecret(id_token); + return id_token; + } + catch (error) { + throw new Error(`Error message: ${error.message}`); + } + }); } - return days; } -//# sourceMappingURL=retention.js.map +exports.OidcClient = OidcClient; +//# sourceMappingURL=oidc-utils.js.map /***/ }), -/***/ 86278: +/***/ 2981: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -6207,240 +4074,56 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.uploadArtifact = void 0; -const core = __importStar(__nccwpck_require__(66526)); -const retention_1 = __nccwpck_require__(79245); -const path_and_artifact_name_validation_1 = __nccwpck_require__(4913); -const artifact_twirp_client_1 = __nccwpck_require__(63550); -const upload_zip_specification_1 = __nccwpck_require__(16206); -const util_1 = __nccwpck_require__(80565); -const blob_upload_1 = __nccwpck_require__(63311); -const zip_1 = __nccwpck_require__(6180); -const generated_1 = __nccwpck_require__(90265); -const errors_1 = __nccwpck_require__(69398); -function uploadArtifact(name, files, rootDirectory, options) { - return __awaiter(this, void 0, void 0, function* () { - (0, path_and_artifact_name_validation_1.validateArtifactName)(name); - (0, upload_zip_specification_1.validateRootDirectory)(rootDirectory); - const zipSpecification = (0, upload_zip_specification_1.getUploadZipSpecification)(files, rootDirectory); - if (zipSpecification.length === 0) { - throw new errors_1.FilesNotFoundError(zipSpecification.flatMap(s => (s.sourcePath ? [s.sourcePath] : []))); - } - // get the IDs needed for the artifact creation - const backendIds = (0, util_1.getBackendIdsFromToken)(); - // create the artifact client - const artifactClient = (0, artifact_twirp_client_1.internalArtifactTwirpClient)(); - // create the artifact - const createArtifactReq = { - workflowRunBackendId: backendIds.workflowRunBackendId, - workflowJobRunBackendId: backendIds.workflowJobRunBackendId, - name, - version: 4 - }; - // if there is a retention period, add it to the request - const expiresAt = (0, retention_1.getExpiration)(options === null || options === void 0 ? void 0 : options.retentionDays); - if (expiresAt) { - createArtifactReq.expiresAt = expiresAt; - } - const createArtifactResp = yield artifactClient.CreateArtifact(createArtifactReq); - if (!createArtifactResp.ok) { - throw new errors_1.InvalidResponseError('CreateArtifact: response from backend was not ok'); - } - const zipUploadStream = yield (0, zip_1.createZipUploadStream)(zipSpecification, options === null || options === void 0 ? void 0 : options.compressionLevel); - // Upload zip to blob storage - const uploadResult = yield (0, blob_upload_1.uploadZipToBlobStorage)(createArtifactResp.signedUploadUrl, zipUploadStream); - // finalize the artifact - const finalizeArtifactReq = { - workflowRunBackendId: backendIds.workflowRunBackendId, - workflowJobRunBackendId: backendIds.workflowJobRunBackendId, - name, - size: uploadResult.uploadSize ? uploadResult.uploadSize.toString() : '0' - }; - if (uploadResult.sha256Hash) { - finalizeArtifactReq.hash = generated_1.StringValue.create({ - value: `sha256:${uploadResult.sha256Hash}` - }); - } - core.info(`Finalizing artifact upload`); - const finalizeArtifactResp = yield artifactClient.FinalizeArtifact(finalizeArtifactReq); - if (!finalizeArtifactResp.ok) { - throw new errors_1.InvalidResponseError('FinalizeArtifact: response from backend was not ok'); - } - const artifactId = BigInt(finalizeArtifactResp.artifactId); - core.info(`Artifact ${name}.zip successfully finalized. Artifact ID ${artifactId}`); - return { - size: uploadResult.uploadSize, - id: Number(artifactId) - }; - }); +exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; +const path = __importStar(__nccwpck_require__(71017)); +/** + * toPosixPath converts the given path to the posix form. On Windows, \\ will be + * replaced with /. + * + * @param pth. Path to transform. + * @return string Posix path. + */ +function toPosixPath(pth) { + return pth.replace(/[\\]/g, '/'); } -exports.uploadArtifact = uploadArtifact; -//# sourceMappingURL=upload-artifact.js.map - -/***/ }), - -/***/ 16206: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getUploadZipSpecification = exports.validateRootDirectory = void 0; -const fs = __importStar(__nccwpck_require__(57147)); -const core_1 = __nccwpck_require__(66526); -const path_1 = __nccwpck_require__(71017); -const path_and_artifact_name_validation_1 = __nccwpck_require__(4913); +exports.toPosixPath = toPosixPath; /** - * Checks if a root directory exists and is valid - * @param rootDirectory an absolute root directory path common to all input files that that will be trimmed from the final zip structure + * toWin32Path converts the given path to the win32 form. On Linux, / will be + * replaced with \\. + * + * @param pth. Path to transform. + * @return string Win32 path. */ -function validateRootDirectory(rootDirectory) { - if (!fs.existsSync(rootDirectory)) { - throw new Error(`The provided rootDirectory ${rootDirectory} does not exist`); - } - if (!fs.statSync(rootDirectory).isDirectory()) { - throw new Error(`The provided rootDirectory ${rootDirectory} is not a valid directory`); - } - (0, core_1.info)(`Root directory input is valid!`); +function toWin32Path(pth) { + return pth.replace(/[/]/g, '\\'); } -exports.validateRootDirectory = validateRootDirectory; +exports.toWin32Path = toWin32Path; /** - * Creates a specification that describes how a zip file will be created for a set of input files - * @param filesToZip a list of file that should be included in the zip - * @param rootDirectory an absolute root directory path common to all input files that that will be trimmed from the final zip structure + * toPlatformPath converts the given path to a platform-specific path. It does + * this by replacing instances of / and \ with the platform-specific path + * separator. + * + * @param pth The path to platformize. + * @return string The platform-specific path. */ -function getUploadZipSpecification(filesToZip, rootDirectory) { - const specification = []; - // Normalize and resolve, this allows for either absolute or relative paths to be used - rootDirectory = (0, path_1.normalize)(rootDirectory); - rootDirectory = (0, path_1.resolve)(rootDirectory); - /* - Example - - Input: - rootDirectory: '/home/user/files/plz-upload' - artifactFiles: [ - '/home/user/files/plz-upload/file1.txt', - '/home/user/files/plz-upload/file2.txt', - '/home/user/files/plz-upload/dir/file3.txt' - ] - - Output: - specifications: [ - ['/home/user/files/plz-upload/file1.txt', '/file1.txt'], - ['/home/user/files/plz-upload/file1.txt', '/file2.txt'], - ['/home/user/files/plz-upload/file1.txt', '/dir/file3.txt'] - ] - - The final zip that is later uploaded will look like this: - - my-artifact.zip - - file.txt - - file2.txt - - dir/ - - file3.txt - */ - for (let file of filesToZip) { - if (!fs.existsSync(file)) { - throw new Error(`File ${file} does not exist`); - } - if (!fs.statSync(file).isDirectory()) { - // Normalize and resolve, this allows for either absolute or relative paths to be used - file = (0, path_1.normalize)(file); - file = (0, path_1.resolve)(file); - if (!file.startsWith(rootDirectory)) { - throw new Error(`The rootDirectory: ${rootDirectory} is not a parent directory of the file: ${file}`); - } - // Check for forbidden characters in file paths that may cause ambiguous behavior if downloaded on different file systems - const uploadPath = file.replace(rootDirectory, ''); - (0, path_and_artifact_name_validation_1.validateFilePath)(uploadPath); - specification.push({ - sourcePath: file, - destinationPath: uploadPath - }); - } - else { - // Empty directory - const directoryPath = file.replace(rootDirectory, ''); - (0, path_and_artifact_name_validation_1.validateFilePath)(directoryPath); - specification.push({ - sourcePath: null, - destinationPath: directoryPath - }); - } - } - return specification; +function toPlatformPath(pth) { + return pth.replace(/[/\\]/g, path.sep); } -exports.getUploadZipSpecification = getUploadZipSpecification; -//# sourceMappingURL=upload-zip-specification.js.map +exports.toPlatformPath = toPlatformPath; +//# sourceMappingURL=path-utils.js.map /***/ }), -/***/ 6180: +/***/ 81327: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { @@ -6451,89 +4134,390 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createZipUploadStream = exports.ZipUploadStream = exports.DEFAULT_COMPRESSION_LEVEL = void 0; -const stream = __importStar(__nccwpck_require__(12781)); -const archiver = __importStar(__nccwpck_require__(71160)); -const core = __importStar(__nccwpck_require__(66526)); +exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; +const os_1 = __nccwpck_require__(22037); const fs_1 = __nccwpck_require__(57147); -const config_1 = __nccwpck_require__(95042); -exports.DEFAULT_COMPRESSION_LEVEL = 6; -// Custom stream transformer so we can set the highWaterMark property -// See https://github.com/nodejs/node/issues/8855 -class ZipUploadStream extends stream.Transform { - constructor(bufferSize) { - super({ - highWaterMark: bufferSize - }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - _transform(chunk, enc, cb) { - cb(null, chunk); +const { access, appendFile, writeFile } = fs_1.promises; +exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; +exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; +class Summary { + constructor() { + this._buffer = ''; } -} -exports.ZipUploadStream = ZipUploadStream; -function createZipUploadStream(uploadSpecification, compressionLevel = exports.DEFAULT_COMPRESSION_LEVEL) { - return __awaiter(this, void 0, void 0, function* () { - core.debug(`Creating Artifact archive with compressionLevel: ${compressionLevel}`); - const zip = archiver.create('zip', { - highWaterMark: (0, config_1.getUploadChunkSize)(), - zlib: { level: compressionLevel } - }); - // register callbacks for various events during the zip lifecycle - zip.on('error', zipErrorCallback); - zip.on('warning', zipWarningCallback); - zip.on('finish', zipFinishCallback); - zip.on('end', zipEndCallback); - for (const file of uploadSpecification) { - if (file.sourcePath !== null) { - // Add a normal file to the zip - zip.append((0, fs_1.createReadStream)(file.sourcePath), { - name: file.destinationPath - }); + /** + * Finds the summary file path from the environment, rejects if env var is not found or file does not exist + * Also checks r/w permissions. + * + * @returns step summary file path + */ + filePath() { + return __awaiter(this, void 0, void 0, function* () { + if (this._filePath) { + return this._filePath; } - else { - // Add a directory to the zip - zip.append('', { name: file.destinationPath }); + const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR]; + if (!pathFromEnv) { + throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); + } + try { + yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); } + catch (_a) { + throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); + } + this._filePath = pathFromEnv; + return this._filePath; + }); + } + /** + * Wraps content in an HTML tag, adding any HTML attributes + * + * @param {string} tag HTML tag to wrap + * @param {string | null} content content within the tag + * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add + * + * @returns {string} content wrapped in HTML element + */ + wrap(tag, content, attrs = {}) { + const htmlAttrs = Object.entries(attrs) + .map(([key, value]) => ` ${key}="${value}"`) + .join(''); + if (!content) { + return `<${tag}${htmlAttrs}>`; } - const bufferSize = (0, config_1.getUploadChunkSize)(); - const zipUploadStream = new ZipUploadStream(bufferSize); - core.debug(`Zip write high watermark value ${zipUploadStream.writableHighWaterMark}`); - core.debug(`Zip read high watermark value ${zipUploadStream.readableHighWaterMark}`); - zip.pipe(zipUploadStream); - zip.finalize(); - return zipUploadStream; - }); + return `<${tag}${htmlAttrs}>${content}`; + } + /** + * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. + * + * @param {SummaryWriteOptions} [options] (optional) options for write operation + * + * @returns {Promise} summary instance + */ + write(options) { + return __awaiter(this, void 0, void 0, function* () { + const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); + const filePath = yield this.filePath(); + const writeFunc = overwrite ? writeFile : appendFile; + yield writeFunc(filePath, this._buffer, { encoding: 'utf8' }); + return this.emptyBuffer(); + }); + } + /** + * Clears the summary buffer and wipes the summary file + * + * @returns {Summary} summary instance + */ + clear() { + return __awaiter(this, void 0, void 0, function* () { + return this.emptyBuffer().write({ overwrite: true }); + }); + } + /** + * Returns the current summary buffer as a string + * + * @returns {string} string of summary buffer + */ + stringify() { + return this._buffer; + } + /** + * If the summary buffer is empty + * + * @returns {boolen} true if the buffer is empty + */ + isEmptyBuffer() { + return this._buffer.length === 0; + } + /** + * Resets the summary buffer without writing to summary file + * + * @returns {Summary} summary instance + */ + emptyBuffer() { + this._buffer = ''; + return this; + } + /** + * Adds raw text to the summary buffer + * + * @param {string} text content to add + * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) + * + * @returns {Summary} summary instance + */ + addRaw(text, addEOL = false) { + this._buffer += text; + return addEOL ? this.addEOL() : this; + } + /** + * Adds the operating system-specific end-of-line marker to the buffer + * + * @returns {Summary} summary instance + */ + addEOL() { + return this.addRaw(os_1.EOL); + } + /** + * Adds an HTML codeblock to the summary buffer + * + * @param {string} code content to render within fenced code block + * @param {string} lang (optional) language to syntax highlight code + * + * @returns {Summary} summary instance + */ + addCodeBlock(code, lang) { + const attrs = Object.assign({}, (lang && { lang })); + const element = this.wrap('pre', this.wrap('code', code), attrs); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML list to the summary buffer + * + * @param {string[]} items list of items to render + * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) + * + * @returns {Summary} summary instance + */ + addList(items, ordered = false) { + const tag = ordered ? 'ol' : 'ul'; + const listItems = items.map(item => this.wrap('li', item)).join(''); + const element = this.wrap(tag, listItems); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML table to the summary buffer + * + * @param {SummaryTableCell[]} rows table rows + * + * @returns {Summary} summary instance + */ + addTable(rows) { + const tableBody = rows + .map(row => { + const cells = row + .map(cell => { + if (typeof cell === 'string') { + return this.wrap('td', cell); + } + const { header, data, colspan, rowspan } = cell; + const tag = header ? 'th' : 'td'; + const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan })); + return this.wrap(tag, data, attrs); + }) + .join(''); + return this.wrap('tr', cells); + }) + .join(''); + const element = this.wrap('table', tableBody); + return this.addRaw(element).addEOL(); + } + /** + * Adds a collapsable HTML details element to the summary buffer + * + * @param {string} label text for the closed state + * @param {string} content collapsable content + * + * @returns {Summary} summary instance + */ + addDetails(label, content) { + const element = this.wrap('details', this.wrap('summary', label) + content); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML image tag to the summary buffer + * + * @param {string} src path to the image you to embed + * @param {string} alt text description of the image + * @param {SummaryImageOptions} options (optional) addition image attributes + * + * @returns {Summary} summary instance + */ + addImage(src, alt, options) { + const { width, height } = options || {}; + const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height })); + const element = this.wrap('img', null, Object.assign({ src, alt }, attrs)); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML section heading element + * + * @param {string} text heading text + * @param {number | string} [level=1] (optional) the heading level, default: 1 + * + * @returns {Summary} summary instance + */ + addHeading(text, level) { + const tag = `h${level}`; + const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag) + ? tag + : 'h1'; + const element = this.wrap(allowedTag, text); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML thematic break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addSeparator() { + const element = this.wrap('hr', null); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML line break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addBreak() { + const element = this.wrap('br', null); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML blockquote to the summary buffer + * + * @param {string} text quote text + * @param {string} cite (optional) citation url + * + * @returns {Summary} summary instance + */ + addQuote(text, cite) { + const attrs = Object.assign({}, (cite && { cite })); + const element = this.wrap('blockquote', text, attrs); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML anchor tag to the summary buffer + * + * @param {string} text link text/content + * @param {string} href hyperlink + * + * @returns {Summary} summary instance + */ + addLink(text, href) { + const element = this.wrap('a', text, { href }); + return this.addRaw(element).addEOL(); + } } -exports.createZipUploadStream = createZipUploadStream; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -const zipErrorCallback = (error) => { - core.error('An error has occurred while creating the zip file for upload'); - core.info(error); - throw new Error('An error has occurred during zip creation for the artifact'); -}; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -const zipWarningCallback = (error) => { - if (error.code === 'ENOENT') { - core.warning('ENOENT warning during artifact zip creation. No such file or directory'); - core.info(error); +const _summary = new Summary(); +/** + * @deprecated use `core.summary` + */ +exports.markdownSummary = _summary; +exports.summary = _summary; +//# sourceMappingURL=summary.js.map + +/***/ }), + +/***/ 5278: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.toCommandProperties = exports.toCommandValue = void 0; +/** + * Sanitizes an input into a string so it can be passed into issueCommand safely + * @param input input to sanitize into a string + */ +function toCommandValue(input) { + if (input === null || input === undefined) { + return ''; } - else { - core.warning(`A non-blocking warning has occurred during artifact zip creation: ${error.code}`); - core.info(error); + else if (typeof input === 'string' || input instanceof String) { + return input; } -}; -const zipFinishCallback = () => { - core.debug('Zip stream for upload has finished.'); -}; -const zipEndCallback = () => { - core.debug('Zip stream for upload has ended.'); -}; -//# sourceMappingURL=zip.js.map + return JSON.stringify(input); +} +exports.toCommandValue = toCommandValue; +/** + * + * @param annotationProperties + * @returns The command properties to send with the actual annotation command + * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646 + */ +function toCommandProperties(annotationProperties) { + if (!Object.keys(annotationProperties).length) { + return {}; + } + return { + title: annotationProperties.title, + file: annotationProperties.file, + line: annotationProperties.startLine, + endLine: annotationProperties.endLine, + col: annotationProperties.startColumn, + endColumn: annotationProperties.endColumn + }; +} +exports.toCommandProperties = toCommandProperties; +//# sourceMappingURL=utils.js.map + +/***/ }), + +/***/ 74087: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Context = void 0; +const fs_1 = __nccwpck_require__(57147); +const os_1 = __nccwpck_require__(22037); +class Context { + /** + * Hydrate the context from the environment + */ + constructor() { + var _a, _b, _c; + this.payload = {}; + if (process.env.GITHUB_EVENT_PATH) { + if (fs_1.existsSync(process.env.GITHUB_EVENT_PATH)) { + this.payload = JSON.parse(fs_1.readFileSync(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' })); + } + else { + const path = process.env.GITHUB_EVENT_PATH; + process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${os_1.EOL}`); + } + } + this.eventName = process.env.GITHUB_EVENT_NAME; + this.sha = process.env.GITHUB_SHA; + this.ref = process.env.GITHUB_REF; + this.workflow = process.env.GITHUB_WORKFLOW; + this.action = process.env.GITHUB_ACTION; + this.actor = process.env.GITHUB_ACTOR; + this.job = process.env.GITHUB_JOB; + this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10); + this.runId = parseInt(process.env.GITHUB_RUN_ID, 10); + this.apiUrl = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `https://api.github.com`; + this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`; + this.graphqlUrl = (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://github.com/gitapi/graphql`; + } + get issue() { + const payload = this.payload; + return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number }); + } + get repo() { + if (process.env.GITHUB_REPOSITORY) { + const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/'); + return { owner, repo }; + } + if (this.payload.repository) { + return { + owner: this.payload.repository.owner.login, + repo: this.payload.repository.name + }; + } + throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'"); + } +} +exports.Context = Context; +//# sourceMappingURL=context.js.map /***/ }), -/***/ 29835: +/***/ 95438: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -6558,81 +4542,76 @@ var __importStar = (this && this.__importStar) || function (mod) { return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.issue = exports.issueCommand = void 0; -const os = __importStar(__nccwpck_require__(22037)); -const utils_1 = __nccwpck_require__(85932); +exports.getOctokit = exports.context = void 0; +const Context = __importStar(__nccwpck_require__(74087)); +const utils_1 = __nccwpck_require__(73030); +exports.context = new Context.Context(); /** - * Commands - * - * Command Format: - * ::name key=value,key=value::message + * Returns a hydrated octokit ready to use for GitHub Actions * - * Examples: - * ::warning::This is the message - * ::set-env name=MY_VAR::some value + * @param token the repo PAT or GITHUB_TOKEN + * @param options other options to set */ -function issueCommand(command, properties, message) { - const cmd = new Command(command, properties, message); - process.stdout.write(cmd.toString() + os.EOL); -} -exports.issueCommand = issueCommand; -function issue(name, message = '') { - issueCommand(name, {}, message); +function getOctokit(token, options, ...additionalPlugins) { + const GitHubWithPlugins = utils_1.GitHub.plugin(...additionalPlugins); + return new GitHubWithPlugins(utils_1.getOctokitOptions(token, options)); } -exports.issue = issue; -const CMD_STRING = '::'; -class Command { - constructor(command, properties, message) { - if (!command) { - command = 'missing.command'; - } - this.command = command; - this.properties = properties; - this.message = message; +exports.getOctokit = getOctokit; +//# sourceMappingURL=github.js.map + +/***/ }), + +/***/ 47914: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getApiBaseUrl = exports.getProxyAgent = exports.getAuthString = void 0; +const httpClient = __importStar(__nccwpck_require__(96255)); +function getAuthString(token, options) { + if (!token && !options.auth) { + throw new Error('Parameter token or opts.auth is required'); } - toString() { - let cmdStr = CMD_STRING + this.command; - if (this.properties && Object.keys(this.properties).length > 0) { - cmdStr += ' '; - let first = true; - for (const key in this.properties) { - if (this.properties.hasOwnProperty(key)) { - const val = this.properties[key]; - if (val) { - if (first) { - first = false; - } - else { - cmdStr += ','; - } - cmdStr += `${key}=${escapeProperty(val)}`; - } - } - } - } - cmdStr += `${CMD_STRING}${escapeData(this.message)}`; - return cmdStr; + else if (token && options.auth) { + throw new Error('Parameters token and opts.auth may not both be specified'); } + return typeof options.auth === 'string' ? options.auth : `token ${token}`; } -function escapeData(s) { - return utils_1.toCommandValue(s) - .replace(/%/g, '%25') - .replace(/\r/g, '%0D') - .replace(/\n/g, '%0A'); +exports.getAuthString = getAuthString; +function getProxyAgent(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgent(destinationUrl); } -function escapeProperty(s) { - return utils_1.toCommandValue(s) - .replace(/%/g, '%25') - .replace(/\r/g, '%0D') - .replace(/\n/g, '%0A') - .replace(/:/g, '%3A') - .replace(/,/g, '%2C'); +exports.getProxyAgent = getProxyAgent; +function getApiBaseUrl() { + return process.env['GITHUB_API_URL'] || 'https://api.github.com'; } -//# sourceMappingURL=command.js.map +exports.getApiBaseUrl = getApiBaseUrl; +//# sourceMappingURL=utils.js.map /***/ }), -/***/ 66526: +/***/ 73030: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -6656,6 +4635,48 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getOctokitOptions = exports.GitHub = exports.defaults = exports.context = void 0; +const Context = __importStar(__nccwpck_require__(74087)); +const Utils = __importStar(__nccwpck_require__(47914)); +// octokit + plugins +const core_1 = __nccwpck_require__(76762); +const plugin_rest_endpoint_methods_1 = __nccwpck_require__(83044); +const plugin_paginate_rest_1 = __nccwpck_require__(64193); +exports.context = new Context.Context(); +const baseUrl = Utils.getApiBaseUrl(); +exports.defaults = { + baseUrl, + request: { + agent: Utils.getProxyAgent(baseUrl) + } +}; +exports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(exports.defaults); +/** + * Convience function to correctly format Octokit Options to pass into the constructor. + * + * @param token the repo PAT or GITHUB_TOKEN + * @param options other options to set + */ +function getOctokitOptions(token, options) { + const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller + // Auth + const auth = Utils.getAuthString(token, opts); + if (auth) { + opts.auth = auth; + } + return opts; +} +exports.getOctokitOptions = getOctokitOptions; +//# sourceMappingURL=utils.js.map + +/***/ }), + +/***/ 28090: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { @@ -6666,321 +4687,47 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; -const command_1 = __nccwpck_require__(29835); -const file_command_1 = __nccwpck_require__(71117); -const utils_1 = __nccwpck_require__(85932); -const os = __importStar(__nccwpck_require__(22037)); -const path = __importStar(__nccwpck_require__(71017)); -const oidc_utils_1 = __nccwpck_require__(64663); +exports.hashFiles = exports.create = void 0; +const internal_globber_1 = __nccwpck_require__(28298); +const internal_hash_files_1 = __nccwpck_require__(2448); /** - * The code to exit an action - */ -var ExitCode; -(function (ExitCode) { - /** - * A code indicating that the action was successful - */ - ExitCode[ExitCode["Success"] = 0] = "Success"; - /** - * A code indicating that the action was a failure - */ - ExitCode[ExitCode["Failure"] = 1] = "Failure"; -})(ExitCode = exports.ExitCode || (exports.ExitCode = {})); -//----------------------------------------------------------------------- -// Variables -//----------------------------------------------------------------------- -/** - * Sets env variable for this action and future actions in the job - * @param name the name of the variable to set - * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function exportVariable(name, val) { - const convertedVal = utils_1.toCommandValue(val); - process.env[name] = convertedVal; - const filePath = process.env['GITHUB_ENV'] || ''; - if (filePath) { - return file_command_1.issueFileCommand('ENV', file_command_1.prepareKeyValueMessage(name, val)); - } - command_1.issueCommand('set-env', { name }, convertedVal); -} -exports.exportVariable = exportVariable; -/** - * Registers a secret which will get masked from logs - * @param secret value of the secret - */ -function setSecret(secret) { - command_1.issueCommand('add-mask', {}, secret); -} -exports.setSecret = setSecret; -/** - * Prepends inputPath to the PATH (for this action and future actions) - * @param inputPath - */ -function addPath(inputPath) { - const filePath = process.env['GITHUB_PATH'] || ''; - if (filePath) { - file_command_1.issueFileCommand('PATH', inputPath); - } - else { - command_1.issueCommand('add-path', {}, inputPath); - } - process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; -} -exports.addPath = addPath; -/** - * Gets the value of an input. - * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. - * Returns an empty string if the value is not defined. - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns string - */ -function getInput(name, options) { - const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; - if (options && options.required && !val) { - throw new Error(`Input required and not supplied: ${name}`); - } - if (options && options.trimWhitespace === false) { - return val; - } - return val.trim(); -} -exports.getInput = getInput; -/** - * Gets the values of an multiline input. Each value is also trimmed. - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns string[] - * - */ -function getMultilineInput(name, options) { - const inputs = getInput(name, options) - .split('\n') - .filter(x => x !== ''); - if (options && options.trimWhitespace === false) { - return inputs; - } - return inputs.map(input => input.trim()); -} -exports.getMultilineInput = getMultilineInput; -/** - * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. - * Support boolean input list: `true | True | TRUE | false | False | FALSE` . - * The return value is also in boolean type. - * ref: https://yaml.org/spec/1.2/spec.html#id2804923 - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns boolean - */ -function getBooleanInput(name, options) { - const trueValue = ['true', 'True', 'TRUE']; - const falseValue = ['false', 'False', 'FALSE']; - const val = getInput(name, options); - if (trueValue.includes(val)) - return true; - if (falseValue.includes(val)) - return false; - throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + - `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); -} -exports.getBooleanInput = getBooleanInput; -/** - * Sets the value of an output. - * - * @param name name of the output to set - * @param value value to store. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function setOutput(name, value) { - const filePath = process.env['GITHUB_OUTPUT'] || ''; - if (filePath) { - return file_command_1.issueFileCommand('OUTPUT', file_command_1.prepareKeyValueMessage(name, value)); - } - process.stdout.write(os.EOL); - command_1.issueCommand('set-output', { name }, utils_1.toCommandValue(value)); -} -exports.setOutput = setOutput; -/** - * Enables or disables the echoing of commands into stdout for the rest of the step. - * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. - * - */ -function setCommandEcho(enabled) { - command_1.issue('echo', enabled ? 'on' : 'off'); -} -exports.setCommandEcho = setCommandEcho; -//----------------------------------------------------------------------- -// Results -//----------------------------------------------------------------------- -/** - * Sets the action status to failed. - * When the action exits it will be with an exit code of 1 - * @param message add error issue message - */ -function setFailed(message) { - process.exitCode = ExitCode.Failure; - error(message); -} -exports.setFailed = setFailed; -//----------------------------------------------------------------------- -// Logging Commands -//----------------------------------------------------------------------- -/** - * Gets whether Actions Step Debug is on or not - */ -function isDebug() { - return process.env['RUNNER_DEBUG'] === '1'; -} -exports.isDebug = isDebug; -/** - * Writes debug message to user log - * @param message debug message - */ -function debug(message) { - command_1.issueCommand('debug', {}, message); -} -exports.debug = debug; -/** - * Adds an error issue - * @param message error issue message. Errors will be converted to string via toString() - * @param properties optional properties to add to the annotation. - */ -function error(message, properties = {}) { - command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); -} -exports.error = error; -/** - * Adds a warning issue - * @param message warning issue message. Errors will be converted to string via toString() - * @param properties optional properties to add to the annotation. - */ -function warning(message, properties = {}) { - command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); -} -exports.warning = warning; -/** - * Adds a notice issue - * @param message notice issue message. Errors will be converted to string via toString() - * @param properties optional properties to add to the annotation. - */ -function notice(message, properties = {}) { - command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); -} -exports.notice = notice; -/** - * Writes info to log with console.log. - * @param message info message - */ -function info(message) { - process.stdout.write(message + os.EOL); -} -exports.info = info; -/** - * Begin an output group. - * - * Output until the next `groupEnd` will be foldable in this group - * - * @param name The name of the output group - */ -function startGroup(name) { - command_1.issue('group', name); -} -exports.startGroup = startGroup; -/** - * End an output group. - */ -function endGroup() { - command_1.issue('endgroup'); -} -exports.endGroup = endGroup; -/** - * Wrap an asynchronous function call in a group. - * - * Returns the same type as the function itself. + * Constructs a globber * - * @param name The name of the group - * @param fn The function to wrap in the group + * @param patterns Patterns separated by newlines + * @param options Glob options */ -function group(name, fn) { +function create(patterns, options) { return __awaiter(this, void 0, void 0, function* () { - startGroup(name); - let result; - try { - result = yield fn(); - } - finally { - endGroup(); - } - return result; + return yield internal_globber_1.DefaultGlobber.create(patterns, options); }); } -exports.group = group; -//----------------------------------------------------------------------- -// Wrapper action state -//----------------------------------------------------------------------- -/** - * Saves state for current action, the state can only be retrieved by this action's post job execution. - * - * @param name name of the state to store - * @param value value to store. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function saveState(name, value) { - const filePath = process.env['GITHUB_STATE'] || ''; - if (filePath) { - return file_command_1.issueFileCommand('STATE', file_command_1.prepareKeyValueMessage(name, value)); - } - command_1.issueCommand('save-state', { name }, utils_1.toCommandValue(value)); -} -exports.saveState = saveState; +exports.create = create; /** - * Gets the value of an state set by this action's main execution. + * Computes the sha256 hash of a glob * - * @param name name of the state to get - * @returns string + * @param patterns Patterns separated by newlines + * @param options Glob options */ -function getState(name) { - return process.env[`STATE_${name}`] || ''; -} -exports.getState = getState; -function getIDToken(aud) { +function hashFiles(patterns, options, verbose = false) { return __awaiter(this, void 0, void 0, function* () { - return yield oidc_utils_1.OidcClient.getIDToken(aud); + let followSymbolicLinks = true; + if (options && typeof options.followSymbolicLinks === 'boolean') { + followSymbolicLinks = options.followSymbolicLinks; + } + const globber = yield create(patterns, { followSymbolicLinks }); + return internal_hash_files_1.hashFiles(globber, verbose); }); } -exports.getIDToken = getIDToken; -/** - * Summary exports - */ -var summary_1 = __nccwpck_require__(71861); -Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); -/** - * @deprecated use core.summary - */ -var summary_2 = __nccwpck_require__(71861); -Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); -/** - * Path exports - */ -var path_utils_1 = __nccwpck_require__(48077); -Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } })); -Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } })); -Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } })); -//# sourceMappingURL=core.js.map +exports.hashFiles = hashFiles; +//# sourceMappingURL=glob.js.map /***/ }), -/***/ 71117: +/***/ 51026: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -// For internal use, subject to change. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); @@ -7001,130 +4748,44 @@ var __importStar = (this && this.__importStar) || function (mod) { return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.prepareKeyValueMessage = exports.issueFileCommand = void 0; -// We use any as a valid input type -/* eslint-disable @typescript-eslint/no-explicit-any */ -const fs = __importStar(__nccwpck_require__(57147)); -const os = __importStar(__nccwpck_require__(22037)); -const uuid_1 = __nccwpck_require__(4413); -const utils_1 = __nccwpck_require__(85932); -function issueFileCommand(command, message) { - const filePath = process.env[`GITHUB_${command}`]; - if (!filePath) { - throw new Error(`Unable to find environment variable for file command ${command}`); - } - if (!fs.existsSync(filePath)) { - throw new Error(`Missing file at path: ${filePath}`); - } - fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, { - encoding: 'utf8' - }); -} -exports.issueFileCommand = issueFileCommand; -function prepareKeyValueMessage(key, value) { - const delimiter = `ghadelimiter_${uuid_1.v4()}`; - const convertedValue = utils_1.toCommandValue(value); - // These should realistically never happen, but just in case someone finds a - // way to exploit uuid generation let's not allow keys or values that contain - // the delimiter. - if (key.includes(delimiter)) { - throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); - } - if (convertedValue.includes(delimiter)) { - throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); - } - return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; -} -exports.prepareKeyValueMessage = prepareKeyValueMessage; -//# sourceMappingURL=file-command.js.map - -/***/ }), - -/***/ 64663: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.OidcClient = void 0; -const http_client_1 = __nccwpck_require__(52932); -const auth_1 = __nccwpck_require__(40903); -const core_1 = __nccwpck_require__(66526); -class OidcClient { - static createHttpClient(allowRetry = true, maxRetry = 10) { - const requestOptions = { - allowRetries: allowRetry, - maxRetries: maxRetry - }; - return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions); - } - static getRequestToken() { - const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN']; - if (!token) { - throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable'); +exports.getOptions = void 0; +const core = __importStar(__nccwpck_require__(42186)); +/** + * Returns a copy with defaults filled in. + */ +function getOptions(copy) { + const result = { + followSymbolicLinks: true, + implicitDescendants: true, + matchDirectories: true, + omitBrokenSymbolicLinks: true + }; + if (copy) { + if (typeof copy.followSymbolicLinks === 'boolean') { + result.followSymbolicLinks = copy.followSymbolicLinks; + core.debug(`followSymbolicLinks '${result.followSymbolicLinks}'`); } - return token; - } - static getIDTokenUrl() { - const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL']; - if (!runtimeUrl) { - throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable'); + if (typeof copy.implicitDescendants === 'boolean') { + result.implicitDescendants = copy.implicitDescendants; + core.debug(`implicitDescendants '${result.implicitDescendants}'`); + } + if (typeof copy.matchDirectories === 'boolean') { + result.matchDirectories = copy.matchDirectories; + core.debug(`matchDirectories '${result.matchDirectories}'`); + } + if (typeof copy.omitBrokenSymbolicLinks === 'boolean') { + result.omitBrokenSymbolicLinks = copy.omitBrokenSymbolicLinks; + core.debug(`omitBrokenSymbolicLinks '${result.omitBrokenSymbolicLinks}'`); } - return runtimeUrl; - } - static getCall(id_token_url) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const httpclient = OidcClient.createHttpClient(); - const res = yield httpclient - .getJson(id_token_url) - .catch(error => { - throw new Error(`Failed to get ID Token. \n - Error Code : ${error.statusCode}\n - Error Message: ${error.result.message}`); - }); - const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; - if (!id_token) { - throw new Error('Response json body do not have ID Token field'); - } - return id_token; - }); - } - static getIDToken(audience) { - return __awaiter(this, void 0, void 0, function* () { - try { - // New ID Token is requested from action service - let id_token_url = OidcClient.getIDTokenUrl(); - if (audience) { - const encodedAudience = encodeURIComponent(audience); - id_token_url = `${id_token_url}&audience=${encodedAudience}`; - } - core_1.debug(`ID token url is ${id_token_url}`); - const id_token = yield OidcClient.getCall(id_token_url); - core_1.setSecret(id_token); - return id_token; - } - catch (error) { - throw new Error(`Error message: ${error.message}`); - } - }); } + return result; } -exports.OidcClient = OidcClient; -//# sourceMappingURL=oidc-utils.js.map +exports.getOptions = getOptions; +//# sourceMappingURL=internal-glob-options-helper.js.map /***/ }), -/***/ 48077: +/***/ 28298: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -7148,52 +4809,6 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; -const path = __importStar(__nccwpck_require__(71017)); -/** - * toPosixPath converts the given path to the posix form. On Windows, \\ will be - * replaced with /. - * - * @param pth. Path to transform. - * @return string Posix path. - */ -function toPosixPath(pth) { - return pth.replace(/[\\]/g, '/'); -} -exports.toPosixPath = toPosixPath; -/** - * toWin32Path converts the given path to the win32 form. On Linux, / will be - * replaced with \\. - * - * @param pth. Path to transform. - * @return string Win32 path. - */ -function toWin32Path(pth) { - return pth.replace(/[/]/g, '\\'); -} -exports.toWin32Path = toWin32Path; -/** - * toPlatformPath converts the given path to a platform-specific path. It does - * this by replacing instances of / and \ with the platform-specific path - * separator. - * - * @param pth The path to platformize. - * @return string The platform-specific path. - */ -function toPlatformPath(pth) { - return pth.replace(/[/\\]/g, path.sep); -} -exports.toPlatformPath = toPlatformPath; -//# sourceMappingURL=path-utils.js.map - -/***/ }), - -/***/ 71861: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { @@ -7203,391 +4818,343 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; +var __asyncValues = (this && this.__asyncValues) || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +}; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } +var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; -const os_1 = __nccwpck_require__(22037); -const fs_1 = __nccwpck_require__(57147); -const { access, appendFile, writeFile } = fs_1.promises; -exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; -exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; -class Summary { - constructor() { - this._buffer = ''; +exports.DefaultGlobber = void 0; +const core = __importStar(__nccwpck_require__(42186)); +const fs = __importStar(__nccwpck_require__(57147)); +const globOptionsHelper = __importStar(__nccwpck_require__(51026)); +const path = __importStar(__nccwpck_require__(71017)); +const patternHelper = __importStar(__nccwpck_require__(29005)); +const internal_match_kind_1 = __nccwpck_require__(81063); +const internal_pattern_1 = __nccwpck_require__(64536); +const internal_search_state_1 = __nccwpck_require__(89117); +const IS_WINDOWS = process.platform === 'win32'; +class DefaultGlobber { + constructor(options) { + this.patterns = []; + this.searchPaths = []; + this.options = globOptionsHelper.getOptions(options); } - /** - * Finds the summary file path from the environment, rejects if env var is not found or file does not exist - * Also checks r/w permissions. - * - * @returns step summary file path - */ - filePath() { + getSearchPaths() { + // Return a copy + return this.searchPaths.slice(); + } + glob() { + var e_1, _a; return __awaiter(this, void 0, void 0, function* () { - if (this._filePath) { - return this._filePath; - } - const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR]; - if (!pathFromEnv) { - throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); - } + const result = []; try { - yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); + for (var _b = __asyncValues(this.globGenerator()), _c; _c = yield _b.next(), !_c.done;) { + const itemPath = _c.value; + result.push(itemPath); + } } - catch (_a) { - throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b); + } + finally { if (e_1) throw e_1.error; } } - this._filePath = pathFromEnv; - return this._filePath; + return result; }); } - /** - * Wraps content in an HTML tag, adding any HTML attributes - * - * @param {string} tag HTML tag to wrap - * @param {string | null} content content within the tag - * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add - * - * @returns {string} content wrapped in HTML element - */ - wrap(tag, content, attrs = {}) { - const htmlAttrs = Object.entries(attrs) - .map(([key, value]) => ` ${key}="${value}"`) - .join(''); - if (!content) { - return `<${tag}${htmlAttrs}>`; - } - return `<${tag}${htmlAttrs}>${content}`; - } - /** - * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. - * - * @param {SummaryWriteOptions} [options] (optional) options for write operation - * - * @returns {Promise} summary instance - */ - write(options) { - return __awaiter(this, void 0, void 0, function* () { - const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); - const filePath = yield this.filePath(); - const writeFunc = overwrite ? writeFile : appendFile; - yield writeFunc(filePath, this._buffer, { encoding: 'utf8' }); - return this.emptyBuffer(); + globGenerator() { + return __asyncGenerator(this, arguments, function* globGenerator_1() { + // Fill in defaults options + const options = globOptionsHelper.getOptions(this.options); + // Implicit descendants? + const patterns = []; + for (const pattern of this.patterns) { + patterns.push(pattern); + if (options.implicitDescendants && + (pattern.trailingSeparator || + pattern.segments[pattern.segments.length - 1] !== '**')) { + patterns.push(new internal_pattern_1.Pattern(pattern.negate, true, pattern.segments.concat('**'))); + } + } + // Push the search paths + const stack = []; + for (const searchPath of patternHelper.getSearchPaths(patterns)) { + core.debug(`Search path '${searchPath}'`); + // Exists? + try { + // Intentionally using lstat. Detection for broken symlink + // will be performed later (if following symlinks). + yield __await(fs.promises.lstat(searchPath)); + } + catch (err) { + if (err.code === 'ENOENT') { + continue; + } + throw err; + } + stack.unshift(new internal_search_state_1.SearchState(searchPath, 1)); + } + // Search + const traversalChain = []; // used to detect cycles + while (stack.length) { + // Pop + const item = stack.pop(); + // Match? + const match = patternHelper.match(patterns, item.path); + const partialMatch = !!match || patternHelper.partialMatch(patterns, item.path); + if (!match && !partialMatch) { + continue; + } + // Stat + const stats = yield __await(DefaultGlobber.stat(item, options, traversalChain) + // Broken symlink, or symlink cycle detected, or no longer exists + ); + // Broken symlink, or symlink cycle detected, or no longer exists + if (!stats) { + continue; + } + // Directory + if (stats.isDirectory()) { + // Matched + if (match & internal_match_kind_1.MatchKind.Directory && options.matchDirectories) { + yield yield __await(item.path); + } + // Descend? + else if (!partialMatch) { + continue; + } + // Push the child items in reverse + const childLevel = item.level + 1; + const childItems = (yield __await(fs.promises.readdir(item.path))).map(x => new internal_search_state_1.SearchState(path.join(item.path, x), childLevel)); + stack.push(...childItems.reverse()); + } + // File + else if (match & internal_match_kind_1.MatchKind.File) { + yield yield __await(item.path); + } + } }); } /** - * Clears the summary buffer and wipes the summary file - * - * @returns {Summary} summary instance + * Constructs a DefaultGlobber */ - clear() { + static create(patterns, options) { return __awaiter(this, void 0, void 0, function* () { - return this.emptyBuffer().write({ overwrite: true }); + const result = new DefaultGlobber(options); + if (IS_WINDOWS) { + patterns = patterns.replace(/\r\n/g, '\n'); + patterns = patterns.replace(/\r/g, '\n'); + } + const lines = patterns.split('\n').map(x => x.trim()); + for (const line of lines) { + // Empty or comment + if (!line || line.startsWith('#')) { + continue; + } + // Pattern + else { + result.patterns.push(new internal_pattern_1.Pattern(line)); + } + } + result.searchPaths.push(...patternHelper.getSearchPaths(result.patterns)); + return result; }); } - /** - * Returns the current summary buffer as a string - * - * @returns {string} string of summary buffer - */ - stringify() { - return this._buffer; - } - /** - * If the summary buffer is empty - * - * @returns {boolen} true if the buffer is empty - */ - isEmptyBuffer() { - return this._buffer.length === 0; - } - /** - * Resets the summary buffer without writing to summary file - * - * @returns {Summary} summary instance - */ - emptyBuffer() { - this._buffer = ''; - return this; - } - /** - * Adds raw text to the summary buffer - * - * @param {string} text content to add - * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) - * - * @returns {Summary} summary instance - */ - addRaw(text, addEOL = false) { - this._buffer += text; - return addEOL ? this.addEOL() : this; - } - /** - * Adds the operating system-specific end-of-line marker to the buffer - * - * @returns {Summary} summary instance - */ - addEOL() { - return this.addRaw(os_1.EOL); - } - /** - * Adds an HTML codeblock to the summary buffer - * - * @param {string} code content to render within fenced code block - * @param {string} lang (optional) language to syntax highlight code - * - * @returns {Summary} summary instance - */ - addCodeBlock(code, lang) { - const attrs = Object.assign({}, (lang && { lang })); - const element = this.wrap('pre', this.wrap('code', code), attrs); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML list to the summary buffer - * - * @param {string[]} items list of items to render - * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) - * - * @returns {Summary} summary instance - */ - addList(items, ordered = false) { - const tag = ordered ? 'ol' : 'ul'; - const listItems = items.map(item => this.wrap('li', item)).join(''); - const element = this.wrap(tag, listItems); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML table to the summary buffer - * - * @param {SummaryTableCell[]} rows table rows - * - * @returns {Summary} summary instance - */ - addTable(rows) { - const tableBody = rows - .map(row => { - const cells = row - .map(cell => { - if (typeof cell === 'string') { - return this.wrap('td', cell); + static stat(item, options, traversalChain) { + return __awaiter(this, void 0, void 0, function* () { + // Note: + // `stat` returns info about the target of a symlink (or symlink chain) + // `lstat` returns info about a symlink itself + let stats; + if (options.followSymbolicLinks) { + try { + // Use `stat` (following symlinks) + stats = yield fs.promises.stat(item.path); } - const { header, data, colspan, rowspan } = cell; - const tag = header ? 'th' : 'td'; - const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan })); - return this.wrap(tag, data, attrs); - }) - .join(''); - return this.wrap('tr', cells); - }) - .join(''); - const element = this.wrap('table', tableBody); - return this.addRaw(element).addEOL(); - } - /** - * Adds a collapsable HTML details element to the summary buffer - * - * @param {string} label text for the closed state - * @param {string} content collapsable content - * - * @returns {Summary} summary instance - */ - addDetails(label, content) { - const element = this.wrap('details', this.wrap('summary', label) + content); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML image tag to the summary buffer - * - * @param {string} src path to the image you to embed - * @param {string} alt text description of the image - * @param {SummaryImageOptions} options (optional) addition image attributes - * - * @returns {Summary} summary instance - */ - addImage(src, alt, options) { - const { width, height } = options || {}; - const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height })); - const element = this.wrap('img', null, Object.assign({ src, alt }, attrs)); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML section heading element - * - * @param {string} text heading text - * @param {number | string} [level=1] (optional) the heading level, default: 1 - * - * @returns {Summary} summary instance - */ - addHeading(text, level) { - const tag = `h${level}`; - const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag) - ? tag - : 'h1'; - const element = this.wrap(allowedTag, text); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML thematic break (
) to the summary buffer - * - * @returns {Summary} summary instance - */ - addSeparator() { - const element = this.wrap('hr', null); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML line break (
) to the summary buffer - * - * @returns {Summary} summary instance - */ - addBreak() { - const element = this.wrap('br', null); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML blockquote to the summary buffer - * - * @param {string} text quote text - * @param {string} cite (optional) citation url - * - * @returns {Summary} summary instance - */ - addQuote(text, cite) { - const attrs = Object.assign({}, (cite && { cite })); - const element = this.wrap('blockquote', text, attrs); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML anchor tag to the summary buffer - * - * @param {string} text link text/content - * @param {string} href hyperlink - * - * @returns {Summary} summary instance - */ - addLink(text, href) { - const element = this.wrap('a', text, { href }); - return this.addRaw(element).addEOL(); - } -} -const _summary = new Summary(); -/** - * @deprecated use `core.summary` - */ -exports.markdownSummary = _summary; -exports.summary = _summary; -//# sourceMappingURL=summary.js.map - -/***/ }), - -/***/ 85932: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -// We use any as a valid input type -/* eslint-disable @typescript-eslint/no-explicit-any */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toCommandProperties = exports.toCommandValue = void 0; -/** - * Sanitizes an input into a string so it can be passed into issueCommand safely - * @param input input to sanitize into a string - */ -function toCommandValue(input) { - if (input === null || input === undefined) { - return ''; - } - else if (typeof input === 'string' || input instanceof String) { - return input; - } - return JSON.stringify(input); -} -exports.toCommandValue = toCommandValue; -/** - * - * @param annotationProperties - * @returns The command properties to send with the actual annotation command - * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646 - */ -function toCommandProperties(annotationProperties) { - if (!Object.keys(annotationProperties).length) { - return {}; + catch (err) { + if (err.code === 'ENOENT') { + if (options.omitBrokenSymbolicLinks) { + core.debug(`Broken symlink '${item.path}'`); + return undefined; + } + throw new Error(`No information found for the path '${item.path}'. This may indicate a broken symbolic link.`); + } + throw err; + } + } + else { + // Use `lstat` (not following symlinks) + stats = yield fs.promises.lstat(item.path); + } + // Note, isDirectory() returns false for the lstat of a symlink + if (stats.isDirectory() && options.followSymbolicLinks) { + // Get the realpath + const realPath = yield fs.promises.realpath(item.path); + // Fixup the traversal chain to match the item level + while (traversalChain.length >= item.level) { + traversalChain.pop(); + } + // Test for a cycle + if (traversalChain.some((x) => x === realPath)) { + core.debug(`Symlink cycle detected for path '${item.path}' and realpath '${realPath}'`); + return undefined; + } + // Update the traversal chain + traversalChain.push(realPath); + } + return stats; + }); } - return { - title: annotationProperties.title, - file: annotationProperties.file, - line: annotationProperties.startLine, - endLine: annotationProperties.endLine, - col: annotationProperties.startColumn, - endColumn: annotationProperties.endColumn - }; } -exports.toCommandProperties = toCommandProperties; -//# sourceMappingURL=utils.js.map +exports.DefaultGlobber = DefaultGlobber; +//# sourceMappingURL=internal-globber.js.map /***/ }), -/***/ 78489: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 2448: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __asyncValues = (this && this.__asyncValues) || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Context = void 0; -const fs_1 = __nccwpck_require__(57147); -const os_1 = __nccwpck_require__(22037); -class Context { - /** - * Hydrate the context from the environment - */ - constructor() { - var _a, _b, _c; - this.payload = {}; - if (process.env.GITHUB_EVENT_PATH) { - if (fs_1.existsSync(process.env.GITHUB_EVENT_PATH)) { - this.payload = JSON.parse(fs_1.readFileSync(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' })); +exports.hashFiles = void 0; +const crypto = __importStar(__nccwpck_require__(6113)); +const core = __importStar(__nccwpck_require__(42186)); +const fs = __importStar(__nccwpck_require__(57147)); +const stream = __importStar(__nccwpck_require__(12781)); +const util = __importStar(__nccwpck_require__(73837)); +const path = __importStar(__nccwpck_require__(71017)); +function hashFiles(globber, verbose = false) { + var e_1, _a; + var _b; + return __awaiter(this, void 0, void 0, function* () { + const writeDelegate = verbose ? core.info : core.debug; + let hasMatch = false; + const githubWorkspace = (_b = process.env['GITHUB_WORKSPACE']) !== null && _b !== void 0 ? _b : process.cwd(); + const result = crypto.createHash('sha256'); + let count = 0; + try { + for (var _c = __asyncValues(globber.globGenerator()), _d; _d = yield _c.next(), !_d.done;) { + const file = _d.value; + writeDelegate(file); + if (!file.startsWith(`${githubWorkspace}${path.sep}`)) { + writeDelegate(`Ignore '${file}' since it is not under GITHUB_WORKSPACE.`); + continue; + } + if (fs.statSync(file).isDirectory()) { + writeDelegate(`Skip directory '${file}'.`); + continue; + } + const hash = crypto.createHash('sha256'); + const pipeline = util.promisify(stream.pipeline); + yield pipeline(fs.createReadStream(file), hash); + result.write(hash.digest()); + count++; + if (!hasMatch) { + hasMatch = true; + } } - else { - const path = process.env.GITHUB_EVENT_PATH; - process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${os_1.EOL}`); + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_d && !_d.done && (_a = _c.return)) yield _a.call(_c); } + finally { if (e_1) throw e_1.error; } } - this.eventName = process.env.GITHUB_EVENT_NAME; - this.sha = process.env.GITHUB_SHA; - this.ref = process.env.GITHUB_REF; - this.workflow = process.env.GITHUB_WORKFLOW; - this.action = process.env.GITHUB_ACTION; - this.actor = process.env.GITHUB_ACTOR; - this.job = process.env.GITHUB_JOB; - this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10); - this.runId = parseInt(process.env.GITHUB_RUN_ID, 10); - this.apiUrl = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `https://api.github.com`; - this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`; - this.graphqlUrl = (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://github.com/gitapi/graphql`; - } - get issue() { - const payload = this.payload; - return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number }); - } - get repo() { - if (process.env.GITHUB_REPOSITORY) { - const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/'); - return { owner, repo }; + result.end(); + if (hasMatch) { + writeDelegate(`Found ${count} files to hash.`); + return result.digest('hex'); } - if (this.payload.repository) { - return { - owner: this.payload.repository.owner.login, - repo: this.payload.repository.name - }; + else { + writeDelegate(`No matches found for glob`); + return ''; } - throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'"); - } + }); } -exports.Context = Context; -//# sourceMappingURL=context.js.map +exports.hashFiles = hashFiles; +//# sourceMappingURL=internal-hash-files.js.map + +/***/ }), + +/***/ 81063: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MatchKind = void 0; +/** + * Indicates whether a pattern matches a path + */ +var MatchKind; +(function (MatchKind) { + /** Not matched */ + MatchKind[MatchKind["None"] = 0] = "None"; + /** Matched if the path is a directory */ + MatchKind[MatchKind["Directory"] = 1] = "Directory"; + /** Matched if the path is a regular file */ + MatchKind[MatchKind["File"] = 2] = "File"; + /** Matched */ + MatchKind[MatchKind["All"] = 3] = "All"; +})(MatchKind = exports.MatchKind || (exports.MatchKind = {})); +//# sourceMappingURL=internal-match-kind.js.map /***/ }), -/***/ 51132: +/***/ 1849: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -7611,27 +5178,188 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getOctokit = exports.context = void 0; -const Context = __importStar(__nccwpck_require__(78489)); -const utils_1 = __nccwpck_require__(43129); -exports.context = new Context.Context(); +exports.safeTrimTrailingSeparator = exports.normalizeSeparators = exports.hasRoot = exports.hasAbsoluteRoot = exports.ensureAbsoluteRoot = exports.dirname = void 0; +const path = __importStar(__nccwpck_require__(71017)); +const assert_1 = __importDefault(__nccwpck_require__(39491)); +const IS_WINDOWS = process.platform === 'win32'; /** - * Returns a hydrated octokit ready to use for GitHub Actions + * Similar to path.dirname except normalizes the path separators and slightly better handling for Windows UNC paths. * - * @param token the repo PAT or GITHUB_TOKEN - * @param options other options to set + * For example, on Linux/macOS: + * - `/ => /` + * - `/hello => /` + * + * For example, on Windows: + * - `C:\ => C:\` + * - `C:\hello => C:\` + * - `C: => C:` + * - `C:hello => C:` + * - `\ => \` + * - `\hello => \` + * - `\\hello => \\hello` + * - `\\hello\world => \\hello\world` */ -function getOctokit(token, options, ...additionalPlugins) { - const GitHubWithPlugins = utils_1.GitHub.plugin(...additionalPlugins); - return new GitHubWithPlugins(utils_1.getOctokitOptions(token, options)); +function dirname(p) { + // Normalize slashes and trim unnecessary trailing slash + p = safeTrimTrailingSeparator(p); + // Windows UNC root, e.g. \\hello or \\hello\world + if (IS_WINDOWS && /^\\\\[^\\]+(\\[^\\]+)?$/.test(p)) { + return p; + } + // Get dirname + let result = path.dirname(p); + // Trim trailing slash for Windows UNC root, e.g. \\hello\world\ + if (IS_WINDOWS && /^\\\\[^\\]+\\[^\\]+\\$/.test(result)) { + result = safeTrimTrailingSeparator(result); + } + return result; } -exports.getOctokit = getOctokit; -//# sourceMappingURL=github.js.map +exports.dirname = dirname; +/** + * Roots the path if not already rooted. On Windows, relative roots like `\` + * or `C:` are expanded based on the current working directory. + */ +function ensureAbsoluteRoot(root, itemPath) { + assert_1.default(root, `ensureAbsoluteRoot parameter 'root' must not be empty`); + assert_1.default(itemPath, `ensureAbsoluteRoot parameter 'itemPath' must not be empty`); + // Already rooted + if (hasAbsoluteRoot(itemPath)) { + return itemPath; + } + // Windows + if (IS_WINDOWS) { + // Check for itemPath like C: or C:foo + if (itemPath.match(/^[A-Z]:[^\\/]|^[A-Z]:$/i)) { + let cwd = process.cwd(); + assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); + // Drive letter matches cwd? Expand to cwd + if (itemPath[0].toUpperCase() === cwd[0].toUpperCase()) { + // Drive only, e.g. C: + if (itemPath.length === 2) { + // Preserve specified drive letter case (upper or lower) + return `${itemPath[0]}:\\${cwd.substr(3)}`; + } + // Drive + path, e.g. C:foo + else { + if (!cwd.endsWith('\\')) { + cwd += '\\'; + } + // Preserve specified drive letter case (upper or lower) + return `${itemPath[0]}:\\${cwd.substr(3)}${itemPath.substr(2)}`; + } + } + // Different drive + else { + return `${itemPath[0]}:\\${itemPath.substr(2)}`; + } + } + // Check for itemPath like \ or \foo + else if (normalizeSeparators(itemPath).match(/^\\$|^\\[^\\]/)) { + const cwd = process.cwd(); + assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); + return `${cwd[0]}:\\${itemPath.substr(1)}`; + } + } + assert_1.default(hasAbsoluteRoot(root), `ensureAbsoluteRoot parameter 'root' must have an absolute root`); + // Otherwise ensure root ends with a separator + if (root.endsWith('/') || (IS_WINDOWS && root.endsWith('\\'))) { + // Intentionally empty + } + else { + // Append separator + root += path.sep; + } + return root + itemPath; +} +exports.ensureAbsoluteRoot = ensureAbsoluteRoot; +/** + * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like: + * `\\hello\share` and `C:\hello` (and using alternate separator). + */ +function hasAbsoluteRoot(itemPath) { + assert_1.default(itemPath, `hasAbsoluteRoot parameter 'itemPath' must not be empty`); + // Normalize separators + itemPath = normalizeSeparators(itemPath); + // Windows + if (IS_WINDOWS) { + // E.g. \\hello\share or C:\hello + return itemPath.startsWith('\\\\') || /^[A-Z]:\\/i.test(itemPath); + } + // E.g. /hello + return itemPath.startsWith('/'); +} +exports.hasAbsoluteRoot = hasAbsoluteRoot; +/** + * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like: + * `\`, `\hello`, `\\hello\share`, `C:`, and `C:\hello` (and using alternate separator). + */ +function hasRoot(itemPath) { + assert_1.default(itemPath, `isRooted parameter 'itemPath' must not be empty`); + // Normalize separators + itemPath = normalizeSeparators(itemPath); + // Windows + if (IS_WINDOWS) { + // E.g. \ or \hello or \\hello + // E.g. C: or C:\hello + return itemPath.startsWith('\\') || /^[A-Z]:/i.test(itemPath); + } + // E.g. /hello + return itemPath.startsWith('/'); +} +exports.hasRoot = hasRoot; +/** + * Removes redundant slashes and converts `/` to `\` on Windows + */ +function normalizeSeparators(p) { + p = p || ''; + // Windows + if (IS_WINDOWS) { + // Convert slashes on Windows + p = p.replace(/\//g, '\\'); + // Remove redundant slashes + const isUnc = /^\\\\+[^\\]/.test(p); // e.g. \\hello + return (isUnc ? '\\' : '') + p.replace(/\\\\+/g, '\\'); // preserve leading \\ for UNC + } + // Remove redundant slashes + return p.replace(/\/\/+/g, '/'); +} +exports.normalizeSeparators = normalizeSeparators; +/** + * Normalizes the path separators and trims the trailing separator (when safe). + * For example, `/foo/ => /foo` but `/ => /` + */ +function safeTrimTrailingSeparator(p) { + // Short-circuit if empty + if (!p) { + return ''; + } + // Normalize separators + p = normalizeSeparators(p); + // No trailing slash + if (!p.endsWith(path.sep)) { + return p; + } + // Check '/' on Linux/macOS and '\' on Windows + if (p === path.sep) { + return p; + } + // On Windows check if drive root. E.g. C:\ + if (IS_WINDOWS && /^[A-Z]:\\$/i.test(p)) { + return p; + } + // Otherwise trim trailing slash + return p.substr(0, p.length - 1); +} +exports.safeTrimTrailingSeparator = safeTrimTrailingSeparator; +//# sourceMappingURL=internal-path-helper.js.map /***/ }), -/***/ 31179: +/***/ 96836: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -7655,33 +5383,103 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getApiBaseUrl = exports.getProxyAgent = exports.getAuthString = void 0; -const httpClient = __importStar(__nccwpck_require__(52932)); -function getAuthString(token, options) { - if (!token && !options.auth) { - throw new Error('Parameter token or opts.auth is required'); +exports.Path = void 0; +const path = __importStar(__nccwpck_require__(71017)); +const pathHelper = __importStar(__nccwpck_require__(1849)); +const assert_1 = __importDefault(__nccwpck_require__(39491)); +const IS_WINDOWS = process.platform === 'win32'; +/** + * Helper class for parsing paths into segments + */ +class Path { + /** + * Constructs a Path + * @param itemPath Path or array of segments + */ + constructor(itemPath) { + this.segments = []; + // String + if (typeof itemPath === 'string') { + assert_1.default(itemPath, `Parameter 'itemPath' must not be empty`); + // Normalize slashes and trim unnecessary trailing slash + itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); + // Not rooted + if (!pathHelper.hasRoot(itemPath)) { + this.segments = itemPath.split(path.sep); + } + // Rooted + else { + // Add all segments, while not at the root + let remaining = itemPath; + let dir = pathHelper.dirname(remaining); + while (dir !== remaining) { + // Add the segment + const basename = path.basename(remaining); + this.segments.unshift(basename); + // Truncate the last segment + remaining = dir; + dir = pathHelper.dirname(remaining); + } + // Remainder is the root + this.segments.unshift(remaining); + } + } + // Array + else { + // Must not be empty + assert_1.default(itemPath.length > 0, `Parameter 'itemPath' must not be an empty array`); + // Each segment + for (let i = 0; i < itemPath.length; i++) { + let segment = itemPath[i]; + // Must not be empty + assert_1.default(segment, `Parameter 'itemPath' must not contain any empty segments`); + // Normalize slashes + segment = pathHelper.normalizeSeparators(itemPath[i]); + // Root segment + if (i === 0 && pathHelper.hasRoot(segment)) { + segment = pathHelper.safeTrimTrailingSeparator(segment); + assert_1.default(segment === pathHelper.dirname(segment), `Parameter 'itemPath' root segment contains information for multiple segments`); + this.segments.push(segment); + } + // All other segments + else { + // Must not contain slash + assert_1.default(!segment.includes(path.sep), `Parameter 'itemPath' contains unexpected path separators`); + this.segments.push(segment); + } + } + } } - else if (token && options.auth) { - throw new Error('Parameters token and opts.auth may not both be specified'); + /** + * Converts the path to it's string representation + */ + toString() { + // First segment + let result = this.segments[0]; + // All others + let skipSlash = result.endsWith(path.sep) || (IS_WINDOWS && /^[A-Z]:$/i.test(result)); + for (let i = 1; i < this.segments.length; i++) { + if (skipSlash) { + skipSlash = false; + } + else { + result += path.sep; + } + result += this.segments[i]; + } + return result; } - return typeof options.auth === 'string' ? options.auth : `token ${token}`; -} -exports.getAuthString = getAuthString; -function getProxyAgent(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgent(destinationUrl); -} -exports.getProxyAgent = getProxyAgent; -function getApiBaseUrl() { - return process.env['GITHUB_API_URL'] || 'https://api.github.com'; } -exports.getApiBaseUrl = getApiBaseUrl; -//# sourceMappingURL=utils.js.map +exports.Path = Path; +//# sourceMappingURL=internal-path.js.map /***/ }), -/***/ 43129: +/***/ 29005: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -7706,57 +5504,377 @@ var __importStar = (this && this.__importStar) || function (mod) { return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getOctokitOptions = exports.GitHub = exports.defaults = exports.context = void 0; -const Context = __importStar(__nccwpck_require__(78489)); -const Utils = __importStar(__nccwpck_require__(31179)); -// octokit + plugins -const core_1 = __nccwpck_require__(34266); -const plugin_rest_endpoint_methods_1 = __nccwpck_require__(68590); -const plugin_paginate_rest_1 = __nccwpck_require__(60345); -exports.context = new Context.Context(); -const baseUrl = Utils.getApiBaseUrl(); -exports.defaults = { - baseUrl, - request: { - agent: Utils.getProxyAgent(baseUrl) +exports.partialMatch = exports.match = exports.getSearchPaths = void 0; +const pathHelper = __importStar(__nccwpck_require__(1849)); +const internal_match_kind_1 = __nccwpck_require__(81063); +const IS_WINDOWS = process.platform === 'win32'; +/** + * Given an array of patterns, returns an array of paths to search. + * Duplicates and paths under other included paths are filtered out. + */ +function getSearchPaths(patterns) { + // Ignore negate patterns + patterns = patterns.filter(x => !x.negate); + // Create a map of all search paths + const searchPathMap = {}; + for (const pattern of patterns) { + const key = IS_WINDOWS + ? pattern.searchPath.toUpperCase() + : pattern.searchPath; + searchPathMap[key] = 'candidate'; } -}; -exports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(exports.defaults); + const result = []; + for (const pattern of patterns) { + // Check if already included + const key = IS_WINDOWS + ? pattern.searchPath.toUpperCase() + : pattern.searchPath; + if (searchPathMap[key] === 'included') { + continue; + } + // Check for an ancestor search path + let foundAncestor = false; + let tempKey = key; + let parent = pathHelper.dirname(tempKey); + while (parent !== tempKey) { + if (searchPathMap[parent]) { + foundAncestor = true; + break; + } + tempKey = parent; + parent = pathHelper.dirname(tempKey); + } + // Include the search pattern in the result + if (!foundAncestor) { + result.push(pattern.searchPath); + searchPathMap[key] = 'included'; + } + } + return result; +} +exports.getSearchPaths = getSearchPaths; /** - * Convience function to correctly format Octokit Options to pass into the constructor. - * - * @param token the repo PAT or GITHUB_TOKEN - * @param options other options to set + * Matches the patterns against the path */ -function getOctokitOptions(token, options) { - const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller - // Auth - const auth = Utils.getAuthString(token, opts); - if (auth) { - opts.auth = auth; +function match(patterns, itemPath) { + let result = internal_match_kind_1.MatchKind.None; + for (const pattern of patterns) { + if (pattern.negate) { + result &= ~pattern.match(itemPath); + } + else { + result |= pattern.match(itemPath); + } } - return opts; + return result; } -exports.getOctokitOptions = getOctokitOptions; -//# sourceMappingURL=utils.js.map +exports.match = match; +/** + * Checks whether to descend further into the directory + */ +function partialMatch(patterns, itemPath) { + return patterns.some(x => !x.negate && x.partialMatch(itemPath)); +} +exports.partialMatch = partialMatch; +//# sourceMappingURL=internal-pattern-helper.js.map /***/ }), -/***/ 40903: -/***/ (function(__unused_webpack_module, exports) { +/***/ 64536: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Pattern = void 0; +const os = __importStar(__nccwpck_require__(22037)); +const path = __importStar(__nccwpck_require__(71017)); +const pathHelper = __importStar(__nccwpck_require__(1849)); +const assert_1 = __importDefault(__nccwpck_require__(39491)); +const minimatch_1 = __nccwpck_require__(83973); +const internal_match_kind_1 = __nccwpck_require__(81063); +const internal_path_1 = __nccwpck_require__(96836); +const IS_WINDOWS = process.platform === 'win32'; +class Pattern { + constructor(patternOrNegate, isImplicitPattern = false, segments, homedir) { + /** + * Indicates whether matches should be excluded from the result set + */ + this.negate = false; + // Pattern overload + let pattern; + if (typeof patternOrNegate === 'string') { + pattern = patternOrNegate.trim(); + } + // Segments overload + else { + // Convert to pattern + segments = segments || []; + assert_1.default(segments.length, `Parameter 'segments' must not empty`); + const root = Pattern.getLiteral(segments[0]); + assert_1.default(root && pathHelper.hasAbsoluteRoot(root), `Parameter 'segments' first element must be a root path`); + pattern = new internal_path_1.Path(segments).toString().trim(); + if (patternOrNegate) { + pattern = `!${pattern}`; + } + } + // Negate + while (pattern.startsWith('!')) { + this.negate = !this.negate; + pattern = pattern.substr(1).trim(); + } + // Normalize slashes and ensures absolute root + pattern = Pattern.fixupPattern(pattern, homedir); + // Segments + this.segments = new internal_path_1.Path(pattern).segments; + // Trailing slash indicates the pattern should only match directories, not regular files + this.trailingSeparator = pathHelper + .normalizeSeparators(pattern) + .endsWith(path.sep); + pattern = pathHelper.safeTrimTrailingSeparator(pattern); + // Search path (literal path prior to the first glob segment) + let foundGlob = false; + const searchSegments = this.segments + .map(x => Pattern.getLiteral(x)) + .filter(x => !foundGlob && !(foundGlob = x === '')); + this.searchPath = new internal_path_1.Path(searchSegments).toString(); + // Root RegExp (required when determining partial match) + this.rootRegExp = new RegExp(Pattern.regExpEscape(searchSegments[0]), IS_WINDOWS ? 'i' : ''); + this.isImplicitPattern = isImplicitPattern; + // Create minimatch + const minimatchOptions = { + dot: true, + nobrace: true, + nocase: IS_WINDOWS, + nocomment: true, + noext: true, + nonegate: true + }; + pattern = IS_WINDOWS ? pattern.replace(/\\/g, '/') : pattern; + this.minimatch = new minimatch_1.Minimatch(pattern, minimatchOptions); + } + /** + * Matches the pattern against the specified path + */ + match(itemPath) { + // Last segment is globstar? + if (this.segments[this.segments.length - 1] === '**') { + // Normalize slashes + itemPath = pathHelper.normalizeSeparators(itemPath); + // Append a trailing slash. Otherwise Minimatch will not match the directory immediately + // preceding the globstar. For example, given the pattern `/foo/**`, Minimatch returns + // false for `/foo` but returns true for `/foo/`. Append a trailing slash to handle that quirk. + if (!itemPath.endsWith(path.sep) && this.isImplicitPattern === false) { + // Note, this is safe because the constructor ensures the pattern has an absolute root. + // For example, formats like C: and C:foo on Windows are resolved to an absolute root. + itemPath = `${itemPath}${path.sep}`; + } + } + else { + // Normalize slashes and trim unnecessary trailing slash + itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); + } + // Match + if (this.minimatch.match(itemPath)) { + return this.trailingSeparator ? internal_match_kind_1.MatchKind.Directory : internal_match_kind_1.MatchKind.All; + } + return internal_match_kind_1.MatchKind.None; + } + /** + * Indicates whether the pattern may match descendants of the specified path + */ + partialMatch(itemPath) { + // Normalize slashes and trim unnecessary trailing slash + itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); + // matchOne does not handle root path correctly + if (pathHelper.dirname(itemPath) === itemPath) { + return this.rootRegExp.test(itemPath); + } + return this.minimatch.matchOne(itemPath.split(IS_WINDOWS ? /\\+/ : /\/+/), this.minimatch.set[0], true); + } + /** + * Escapes glob patterns within a path + */ + static globEscape(s) { + return (IS_WINDOWS ? s : s.replace(/\\/g, '\\\\')) // escape '\' on Linux/macOS + .replace(/(\[)(?=[^/]+\])/g, '[[]') // escape '[' when ']' follows within the path segment + .replace(/\?/g, '[?]') // escape '?' + .replace(/\*/g, '[*]'); // escape '*' + } + /** + * Normalizes slashes and ensures absolute root + */ + static fixupPattern(pattern, homedir) { + // Empty + assert_1.default(pattern, 'pattern cannot be empty'); + // Must not contain `.` segment, unless first segment + // Must not contain `..` segment + const literalSegments = new internal_path_1.Path(pattern).segments.map(x => Pattern.getLiteral(x)); + assert_1.default(literalSegments.every((x, i) => (x !== '.' || i === 0) && x !== '..'), `Invalid pattern '${pattern}'. Relative pathing '.' and '..' is not allowed.`); + // Must not contain globs in root, e.g. Windows UNC path \\foo\b*r + assert_1.default(!pathHelper.hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`); + // Normalize slashes + pattern = pathHelper.normalizeSeparators(pattern); + // Replace leading `.` segment + if (pattern === '.' || pattern.startsWith(`.${path.sep}`)) { + pattern = Pattern.globEscape(process.cwd()) + pattern.substr(1); + } + // Replace leading `~` segment + else if (pattern === '~' || pattern.startsWith(`~${path.sep}`)) { + homedir = homedir || os.homedir(); + assert_1.default(homedir, 'Unable to determine HOME directory'); + assert_1.default(pathHelper.hasAbsoluteRoot(homedir), `Expected HOME directory to be a rooted path. Actual '${homedir}'`); + pattern = Pattern.globEscape(homedir) + pattern.substr(1); + } + // Replace relative drive root, e.g. pattern is C: or C:foo + else if (IS_WINDOWS && + (pattern.match(/^[A-Z]:$/i) || pattern.match(/^[A-Z]:[^\\]/i))) { + let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', pattern.substr(0, 2)); + if (pattern.length > 2 && !root.endsWith('\\')) { + root += '\\'; + } + pattern = Pattern.globEscape(root) + pattern.substr(2); + } + // Replace relative root, e.g. pattern is \ or \foo + else if (IS_WINDOWS && (pattern === '\\' || pattern.match(/^\\[^\\]/))) { + let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', '\\'); + if (!root.endsWith('\\')) { + root += '\\'; + } + pattern = Pattern.globEscape(root) + pattern.substr(1); + } + // Otherwise ensure absolute root + else { + pattern = pathHelper.ensureAbsoluteRoot(Pattern.globEscape(process.cwd()), pattern); + } + return pathHelper.normalizeSeparators(pattern); + } + /** + * Attempts to unescape a pattern segment to create a literal path segment. + * Otherwise returns empty string. + */ + static getLiteral(segment) { + let literal = ''; + for (let i = 0; i < segment.length; i++) { + const c = segment[i]; + // Escape + if (c === '\\' && !IS_WINDOWS && i + 1 < segment.length) { + literal += segment[++i]; + continue; + } + // Wildcard + else if (c === '*' || c === '?') { + return ''; + } + // Character set + else if (c === '[' && i + 1 < segment.length) { + let set = ''; + let closed = -1; + for (let i2 = i + 1; i2 < segment.length; i2++) { + const c2 = segment[i2]; + // Escape + if (c2 === '\\' && !IS_WINDOWS && i2 + 1 < segment.length) { + set += segment[++i2]; + continue; + } + // Closed + else if (c2 === ']') { + closed = i2; + break; + } + // Otherwise + else { + set += c2; + } + } + // Closed? + if (closed >= 0) { + // Cannot convert + if (set.length > 1) { + return ''; + } + // Convert to literal + if (set) { + literal += set; + i = closed; + continue; + } + } + // Otherwise fall thru + } + // Append + literal += c; + } + return literal; + } + /** + * Escapes regexp special characters + * https://javascript.info/regexp-escaping + */ + static regExpEscape(s) { + return s.replace(/[[\\^$.|?*+()]/g, '\\$&'); + } +} +exports.Pattern = Pattern; +//# sourceMappingURL=internal-pattern.js.map + +/***/ }), + +/***/ 89117: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SearchState = void 0; +class SearchState { + constructor(path, level) { + this.path = path; + this.level = level; + } +} +exports.SearchState = SearchState; +//# sourceMappingURL=internal-search-state.js.map + +/***/ }), + +/***/ 35526: +/***/ (function(__unused_webpack_module, exports) { + +"use strict"; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0; class BasicCredentialHandler { constructor(username, password) { @@ -7830,7 +5948,7 @@ exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHand /***/ }), -/***/ 52932: +/***/ 96255: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -7838,7 +5956,11 @@ exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHand /* eslint-disable @typescript-eslint/no-explicit-any */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -7851,7 +5973,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; @@ -7868,8 +5990,9 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; const http = __importStar(__nccwpck_require__(13685)); const https = __importStar(__nccwpck_require__(95687)); -const pm = __importStar(__nccwpck_require__(34465)); -const tunnel = __importStar(__nccwpck_require__(20791)); +const pm = __importStar(__nccwpck_require__(19835)); +const tunnel = __importStar(__nccwpck_require__(74294)); +const undici_1 = __nccwpck_require__(41773); var HttpCodes; (function (HttpCodes) { HttpCodes[HttpCodes["OK"] = 200] = "OK"; @@ -7899,16 +6022,16 @@ var HttpCodes; HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; -})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); +})(HttpCodes || (exports.HttpCodes = HttpCodes = {})); var Headers; (function (Headers) { Headers["Accept"] = "accept"; Headers["ContentType"] = "content-type"; -})(Headers = exports.Headers || (exports.Headers = {})); +})(Headers || (exports.Headers = Headers = {})); var MediaTypes; (function (MediaTypes) { MediaTypes["ApplicationJson"] = "application/json"; -})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); +})(MediaTypes || (exports.MediaTypes = MediaTypes = {})); /** * Returns the proxy URL, depending upon the supplied url and proxy environment variables. * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com @@ -7959,6 +6082,19 @@ class HttpClientResponse { })); }); } + readBodyBuffer() { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { + const chunks = []; + this.message.on('data', (chunk) => { + chunks.push(chunk); + }); + this.message.on('end', () => { + resolve(Buffer.concat(chunks)); + }); + })); + }); + } } exports.HttpClientResponse = HttpClientResponse; function isHttps(requestUrl) { @@ -8264,6 +6400,15 @@ class HttpClient { const parsedUrl = new URL(serverUrl); return this._getAgent(parsedUrl); } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + } _prepareRequest(method, requestUrl, headers) { const info = {}; info.parsedUrl = requestUrl; @@ -8363,6 +6508,30 @@ class HttpClient { } return agent; } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + // if agent is already assigned use that agent. + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === 'https:'; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && { + token: `${proxyUrl.username}:${proxyUrl.password}` + }))); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process + // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options + // we have to cast it to any and change it directly + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } _performExponentialBackoff(retryNumber) { return __awaiter(this, void 0, void 0, function* () { retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); @@ -8442,7 +6611,7 @@ const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCa /***/ }), -/***/ 34465: +/***/ 19835: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -8463,7 +6632,13 @@ function getProxyUrl(reqUrl) { } })(); if (proxyVar) { - return new URL(proxyVar); + try { + return new URL(proxyVar); + } + catch (_a) { + if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) + return new URL(`http://${proxyVar}`); + } } else { return undefined; @@ -8525,7 +6700,7 @@ function isLoopbackAddress(host) { /***/ }), -/***/ 46889: +/***/ 52557: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -8772,7 +6947,7 @@ exports.AbortSignal = AbortSignal; /***/ }), -/***/ 81417: +/***/ 39645: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -8780,7 +6955,7 @@ exports.AbortSignal = AbortSignal; Object.defineProperty(exports, "__esModule", ({ value: true })); -var coreUtil = __nccwpck_require__(47574); +var coreUtil = __nccwpck_require__(51333); // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -8958,7 +7133,7 @@ exports.isTokenCredential = isTokenCredential; /***/ }), -/***/ 85643: +/***/ 24607: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -8966,22 +7141,22 @@ exports.isTokenCredential = isTokenCredential; Object.defineProperty(exports, "__esModule", ({ value: true })); -var uuid = __nccwpck_require__(4413); +var uuid = __nccwpck_require__(75840); var util = __nccwpck_require__(73837); -var tslib = __nccwpck_require__(92716); -var xml2js = __nccwpck_require__(50827); -var coreUtil = __nccwpck_require__(47574); -var logger$1 = __nccwpck_require__(68476); -var coreAuth = __nccwpck_require__(81417); +var tslib = __nccwpck_require__(4351); +var xml2js = __nccwpck_require__(66189); +var coreUtil = __nccwpck_require__(51333); +var logger$1 = __nccwpck_require__(3233); +var coreAuth = __nccwpck_require__(39645); var os = __nccwpck_require__(22037); var http = __nccwpck_require__(13685); var https = __nccwpck_require__(95687); -var abortController = __nccwpck_require__(46889); -var tunnel = __nccwpck_require__(20791); +var abortController = __nccwpck_require__(52557); +var tunnel = __nccwpck_require__(74294); var stream = __nccwpck_require__(12781); -var FormData = __nccwpck_require__(79700); -var node_fetch = __nccwpck_require__(96295); -var coreTracing = __nccwpck_require__(22001); +var FormData = __nccwpck_require__(64334); +var node_fetch = __nccwpck_require__(80467); +var coreTracing = __nccwpck_require__(94175); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } @@ -9058,7 +7233,7 @@ class HttpHeaders { set(headerName, headerValue) { this._headersMap[getHeaderKey(headerName)] = { name: headerName, - value: headerValue.toString(), + value: headerValue.toString().trim(), }; } /** @@ -9198,7 +7373,7 @@ const Constants = { /** * The core-http version */ - coreHttpVersion: "3.0.2", + coreHttpVersion: "3.0.4", /** * Specifies HTTP. */ @@ -14431,7 +12606,7 @@ exports.userAgentPolicy = userAgentPolicy; /***/ }), -/***/ 59158: +/***/ 27094: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -14439,9 +12614,9 @@ exports.userAgentPolicy = userAgentPolicy; Object.defineProperty(exports, "__esModule", ({ value: true })); -var logger$1 = __nccwpck_require__(68476); -var abortController = __nccwpck_require__(46889); -var coreUtil = __nccwpck_require__(47574); +var logger$1 = __nccwpck_require__(3233); +var abortController = __nccwpck_require__(52557); +var coreUtil = __nccwpck_require__(51333); // Copyright (c) Microsoft Corporation. /** @@ -15607,7 +13782,7 @@ exports.createHttpPoller = createHttpPoller; /***/ }), -/***/ 7595: +/***/ 74559: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -15615,7 +13790,7 @@ exports.createHttpPoller = createHttpPoller; Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib = __nccwpck_require__(92716); +var tslib = __nccwpck_require__(4351); // Copyright (c) Microsoft Corporation. /** @@ -15719,7 +13894,7 @@ exports.getPagedAsyncIterator = getPagedAsyncIterator; /***/ }), -/***/ 22001: +/***/ 94175: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -15727,7 +13902,7 @@ exports.getPagedAsyncIterator = getPagedAsyncIterator; Object.defineProperty(exports, "__esModule", ({ value: true })); -var api = __nccwpck_require__(27742); +var api = __nccwpck_require__(65163); // Copyright (c) Microsoft Corporation. (function (SpanKind) { @@ -15946,18 +14121,17 @@ exports.setSpanContext = setSpanContext; /***/ }), -/***/ 47574: +/***/ 51333: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var abortController = __nccwpck_require__(46889); +var abortController = __nccwpck_require__(52557); var crypto = __nccwpck_require__(6113); // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. /** * Creates an abortable promise. * @param buildPromise - A function that takes the resolve and reject functions as parameters. @@ -15998,6 +14172,7 @@ function createAbortablePromise(buildPromise, options) { } // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. const StandardAbortMessage = "The delay was aborted."; /** * A wrapper for setTimeout that resolves a promise after timeInMs milliseconds. @@ -16017,6 +14192,27 @@ function delay(timeInMs, options) { }); } +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * promise.race() wrapper that aborts rest of promises as soon as the first promise settles. + */ +async function cancelablePromiseRace(abortablePromiseBuilders, options) { + var _a, _b; + const aborter = new abortController.AbortController(); + function abortHandler() { + aborter.abort(); + } + (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", abortHandler); + try { + return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal }))); + } + finally { + aborter.abort(); + (_b = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _b === void 0 ? void 0 : _b.removeEventListener("abort", abortHandler); + } +} + // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** @@ -16053,6 +14249,7 @@ function isObject(input) { } // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. /** * Typeguard for an error object shape (has name and message) * @param e - Something caught by a catch clause. @@ -16093,6 +14290,7 @@ function getErrorMessage(e) { } // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. /** * Generates a SHA-256 HMAC signature. * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash. @@ -16217,16 +14415,20 @@ const isWebWorker = typeof self === "object" && (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" || ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" || ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope"); -/** - * A constant that indicates whether the environment the code is running is Node.JS. - */ -const isNode = typeof process !== "undefined" && Boolean(process.version) && Boolean((_d = process.versions) === null || _d === void 0 ? void 0 : _d.node); /** * A constant that indicates whether the environment the code is running is Deno. */ const isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined"; +/** + * A constant that indicates whether the environment the code is running is Node.JS. + */ +const isNode = typeof process !== "undefined" && + Boolean(process.version) && + Boolean((_d = process.versions) === null || _d === void 0 ? void 0 : _d.node) && + // Deno thought it was a good idea to spoof process.versions.node, see https://deno.land/std@0.177.0/node/process.ts?s=versions + !isDeno; /** * A constant that indicates whether the environment the code is running is Bun.sh. */ @@ -16246,14 +14448,7 @@ const isReactNative = typeof navigator !== "undefined" && (navigator === null || * @returns a string of the encoded string */ function uint8ArrayToString(bytes, format) { - switch (format) { - case "utf-8": - return uint8ArrayToUtf8String(bytes); - case "base64": - return uint8ArrayToBase64(bytes); - case "base64url": - return uint8ArrayToBase64Url(bytes); - } + return Buffer.from(bytes).toString(format); } /** * The helper that transforms string to specific character encoded bytes array. @@ -16262,58 +14457,10 @@ function uint8ArrayToString(bytes, format) { * @returns a uint8array */ function stringToUint8Array(value, format) { - switch (format) { - case "utf-8": - return utf8StringToUint8Array(value); - case "base64": - return base64ToUint8Array(value); - case "base64url": - return base64UrlToUint8Array(value); - } -} -/** - * Decodes a Uint8Array into a Base64 string. - * @internal - */ -function uint8ArrayToBase64(bytes) { - return Buffer.from(bytes).toString("base64"); -} -/** - * Decodes a Uint8Array into a Base64Url string. - * @internal - */ -function uint8ArrayToBase64Url(bytes) { - return Buffer.from(bytes).toString("base64url"); -} -/** - * Decodes a Uint8Array into a javascript string. - * @internal - */ -function uint8ArrayToUtf8String(bytes) { - return Buffer.from(bytes).toString("utf-8"); -} -/** - * Encodes a JavaScript string into a Uint8Array. - * @internal - */ -function utf8StringToUint8Array(value) { - return Buffer.from(value); -} -/** - * Encodes a Base64 string into a Uint8Array. - * @internal - */ -function base64ToUint8Array(value) { - return Buffer.from(value, "base64"); -} -/** - * Encodes a Base64Url string into a Uint8Array. - * @internal - */ -function base64UrlToUint8Array(value) { - return Buffer.from(value, "base64url"); + return Buffer.from(value, format); } +exports.cancelablePromiseRace = cancelablePromiseRace; exports.computeSha256Hash = computeSha256Hash; exports.computeSha256Hmac = computeSha256Hmac; exports.createAbortablePromise = createAbortablePromise; @@ -16339,7 +14486,7 @@ exports.uint8ArrayToString = uint8ArrayToString; /***/ }), -/***/ 68476: +/***/ 3233: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -16555,7 +14702,7 @@ exports.setLogLevel = setLogLevel; /***/ }), -/***/ 18061: +/***/ 84100: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -16563,16 +14710,16 @@ exports.setLogLevel = setLogLevel; Object.defineProperty(exports, "__esModule", ({ value: true })); -var coreHttp = __nccwpck_require__(85643); -var tslib = __nccwpck_require__(92716); -var coreTracing = __nccwpck_require__(22001); -var logger$1 = __nccwpck_require__(68476); -var abortController = __nccwpck_require__(46889); +var coreHttp = __nccwpck_require__(24607); +var tslib = __nccwpck_require__(4351); +var coreTracing = __nccwpck_require__(94175); +var logger$1 = __nccwpck_require__(3233); +var abortController = __nccwpck_require__(52557); var os = __nccwpck_require__(22037); var crypto = __nccwpck_require__(6113); var stream = __nccwpck_require__(12781); -__nccwpck_require__(7595); -var coreLro = __nccwpck_require__(59158); +__nccwpck_require__(74559); +var coreLro = __nccwpck_require__(27094); var events = __nccwpck_require__(82361); var fs = __nccwpck_require__(57147); var util = __nccwpck_require__(73837); @@ -17897,7 +16044,8 @@ const BlobPropertiesInternal = { name: "Enum", allowedValues: [ "rehydrate-pending-to-hot", - "rehydrate-pending-to-cool" + "rehydrate-pending-to-cool", + "rehydrate-pending-to-cold" ] } }, @@ -25067,7 +23215,7 @@ const timeoutInSeconds = { const version = { parameterPath: "version", mapper: { - defaultValue: "2023-01-03", + defaultValue: "2023-11-03", isConstant: true, serializedName: "x-ms-version", type: { @@ -29898,8 +28046,8 @@ const logger = logger$1.createClientLogger("storage-blob"); // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -const SDK_VERSION = "12.15.0"; -const SERVICE_VERSION = "2023-01-03"; +const SDK_VERSION = "12.17.0"; +const SERVICE_VERSION = "2023-11-03"; const BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES = 256 * 1024 * 1024; // 256MB const BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES = 4000 * 1024 * 1024; // 4000MB const BLOCK_BLOB_MAX_BLOCKS = 50000; @@ -30263,7 +28411,11 @@ function extractConnectionStringParts(connectionString) { else { // SAS connection string const accountSas = getValueInConnString(connectionString, "SharedAccessSignature"); - const accountName = getAccountNameFromUrl(blobEndpoint); + let accountName = getValueInConnString(connectionString, "AccountName"); + // if accountName is empty, try to read it from BlobEndpoint + if (!accountName) { + accountName = getAccountNameFromUrl(blobEndpoint); + } if (!blobEndpoint) { throw new Error("Invalid BlobEndpoint in the provided SAS Connection String"); } @@ -30557,10 +28709,10 @@ function isIpEndpointStyle(parsedUrl) { } const host = parsedUrl.getHost() + (parsedUrl.getPort() === undefined ? "" : ":" + parsedUrl.getPort()); // Case 1: Ipv6, use a broad regex to find out candidates whose host contains two ':'. - // Case 2: localhost(:port), use broad regex to match port part. + // Case 2: localhost(:port) or host.docker.internal, use broad regex to match port part. // Case 3: Ipv4, use broad regex which just check if host contains Ipv4. // For valid host please refer to https://man7.org/linux/man-pages/man7/hostname.7.html. - return (/^.*:.*:.*$|^localhost(:[0-9]+)?$|^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])){3}(:[0-9]+)?$/.test(host) || + return (/^.*:.*:.*$|^(localhost|host.docker.internal)(:[0-9]+)?$|^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])){3}(:[0-9]+)?$/.test(host) || (parsedUrl.getPort() !== undefined && PathStylePorts.includes(parsedUrl.getPort()))); } /** @@ -31755,7 +29907,7 @@ class StorageSharedKeyCredential extends Credential { * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ const packageName = "azure-storage-blob"; -const packageVersion = "12.15.0"; +const packageVersion = "12.17.0"; class StorageClientContext extends coreHttp__namespace.ServiceClient { /** * Initializes a new instance of the StorageClientContext class. @@ -31781,7 +29933,7 @@ class StorageClientContext extends coreHttp__namespace.ServiceClient { // Parameter assignments this.url = url; // Assigning values to Constant parameters - this.version = options.version || "2023-01-03"; + this.version = options.version || "2023-11-03"; } } @@ -34962,6 +33114,9 @@ exports.StorageBlobAudience = void 0; */ StorageBlobAudience["DiskComputeOAuthScopes"] = "https://disk.compute.azure.com/.default"; })(exports.StorageBlobAudience || (exports.StorageBlobAudience = {})); +function getBlobServiceAccountAudience(storageAccountName) { + return `https://${storageAccountName}.blob.core.windows.net/.default`; +} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -41672,6 +39827,7 @@ exports.StorageSharedKeyCredential = StorageSharedKeyCredential; exports.StorageSharedKeyCredentialPolicy = StorageSharedKeyCredentialPolicy; exports.generateAccountSASQueryParameters = generateAccountSASQueryParameters; exports.generateBlobSASQueryParameters = generateBlobSASQueryParameters; +exports.getBlobServiceAccountAudience = getBlobServiceAccountAudience; exports.isPipelineLike = isPipelineLike; exports.logger = logger; exports.newPipeline = newPipeline; @@ -41680,7 +39836,7 @@ exports.newPipeline = newPipeline; /***/ }), -/***/ 15234: +/***/ 40334: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -41743,7 +39899,7 @@ exports.createTokenAuth = createTokenAuth; /***/ }), -/***/ 34266: +/***/ 76762: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -41751,11 +39907,11 @@ exports.createTokenAuth = createTokenAuth; Object.defineProperty(exports, "__esModule", ({ value: true })); -var universalUserAgent = __nccwpck_require__(68636); -var beforeAfterHook = __nccwpck_require__(18079); -var request = __nccwpck_require__(40857); -var graphql = __nccwpck_require__(51977); -var authToken = __nccwpck_require__(15234); +var universalUserAgent = __nccwpck_require__(45030); +var beforeAfterHook = __nccwpck_require__(83682); +var request = __nccwpck_require__(36234); +var graphql = __nccwpck_require__(88467); +var authToken = __nccwpck_require__(40334); function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; @@ -41927,7 +40083,7 @@ exports.Octokit = Octokit; /***/ }), -/***/ 28124: +/***/ 59440: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -41935,8 +40091,8 @@ exports.Octokit = Octokit; Object.defineProperty(exports, "__esModule", ({ value: true })); -var isPlainObject = __nccwpck_require__(54132); -var universalUserAgent = __nccwpck_require__(68636); +var isPlainObject = __nccwpck_require__(63287); +var universalUserAgent = __nccwpck_require__(45030); function lowercaseKeys(object) { if (!object) { @@ -42325,7 +40481,7 @@ exports.endpoint = endpoint; /***/ }), -/***/ 51977: +/***/ 88467: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -42333,8 +40489,8 @@ exports.endpoint = endpoint; Object.defineProperty(exports, "__esModule", ({ value: true })); -var request = __nccwpck_require__(40857); -var universalUserAgent = __nccwpck_require__(68636); +var request = __nccwpck_require__(36234); +var universalUserAgent = __nccwpck_require__(45030); const VERSION = "4.8.0"; @@ -42451,7 +40607,7 @@ exports.withCustomRequest = withCustomRequest; /***/ }), -/***/ 60345: +/***/ 64193: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -42664,7 +40820,7 @@ exports.paginatingEndpoints = paginatingEndpoints; /***/ }), -/***/ 73665: +/***/ 68883: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -42702,7 +40858,7 @@ exports.requestLog = requestLog; /***/ }), -/***/ 68590: +/***/ 83044: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -43817,7 +41973,7 @@ exports.restEndpointMethods = restEndpointMethods; /***/ }), -/***/ 69980: +/***/ 86298: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -43827,7 +41983,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -var Bottleneck = _interopDefault(__nccwpck_require__(90058)); +var Bottleneck = _interopDefault(__nccwpck_require__(11174)); // @ts-ignore async function errorRequest(octokit, state, error, options) { @@ -43901,7 +42057,7 @@ exports.retry = retry; /***/ }), -/***/ 40857: +/***/ 36234: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -43911,11 +42067,11 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -var endpoint = __nccwpck_require__(28124); -var universalUserAgent = __nccwpck_require__(68636); -var isPlainObject = __nccwpck_require__(54132); -var nodeFetch = _interopDefault(__nccwpck_require__(96295)); -var requestError = __nccwpck_require__(37656); +var endpoint = __nccwpck_require__(59440); +var universalUserAgent = __nccwpck_require__(45030); +var isPlainObject = __nccwpck_require__(63287); +var nodeFetch = _interopDefault(__nccwpck_require__(80467)); +var requestError = __nccwpck_require__(30013); const VERSION = "5.6.3"; @@ -44086,7 +42242,7 @@ exports.request = request; /***/ }), -/***/ 37656: +/***/ 30013: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -44096,8 +42252,8 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -var deprecation = __nccwpck_require__(24107); -var once = _interopDefault(__nccwpck_require__(58203)); +var deprecation = __nccwpck_require__(58932); +var once = _interopDefault(__nccwpck_require__(1223)); const logOnceCode = once(deprecation => console.warn(deprecation)); const logOnceHeaders = once(deprecation => console.warn(deprecation)); @@ -44168,7 +42324,7 @@ exports.RequestError = RequestError; /***/ }), -/***/ 14593: +/***/ 57171: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -44190,9 +42346,9 @@ exports.RequestError = RequestError; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ContextAPI = void 0; -const NoopContextManager_1 = __nccwpck_require__(18571); -const global_utils_1 = __nccwpck_require__(87638); -const diag_1 = __nccwpck_require__(71411); +const NoopContextManager_1 = __nccwpck_require__(54118); +const global_utils_1 = __nccwpck_require__(85135); +const diag_1 = __nccwpck_require__(11877); const API_NAME = 'context'; const NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager(); /** @@ -44256,7 +42412,7 @@ exports.ContextAPI = ContextAPI; /***/ }), -/***/ 71411: +/***/ 11877: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -44278,10 +42434,10 @@ exports.ContextAPI = ContextAPI; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DiagAPI = void 0; -const ComponentLogger_1 = __nccwpck_require__(84394); -const logLevelLogger_1 = __nccwpck_require__(89327); -const types_1 = __nccwpck_require__(39184); -const global_utils_1 = __nccwpck_require__(87638); +const ComponentLogger_1 = __nccwpck_require__(17978); +const logLevelLogger_1 = __nccwpck_require__(99639); +const types_1 = __nccwpck_require__(78077); +const global_utils_1 = __nccwpck_require__(85135); const API_NAME = 'diag'; /** * Singleton object which represents the entry point to the OpenTelemetry internal @@ -44356,7 +42512,7 @@ exports.DiagAPI = DiagAPI; /***/ }), -/***/ 43376: +/***/ 17696: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -44378,9 +42534,9 @@ exports.DiagAPI = DiagAPI; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MetricsAPI = void 0; -const NoopMeterProvider_1 = __nccwpck_require__(9976); -const global_utils_1 = __nccwpck_require__(87638); -const diag_1 = __nccwpck_require__(71411); +const NoopMeterProvider_1 = __nccwpck_require__(72647); +const global_utils_1 = __nccwpck_require__(85135); +const diag_1 = __nccwpck_require__(11877); const API_NAME = 'metrics'; /** * Singleton object which represents the entry point to the OpenTelemetry Metrics API @@ -44424,7 +42580,7 @@ exports.MetricsAPI = MetricsAPI; /***/ }), -/***/ 47827: +/***/ 89909: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -44446,12 +42602,12 @@ exports.MetricsAPI = MetricsAPI; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PropagationAPI = void 0; -const global_utils_1 = __nccwpck_require__(87638); -const NoopTextMapPropagator_1 = __nccwpck_require__(78807); -const TextMapPropagator_1 = __nccwpck_require__(75642); -const context_helpers_1 = __nccwpck_require__(380); -const utils_1 = __nccwpck_require__(97346); -const diag_1 = __nccwpck_require__(71411); +const global_utils_1 = __nccwpck_require__(85135); +const NoopTextMapPropagator_1 = __nccwpck_require__(72368); +const TextMapPropagator_1 = __nccwpck_require__(80865); +const context_helpers_1 = __nccwpck_require__(37682); +const utils_1 = __nccwpck_require__(28136); +const diag_1 = __nccwpck_require__(11877); const API_NAME = 'propagation'; const NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator(); /** @@ -44520,7 +42676,7 @@ exports.PropagationAPI = PropagationAPI; /***/ }), -/***/ 93743: +/***/ 81539: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -44542,11 +42698,11 @@ exports.PropagationAPI = PropagationAPI; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TraceAPI = void 0; -const global_utils_1 = __nccwpck_require__(87638); -const ProxyTracerProvider_1 = __nccwpck_require__(50344); -const spancontext_utils_1 = __nccwpck_require__(62966); -const context_utils_1 = __nccwpck_require__(4054); -const diag_1 = __nccwpck_require__(71411); +const global_utils_1 = __nccwpck_require__(85135); +const ProxyTracerProvider_1 = __nccwpck_require__(2285); +const spancontext_utils_1 = __nccwpck_require__(49745); +const context_utils_1 = __nccwpck_require__(23326); +const diag_1 = __nccwpck_require__(11877); const API_NAME = 'trace'; /** * Singleton object which represents the entry point to the OpenTelemetry Tracing API @@ -44606,7 +42762,7 @@ exports.TraceAPI = TraceAPI; /***/ }), -/***/ 380: +/***/ 37682: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -44628,8 +42784,8 @@ exports.TraceAPI = TraceAPI; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.deleteBaggage = exports.setBaggage = exports.getActiveBaggage = exports.getBaggage = void 0; -const context_1 = __nccwpck_require__(14593); -const context_2 = __nccwpck_require__(85316); +const context_1 = __nccwpck_require__(57171); +const context_2 = __nccwpck_require__(78242); /** * Baggage key */ @@ -44676,7 +42832,7 @@ exports.deleteBaggage = deleteBaggage; /***/ }), -/***/ 27061: +/***/ 84811: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -44738,7 +42894,7 @@ exports.BaggageImpl = BaggageImpl; /***/ }), -/***/ 17248: +/***/ 23542: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -44768,7 +42924,7 @@ exports.baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata'); /***/ }), -/***/ 97346: +/***/ 28136: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -44790,9 +42946,9 @@ exports.baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata'); */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.baggageEntryMetadataFromString = exports.createBaggage = void 0; -const diag_1 = __nccwpck_require__(71411); -const baggage_impl_1 = __nccwpck_require__(27061); -const symbol_1 = __nccwpck_require__(17248); +const diag_1 = __nccwpck_require__(11877); +const baggage_impl_1 = __nccwpck_require__(84811); +const symbol_1 = __nccwpck_require__(23542); const diag = diag_1.DiagAPI.instance(); /** * Create a new Baggage with optional entries @@ -44826,7 +42982,7 @@ exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString; /***/ }), -/***/ 34382: +/***/ 7393: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -44850,14 +43006,14 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.context = void 0; // Split module-level variable definition into separate files to allow // tree-shaking on each api instance. -const context_1 = __nccwpck_require__(14593); +const context_1 = __nccwpck_require__(57171); /** Entrypoint for context API */ exports.context = context_1.ContextAPI.getInstance(); //# sourceMappingURL=context-api.js.map /***/ }), -/***/ 18571: +/***/ 54118: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -44879,7 +43035,7 @@ exports.context = context_1.ContextAPI.getInstance(); */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopContextManager = void 0; -const context_1 = __nccwpck_require__(85316); +const context_1 = __nccwpck_require__(78242); class NoopContextManager { active() { return context_1.ROOT_CONTEXT; @@ -44902,7 +43058,7 @@ exports.NoopContextManager = NoopContextManager; /***/ }), -/***/ 85316: +/***/ 78242: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -44964,7 +43120,7 @@ exports.ROOT_CONTEXT = new BaseContext(); /***/ }), -/***/ 9586: +/***/ 39721: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -44988,7 +43144,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.diag = void 0; // Split module-level variable definition into separate files to allow // tree-shaking on each api instance. -const diag_1 = __nccwpck_require__(71411); +const diag_1 = __nccwpck_require__(11877); /** * Entrypoint for Diag API. * Defines Diagnostic handler used for internal diagnostic logging operations. @@ -45000,7 +43156,7 @@ exports.diag = diag_1.DiagAPI.instance(); /***/ }), -/***/ 84394: +/***/ 17978: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -45022,7 +43178,7 @@ exports.diag = diag_1.DiagAPI.instance(); */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DiagComponentLogger = void 0; -const global_utils_1 = __nccwpck_require__(87638); +const global_utils_1 = __nccwpck_require__(85135); /** * Component Logger which is meant to be used as part of any component which * will add automatically additional namespace in front of the log message. @@ -45066,7 +43222,7 @@ function logProxy(funcName, namespace, args) { /***/ }), -/***/ 12048: +/***/ 3041: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -45130,7 +43286,7 @@ exports.DiagConsoleLogger = DiagConsoleLogger; /***/ }), -/***/ 89327: +/***/ 99639: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -45152,7 +43308,7 @@ exports.DiagConsoleLogger = DiagConsoleLogger; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createLogLevelDiagLogger = void 0; -const types_1 = __nccwpck_require__(39184); +const types_1 = __nccwpck_require__(78077); function createLogLevelDiagLogger(maxLevel, logger) { if (maxLevel < types_1.DiagLogLevel.NONE) { maxLevel = types_1.DiagLogLevel.NONE; @@ -45182,7 +43338,7 @@ exports.createLogLevelDiagLogger = createLogLevelDiagLogger; /***/ }), -/***/ 39184: +/***/ 78077: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -45233,7 +43389,7 @@ var DiagLogLevel; /***/ }), -/***/ 27742: +/***/ 65163: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -45255,59 +43411,59 @@ var DiagLogLevel; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.trace = exports.propagation = exports.metrics = exports.diag = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.createTraceState = exports.TraceFlags = exports.SpanStatusCode = exports.SpanKind = exports.SamplingDecision = exports.ProxyTracerProvider = exports.ProxyTracer = exports.defaultTextMapSetter = exports.defaultTextMapGetter = exports.ValueType = exports.createNoopMeter = exports.DiagLogLevel = exports.DiagConsoleLogger = exports.ROOT_CONTEXT = exports.createContextKey = exports.baggageEntryMetadataFromString = void 0; -var utils_1 = __nccwpck_require__(97346); +var utils_1 = __nccwpck_require__(28136); Object.defineProperty(exports, "baggageEntryMetadataFromString", ({ enumerable: true, get: function () { return utils_1.baggageEntryMetadataFromString; } })); // Context APIs -var context_1 = __nccwpck_require__(85316); +var context_1 = __nccwpck_require__(78242); Object.defineProperty(exports, "createContextKey", ({ enumerable: true, get: function () { return context_1.createContextKey; } })); Object.defineProperty(exports, "ROOT_CONTEXT", ({ enumerable: true, get: function () { return context_1.ROOT_CONTEXT; } })); // Diag APIs -var consoleLogger_1 = __nccwpck_require__(12048); +var consoleLogger_1 = __nccwpck_require__(3041); Object.defineProperty(exports, "DiagConsoleLogger", ({ enumerable: true, get: function () { return consoleLogger_1.DiagConsoleLogger; } })); -var types_1 = __nccwpck_require__(39184); +var types_1 = __nccwpck_require__(78077); Object.defineProperty(exports, "DiagLogLevel", ({ enumerable: true, get: function () { return types_1.DiagLogLevel; } })); // Metrics APIs -var NoopMeter_1 = __nccwpck_require__(99535); +var NoopMeter_1 = __nccwpck_require__(4837); Object.defineProperty(exports, "createNoopMeter", ({ enumerable: true, get: function () { return NoopMeter_1.createNoopMeter; } })); -var Metric_1 = __nccwpck_require__(42414); +var Metric_1 = __nccwpck_require__(89999); Object.defineProperty(exports, "ValueType", ({ enumerable: true, get: function () { return Metric_1.ValueType; } })); // Propagation APIs -var TextMapPropagator_1 = __nccwpck_require__(75642); +var TextMapPropagator_1 = __nccwpck_require__(80865); Object.defineProperty(exports, "defaultTextMapGetter", ({ enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapGetter; } })); Object.defineProperty(exports, "defaultTextMapSetter", ({ enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapSetter; } })); -var ProxyTracer_1 = __nccwpck_require__(61360); +var ProxyTracer_1 = __nccwpck_require__(43503); Object.defineProperty(exports, "ProxyTracer", ({ enumerable: true, get: function () { return ProxyTracer_1.ProxyTracer; } })); -var ProxyTracerProvider_1 = __nccwpck_require__(50344); +var ProxyTracerProvider_1 = __nccwpck_require__(2285); Object.defineProperty(exports, "ProxyTracerProvider", ({ enumerable: true, get: function () { return ProxyTracerProvider_1.ProxyTracerProvider; } })); -var SamplingResult_1 = __nccwpck_require__(62026); +var SamplingResult_1 = __nccwpck_require__(33209); Object.defineProperty(exports, "SamplingDecision", ({ enumerable: true, get: function () { return SamplingResult_1.SamplingDecision; } })); -var span_kind_1 = __nccwpck_require__(32970); +var span_kind_1 = __nccwpck_require__(31424); Object.defineProperty(exports, "SpanKind", ({ enumerable: true, get: function () { return span_kind_1.SpanKind; } })); -var status_1 = __nccwpck_require__(65398); +var status_1 = __nccwpck_require__(48845); Object.defineProperty(exports, "SpanStatusCode", ({ enumerable: true, get: function () { return status_1.SpanStatusCode; } })); -var trace_flags_1 = __nccwpck_require__(96643); +var trace_flags_1 = __nccwpck_require__(26905); Object.defineProperty(exports, "TraceFlags", ({ enumerable: true, get: function () { return trace_flags_1.TraceFlags; } })); -var utils_2 = __nccwpck_require__(85649); +var utils_2 = __nccwpck_require__(32615); Object.defineProperty(exports, "createTraceState", ({ enumerable: true, get: function () { return utils_2.createTraceState; } })); -var spancontext_utils_1 = __nccwpck_require__(62966); +var spancontext_utils_1 = __nccwpck_require__(49745); Object.defineProperty(exports, "isSpanContextValid", ({ enumerable: true, get: function () { return spancontext_utils_1.isSpanContextValid; } })); Object.defineProperty(exports, "isValidTraceId", ({ enumerable: true, get: function () { return spancontext_utils_1.isValidTraceId; } })); Object.defineProperty(exports, "isValidSpanId", ({ enumerable: true, get: function () { return spancontext_utils_1.isValidSpanId; } })); -var invalid_span_constants_1 = __nccwpck_require__(29985); +var invalid_span_constants_1 = __nccwpck_require__(91760); Object.defineProperty(exports, "INVALID_SPANID", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPANID; } })); Object.defineProperty(exports, "INVALID_TRACEID", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_TRACEID; } })); Object.defineProperty(exports, "INVALID_SPAN_CONTEXT", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPAN_CONTEXT; } })); // Split module-level variable definition into separate files to allow // tree-shaking on each api instance. -const context_api_1 = __nccwpck_require__(34382); +const context_api_1 = __nccwpck_require__(7393); Object.defineProperty(exports, "context", ({ enumerable: true, get: function () { return context_api_1.context; } })); -const diag_api_1 = __nccwpck_require__(9586); +const diag_api_1 = __nccwpck_require__(39721); Object.defineProperty(exports, "diag", ({ enumerable: true, get: function () { return diag_api_1.diag; } })); -const metrics_api_1 = __nccwpck_require__(59837); +const metrics_api_1 = __nccwpck_require__(72601); Object.defineProperty(exports, "metrics", ({ enumerable: true, get: function () { return metrics_api_1.metrics; } })); -const propagation_api_1 = __nccwpck_require__(97338); +const propagation_api_1 = __nccwpck_require__(17591); Object.defineProperty(exports, "propagation", ({ enumerable: true, get: function () { return propagation_api_1.propagation; } })); -const trace_api_1 = __nccwpck_require__(18388); +const trace_api_1 = __nccwpck_require__(98989); Object.defineProperty(exports, "trace", ({ enumerable: true, get: function () { return trace_api_1.trace; } })); // Default export. exports["default"] = { @@ -45321,7 +43477,7 @@ exports["default"] = { /***/ }), -/***/ 87638: +/***/ 85135: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -45343,9 +43499,9 @@ exports["default"] = { */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.unregisterGlobal = exports.getGlobal = exports.registerGlobal = void 0; -const platform_1 = __nccwpck_require__(55477); -const version_1 = __nccwpck_require__(93341); -const semver_1 = __nccwpck_require__(62720); +const platform_1 = __nccwpck_require__(99957); +const version_1 = __nccwpck_require__(98996); +const semver_1 = __nccwpck_require__(81522); const major = version_1.VERSION.split('.')[0]; const GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`); const _global = platform_1._globalThis; @@ -45392,7 +43548,7 @@ exports.unregisterGlobal = unregisterGlobal; /***/ }), -/***/ 62720: +/***/ 81522: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -45414,7 +43570,7 @@ exports.unregisterGlobal = unregisterGlobal; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isCompatible = exports._makeCompatibilityCheck = void 0; -const version_1 = __nccwpck_require__(93341); +const version_1 = __nccwpck_require__(98996); const re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; /** * Create a function to test an API version to see if it is compatible with the provided ownVersion. @@ -45521,7 +43677,7 @@ exports.isCompatible = _makeCompatibilityCheck(version_1.VERSION); /***/ }), -/***/ 59837: +/***/ 72601: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -45545,14 +43701,14 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.metrics = void 0; // Split module-level variable definition into separate files to allow // tree-shaking on each api instance. -const metrics_1 = __nccwpck_require__(43376); +const metrics_1 = __nccwpck_require__(17696); /** Entrypoint for metrics API */ exports.metrics = metrics_1.MetricsAPI.getInstance(); //# sourceMappingURL=metrics-api.js.map /***/ }), -/***/ 42414: +/***/ 89999: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -45584,7 +43740,7 @@ var ValueType; /***/ }), -/***/ 99535: +/***/ 4837: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -45707,7 +43863,7 @@ exports.createNoopMeter = createNoopMeter; /***/ }), -/***/ 9976: +/***/ 72647: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -45729,7 +43885,7 @@ exports.createNoopMeter = createNoopMeter; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NOOP_METER_PROVIDER = exports.NoopMeterProvider = void 0; -const NoopMeter_1 = __nccwpck_require__(99535); +const NoopMeter_1 = __nccwpck_require__(4837); /** * An implementation of the {@link MeterProvider} which returns an impotent Meter * for all calls to `getMeter` @@ -45745,7 +43901,7 @@ exports.NOOP_METER_PROVIDER = new NoopMeterProvider(); /***/ }), -/***/ 55477: +/***/ 99957: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -45776,12 +43932,12 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -__exportStar(__nccwpck_require__(31791), exports); +__exportStar(__nccwpck_require__(87200), exports); //# sourceMappingURL=index.js.map /***/ }), -/***/ 83450: +/***/ 89406: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -45810,7 +43966,7 @@ exports._globalThis = typeof globalThis === 'object' ? globalThis : global; /***/ }), -/***/ 31791: +/***/ 87200: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -45841,12 +43997,12 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -__exportStar(__nccwpck_require__(83450), exports); +__exportStar(__nccwpck_require__(89406), exports); //# sourceMappingURL=index.js.map /***/ }), -/***/ 97338: +/***/ 17591: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -45870,14 +44026,14 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.propagation = void 0; // Split module-level variable definition into separate files to allow // tree-shaking on each api instance. -const propagation_1 = __nccwpck_require__(47827); +const propagation_1 = __nccwpck_require__(89909); /** Entrypoint for propagation API */ exports.propagation = propagation_1.PropagationAPI.getInstance(); //# sourceMappingURL=propagation-api.js.map /***/ }), -/***/ 78807: +/***/ 72368: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -45918,7 +44074,7 @@ exports.NoopTextMapPropagator = NoopTextMapPropagator; /***/ }), -/***/ 75642: +/***/ 80865: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -45966,7 +44122,7 @@ exports.defaultTextMapSetter = { /***/ }), -/***/ 18388: +/***/ 98989: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -45990,14 +44146,14 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.trace = void 0; // Split module-level variable definition into separate files to allow // tree-shaking on each api instance. -const trace_1 = __nccwpck_require__(93743); +const trace_1 = __nccwpck_require__(81539); /** Entrypoint for trace API */ exports.trace = trace_1.TraceAPI.getInstance(); //# sourceMappingURL=trace-api.js.map /***/ }), -/***/ 26644: +/***/ 81462: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -46019,7 +44175,7 @@ exports.trace = trace_1.TraceAPI.getInstance(); */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NonRecordingSpan = void 0; -const invalid_span_constants_1 = __nccwpck_require__(29985); +const invalid_span_constants_1 = __nccwpck_require__(91760); /** * The NonRecordingSpan is the default {@link Span} that is used when no Span * implementation is available. All operations are no-op including context @@ -46067,7 +44223,7 @@ exports.NonRecordingSpan = NonRecordingSpan; /***/ }), -/***/ 10555: +/***/ 17606: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -46089,10 +44245,10 @@ exports.NonRecordingSpan = NonRecordingSpan; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopTracer = void 0; -const context_1 = __nccwpck_require__(14593); -const context_utils_1 = __nccwpck_require__(4054); -const NonRecordingSpan_1 = __nccwpck_require__(26644); -const spancontext_utils_1 = __nccwpck_require__(62966); +const context_1 = __nccwpck_require__(57171); +const context_utils_1 = __nccwpck_require__(23326); +const NonRecordingSpan_1 = __nccwpck_require__(81462); +const spancontext_utils_1 = __nccwpck_require__(49745); const contextApi = context_1.ContextAPI.getInstance(); /** * No-op implementations of {@link Tracer}. @@ -46149,7 +44305,7 @@ function isSpanContext(spanContext) { /***/ }), -/***/ 71498: +/***/ 23259: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -46171,7 +44327,7 @@ function isSpanContext(spanContext) { */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopTracerProvider = void 0; -const NoopTracer_1 = __nccwpck_require__(10555); +const NoopTracer_1 = __nccwpck_require__(17606); /** * An implementation of the {@link TracerProvider} which returns an impotent * Tracer for all calls to `getTracer`. @@ -46188,7 +44344,7 @@ exports.NoopTracerProvider = NoopTracerProvider; /***/ }), -/***/ 61360: +/***/ 43503: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -46210,7 +44366,7 @@ exports.NoopTracerProvider = NoopTracerProvider; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProxyTracer = void 0; -const NoopTracer_1 = __nccwpck_require__(10555); +const NoopTracer_1 = __nccwpck_require__(17606); const NOOP_TRACER = new NoopTracer_1.NoopTracer(); /** * Proxy tracer provided by the proxy tracer provider @@ -46250,7 +44406,7 @@ exports.ProxyTracer = ProxyTracer; /***/ }), -/***/ 50344: +/***/ 2285: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -46272,8 +44428,8 @@ exports.ProxyTracer = ProxyTracer; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProxyTracerProvider = void 0; -const ProxyTracer_1 = __nccwpck_require__(61360); -const NoopTracerProvider_1 = __nccwpck_require__(71498); +const ProxyTracer_1 = __nccwpck_require__(43503); +const NoopTracerProvider_1 = __nccwpck_require__(23259); const NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider(); /** * Tracer provider which provides {@link ProxyTracer}s. @@ -46311,7 +44467,7 @@ exports.ProxyTracerProvider = ProxyTracerProvider; /***/ }), -/***/ 62026: +/***/ 33209: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -46360,7 +44516,7 @@ var SamplingDecision; /***/ }), -/***/ 4054: +/***/ 23326: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -46382,9 +44538,9 @@ var SamplingDecision; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getActiveSpan = exports.getSpan = void 0; -const context_1 = __nccwpck_require__(85316); -const NonRecordingSpan_1 = __nccwpck_require__(26644); -const context_2 = __nccwpck_require__(14593); +const context_1 = __nccwpck_require__(78242); +const NonRecordingSpan_1 = __nccwpck_require__(81462); +const context_2 = __nccwpck_require__(57171); /** * span key */ @@ -46449,7 +44605,7 @@ exports.getSpanContext = getSpanContext; /***/ }), -/***/ 90453: +/***/ 62110: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -46471,7 +44627,7 @@ exports.getSpanContext = getSpanContext; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TraceStateImpl = void 0; -const tracestate_validators_1 = __nccwpck_require__(45603); +const tracestate_validators_1 = __nccwpck_require__(54864); const MAX_TRACE_STATE_ITEMS = 32; const MAX_TRACE_STATE_LEN = 512; const LIST_MEMBERS_SEPARATOR = ','; @@ -46559,7 +44715,7 @@ exports.TraceStateImpl = TraceStateImpl; /***/ }), -/***/ 45603: +/***/ 54864: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -46612,7 +44768,7 @@ exports.validateValue = validateValue; /***/ }), -/***/ 85649: +/***/ 32615: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -46634,7 +44790,7 @@ exports.validateValue = validateValue; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createTraceState = void 0; -const tracestate_impl_1 = __nccwpck_require__(90453); +const tracestate_impl_1 = __nccwpck_require__(62110); function createTraceState(rawTraceState) { return new tracestate_impl_1.TraceStateImpl(rawTraceState); } @@ -46643,7 +44799,7 @@ exports.createTraceState = createTraceState; /***/ }), -/***/ 29985: +/***/ 91760: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -46665,7 +44821,7 @@ exports.createTraceState = createTraceState; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0; -const trace_flags_1 = __nccwpck_require__(96643); +const trace_flags_1 = __nccwpck_require__(26905); exports.INVALID_SPANID = '0000000000000000'; exports.INVALID_TRACEID = '00000000000000000000000000000000'; exports.INVALID_SPAN_CONTEXT = { @@ -46677,7 +44833,7 @@ exports.INVALID_SPAN_CONTEXT = { /***/ }), -/***/ 32970: +/***/ 31424: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -46730,7 +44886,7 @@ var SpanKind; /***/ }), -/***/ 62966: +/***/ 49745: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -46752,8 +44908,8 @@ exports.wrapSpanContext = exports.isSpanContextValid = exports.isValidSpanId = e * See the License for the specific language governing permissions and * limitations under the License. */ -const invalid_span_constants_1 = __nccwpck_require__(29985); -const NonRecordingSpan_1 = __nccwpck_require__(26644); +const invalid_span_constants_1 = __nccwpck_require__(91760); +const NonRecordingSpan_1 = __nccwpck_require__(81462); const VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; const VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; function isValidTraceId(traceId) { @@ -46786,7 +44942,7 @@ exports.wrapSpanContext = wrapSpanContext; /***/ }), -/***/ 65398: +/***/ 48845: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -46816,7 +44972,7 @@ var SpanStatusCode; /***/ }), -/***/ 96643: +/***/ 26905: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -46849,7 +45005,7 @@ var TraceFlags; /***/ }), -/***/ 93341: +/***/ 98996: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -46872,12 +45028,12 @@ var TraceFlags; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.VERSION = void 0; // this is autogenerated file, see scripts/version-update.js -exports.VERSION = '1.4.1'; +exports.VERSION = '1.7.0'; //# sourceMappingURL=version.js.map /***/ }), -/***/ 13694: +/***/ 29912: /***/ (function(__unused_webpack_module, exports) { "use strict"; @@ -46935,7 +45091,7 @@ exports.ClientStreamingCall = ClientStreamingCall; /***/ }), -/***/ 52669: +/***/ 85702: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -47029,7 +45185,7 @@ exports.Deferred = Deferred; /***/ }), -/***/ 89835: +/***/ 17042: /***/ (function(__unused_webpack_module, exports) { "use strict"; @@ -47086,7 +45242,7 @@ exports.DuplexStreamingCall = DuplexStreamingCall; /***/ }), -/***/ 81745: +/***/ 60012: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -47095,51 +45251,51 @@ exports.DuplexStreamingCall = DuplexStreamingCall; // Note: we do not use `export * from ...` to help tree shakers, // webpack verbose output hints that this should be useful Object.defineProperty(exports, "__esModule", ({ value: true })); -var service_type_1 = __nccwpck_require__(89999); +var service_type_1 = __nccwpck_require__(14107); Object.defineProperty(exports, "ServiceType", ({ enumerable: true, get: function () { return service_type_1.ServiceType; } })); -var reflection_info_1 = __nccwpck_require__(83044); +var reflection_info_1 = __nccwpck_require__(44331); Object.defineProperty(exports, "readMethodOptions", ({ enumerable: true, get: function () { return reflection_info_1.readMethodOptions; } })); Object.defineProperty(exports, "readMethodOption", ({ enumerable: true, get: function () { return reflection_info_1.readMethodOption; } })); Object.defineProperty(exports, "readServiceOption", ({ enumerable: true, get: function () { return reflection_info_1.readServiceOption; } })); -var rpc_error_1 = __nccwpck_require__(73341); +var rpc_error_1 = __nccwpck_require__(63159); Object.defineProperty(exports, "RpcError", ({ enumerable: true, get: function () { return rpc_error_1.RpcError; } })); -var rpc_options_1 = __nccwpck_require__(26452); +var rpc_options_1 = __nccwpck_require__(67386); Object.defineProperty(exports, "mergeRpcOptions", ({ enumerable: true, get: function () { return rpc_options_1.mergeRpcOptions; } })); -var rpc_output_stream_1 = __nccwpck_require__(19221); +var rpc_output_stream_1 = __nccwpck_require__(76637); Object.defineProperty(exports, "RpcOutputStreamController", ({ enumerable: true, get: function () { return rpc_output_stream_1.RpcOutputStreamController; } })); -var test_transport_1 = __nccwpck_require__(89403); +var test_transport_1 = __nccwpck_require__(87008); Object.defineProperty(exports, "TestTransport", ({ enumerable: true, get: function () { return test_transport_1.TestTransport; } })); -var deferred_1 = __nccwpck_require__(52669); +var deferred_1 = __nccwpck_require__(85702); Object.defineProperty(exports, "Deferred", ({ enumerable: true, get: function () { return deferred_1.Deferred; } })); Object.defineProperty(exports, "DeferredState", ({ enumerable: true, get: function () { return deferred_1.DeferredState; } })); -var duplex_streaming_call_1 = __nccwpck_require__(89835); +var duplex_streaming_call_1 = __nccwpck_require__(17042); Object.defineProperty(exports, "DuplexStreamingCall", ({ enumerable: true, get: function () { return duplex_streaming_call_1.DuplexStreamingCall; } })); -var client_streaming_call_1 = __nccwpck_require__(13694); +var client_streaming_call_1 = __nccwpck_require__(29912); Object.defineProperty(exports, "ClientStreamingCall", ({ enumerable: true, get: function () { return client_streaming_call_1.ClientStreamingCall; } })); -var server_streaming_call_1 = __nccwpck_require__(37387); +var server_streaming_call_1 = __nccwpck_require__(30066); Object.defineProperty(exports, "ServerStreamingCall", ({ enumerable: true, get: function () { return server_streaming_call_1.ServerStreamingCall; } })); -var unary_call_1 = __nccwpck_require__(77727); +var unary_call_1 = __nccwpck_require__(84175); Object.defineProperty(exports, "UnaryCall", ({ enumerable: true, get: function () { return unary_call_1.UnaryCall; } })); -var rpc_interceptor_1 = __nccwpck_require__(61513); +var rpc_interceptor_1 = __nccwpck_require__(51680); Object.defineProperty(exports, "stackIntercept", ({ enumerable: true, get: function () { return rpc_interceptor_1.stackIntercept; } })); Object.defineProperty(exports, "stackDuplexStreamingInterceptors", ({ enumerable: true, get: function () { return rpc_interceptor_1.stackDuplexStreamingInterceptors; } })); Object.defineProperty(exports, "stackClientStreamingInterceptors", ({ enumerable: true, get: function () { return rpc_interceptor_1.stackClientStreamingInterceptors; } })); Object.defineProperty(exports, "stackServerStreamingInterceptors", ({ enumerable: true, get: function () { return rpc_interceptor_1.stackServerStreamingInterceptors; } })); Object.defineProperty(exports, "stackUnaryInterceptors", ({ enumerable: true, get: function () { return rpc_interceptor_1.stackUnaryInterceptors; } })); -var server_call_context_1 = __nccwpck_require__(41449); +var server_call_context_1 = __nccwpck_require__(25320); Object.defineProperty(exports, "ServerCallContextController", ({ enumerable: true, get: function () { return server_call_context_1.ServerCallContextController; } })); /***/ }), -/***/ 83044: +/***/ 44331: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.readServiceOption = exports.readMethodOption = exports.readMethodOptions = exports.normalizeMethodInfo = void 0; -const runtime_1 = __nccwpck_require__(90076); +const runtime_1 = __nccwpck_require__(4061); /** * Turns PartialMethodInfo into MethodInfo. */ @@ -47197,7 +45353,7 @@ exports.readServiceOption = readServiceOption; /***/ }), -/***/ 73341: +/***/ 63159: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -47241,14 +45397,14 @@ exports.RpcError = RpcError; /***/ }), -/***/ 61513: +/***/ 51680: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.stackDuplexStreamingInterceptors = exports.stackClientStreamingInterceptors = exports.stackServerStreamingInterceptors = exports.stackUnaryInterceptors = exports.stackIntercept = void 0; -const runtime_1 = __nccwpck_require__(90076); +const runtime_1 = __nccwpck_require__(4061); /** * Creates a "stack" of of all interceptors specified in the given `RpcOptions`. * Used by generated client implementations. @@ -47323,14 +45479,14 @@ exports.stackDuplexStreamingInterceptors = stackDuplexStreamingInterceptors; /***/ }), -/***/ 26452: +/***/ 67386: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.mergeRpcOptions = void 0; -const runtime_1 = __nccwpck_require__(90076); +const runtime_1 = __nccwpck_require__(4061); /** * Merges custom RPC options with defaults. Returns a new instance and keeps * the "defaults" and the "options" unmodified. @@ -47397,15 +45553,15 @@ function copy(a, into) { /***/ }), -/***/ 19221: +/***/ 76637: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.RpcOutputStreamController = void 0; -const deferred_1 = __nccwpck_require__(52669); -const runtime_1 = __nccwpck_require__(90076); +const deferred_1 = __nccwpck_require__(85702); +const runtime_1 = __nccwpck_require__(4061); /** * A `RpcOutputStream` that you control. */ @@ -47577,7 +45733,7 @@ exports.RpcOutputStreamController = RpcOutputStreamController; /***/ }), -/***/ 41449: +/***/ 25320: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -47645,7 +45801,7 @@ exports.ServerCallContextController = ServerCallContextController; /***/ }), -/***/ 37387: +/***/ 30066: /***/ (function(__unused_webpack_module, exports) { "use strict"; @@ -47703,14 +45859,14 @@ exports.ServerStreamingCall = ServerStreamingCall; /***/ }), -/***/ 89999: +/***/ 14107: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ServiceType = void 0; -const reflection_info_1 = __nccwpck_require__(83044); +const reflection_info_1 = __nccwpck_require__(44331); class ServiceType { constructor(typeName, methods, options) { this.typeName = typeName; @@ -47723,7 +45879,7 @@ exports.ServiceType = ServiceType; /***/ }), -/***/ 89403: +/***/ 87008: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -47739,14 +45895,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TestTransport = void 0; -const rpc_error_1 = __nccwpck_require__(73341); -const runtime_1 = __nccwpck_require__(90076); -const rpc_output_stream_1 = __nccwpck_require__(19221); -const rpc_options_1 = __nccwpck_require__(26452); -const unary_call_1 = __nccwpck_require__(77727); -const server_streaming_call_1 = __nccwpck_require__(37387); -const client_streaming_call_1 = __nccwpck_require__(13694); -const duplex_streaming_call_1 = __nccwpck_require__(89835); +const rpc_error_1 = __nccwpck_require__(63159); +const runtime_1 = __nccwpck_require__(4061); +const rpc_output_stream_1 = __nccwpck_require__(76637); +const rpc_options_1 = __nccwpck_require__(67386); +const unary_call_1 = __nccwpck_require__(84175); +const server_streaming_call_1 = __nccwpck_require__(30066); +const client_streaming_call_1 = __nccwpck_require__(29912); +const duplex_streaming_call_1 = __nccwpck_require__(17042); /** * Transport for testing. */ @@ -48052,7 +46208,7 @@ class TestInputStream { /***/ }), -/***/ 77727: +/***/ 84175: /***/ (function(__unused_webpack_module, exports) { "use strict"; @@ -48109,7 +46265,7 @@ exports.UnaryCall = UnaryCall; /***/ }), -/***/ 67516: +/***/ 54253: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -48160,7 +46316,7 @@ exports.assertFloat32 = assertFloat32; /***/ }), -/***/ 54402: +/***/ 20196: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -48286,7 +46442,7 @@ exports.base64encode = base64encode; /***/ }), -/***/ 22646: +/***/ 84921: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -48394,16 +46550,16 @@ var WireType; /***/ }), -/***/ 76442: +/***/ 65210: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BinaryReader = exports.binaryReadOptions = void 0; -const binary_format_contract_1 = __nccwpck_require__(22646); -const pb_long_1 = __nccwpck_require__(98953); -const goog_varint_1 = __nccwpck_require__(27326); +const binary_format_contract_1 = __nccwpck_require__(84921); +const pb_long_1 = __nccwpck_require__(47777); +const goog_varint_1 = __nccwpck_require__(30433); const defaultsRead = { readUnknownField: true, readerFactory: bytes => new BinaryReader(bytes), @@ -48585,16 +46741,16 @@ exports.BinaryReader = BinaryReader; /***/ }), -/***/ 65469: +/***/ 44354: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BinaryWriter = exports.binaryWriteOptions = void 0; -const pb_long_1 = __nccwpck_require__(98953); -const goog_varint_1 = __nccwpck_require__(27326); -const assert_1 = __nccwpck_require__(67516); +const pb_long_1 = __nccwpck_require__(47777); +const goog_varint_1 = __nccwpck_require__(30433); +const assert_1 = __nccwpck_require__(54253); const defaultsWrite = { writeUnknownFields: true, writerFactory: () => new BinaryWriter(), @@ -48825,7 +46981,7 @@ exports.BinaryWriter = BinaryWriter; /***/ }), -/***/ 3389: +/***/ 20085: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -48920,7 +47076,7 @@ exports.listEnumNumbers = listEnumNumbers; /***/ }), -/***/ 27326: +/***/ 30433: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -49202,7 +47358,7 @@ exports.varint32read = varint32read; /***/ }), -/***/ 90076: +/***/ 4061: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -49212,46 +47368,46 @@ exports.varint32read = varint32read; // webpack verbose output hints that this should be useful Object.defineProperty(exports, "__esModule", ({ value: true })); // Convenience JSON typings and corresponding type guards -var json_typings_1 = __nccwpck_require__(93522); +var json_typings_1 = __nccwpck_require__(70661); Object.defineProperty(exports, "typeofJsonValue", ({ enumerable: true, get: function () { return json_typings_1.typeofJsonValue; } })); Object.defineProperty(exports, "isJsonObject", ({ enumerable: true, get: function () { return json_typings_1.isJsonObject; } })); // Base 64 encoding -var base64_1 = __nccwpck_require__(54402); +var base64_1 = __nccwpck_require__(20196); Object.defineProperty(exports, "base64decode", ({ enumerable: true, get: function () { return base64_1.base64decode; } })); Object.defineProperty(exports, "base64encode", ({ enumerable: true, get: function () { return base64_1.base64encode; } })); // UTF8 encoding -var protobufjs_utf8_1 = __nccwpck_require__(63626); +var protobufjs_utf8_1 = __nccwpck_require__(95290); Object.defineProperty(exports, "utf8read", ({ enumerable: true, get: function () { return protobufjs_utf8_1.utf8read; } })); // Binary format contracts, options for reading and writing, for example -var binary_format_contract_1 = __nccwpck_require__(22646); +var binary_format_contract_1 = __nccwpck_require__(84921); Object.defineProperty(exports, "WireType", ({ enumerable: true, get: function () { return binary_format_contract_1.WireType; } })); Object.defineProperty(exports, "mergeBinaryOptions", ({ enumerable: true, get: function () { return binary_format_contract_1.mergeBinaryOptions; } })); Object.defineProperty(exports, "UnknownFieldHandler", ({ enumerable: true, get: function () { return binary_format_contract_1.UnknownFieldHandler; } })); // Standard IBinaryReader implementation -var binary_reader_1 = __nccwpck_require__(76442); +var binary_reader_1 = __nccwpck_require__(65210); Object.defineProperty(exports, "BinaryReader", ({ enumerable: true, get: function () { return binary_reader_1.BinaryReader; } })); Object.defineProperty(exports, "binaryReadOptions", ({ enumerable: true, get: function () { return binary_reader_1.binaryReadOptions; } })); // Standard IBinaryWriter implementation -var binary_writer_1 = __nccwpck_require__(65469); +var binary_writer_1 = __nccwpck_require__(44354); Object.defineProperty(exports, "BinaryWriter", ({ enumerable: true, get: function () { return binary_writer_1.BinaryWriter; } })); Object.defineProperty(exports, "binaryWriteOptions", ({ enumerable: true, get: function () { return binary_writer_1.binaryWriteOptions; } })); // Int64 and UInt64 implementations required for the binary format -var pb_long_1 = __nccwpck_require__(98953); +var pb_long_1 = __nccwpck_require__(47777); Object.defineProperty(exports, "PbLong", ({ enumerable: true, get: function () { return pb_long_1.PbLong; } })); Object.defineProperty(exports, "PbULong", ({ enumerable: true, get: function () { return pb_long_1.PbULong; } })); // JSON format contracts, options for reading and writing, for example -var json_format_contract_1 = __nccwpck_require__(44025); +var json_format_contract_1 = __nccwpck_require__(48139); Object.defineProperty(exports, "jsonReadOptions", ({ enumerable: true, get: function () { return json_format_contract_1.jsonReadOptions; } })); Object.defineProperty(exports, "jsonWriteOptions", ({ enumerable: true, get: function () { return json_format_contract_1.jsonWriteOptions; } })); Object.defineProperty(exports, "mergeJsonOptions", ({ enumerable: true, get: function () { return json_format_contract_1.mergeJsonOptions; } })); // Message type contract -var message_type_contract_1 = __nccwpck_require__(42658); +var message_type_contract_1 = __nccwpck_require__(1682); Object.defineProperty(exports, "MESSAGE_TYPE", ({ enumerable: true, get: function () { return message_type_contract_1.MESSAGE_TYPE; } })); // Message type implementation via reflection -var message_type_1 = __nccwpck_require__(64469); +var message_type_1 = __nccwpck_require__(63664); Object.defineProperty(exports, "MessageType", ({ enumerable: true, get: function () { return message_type_1.MessageType; } })); // Reflection info, generated by the plugin, exposed to the user, used by reflection ops -var reflection_info_1 = __nccwpck_require__(56095); +var reflection_info_1 = __nccwpck_require__(21370); Object.defineProperty(exports, "ScalarType", ({ enumerable: true, get: function () { return reflection_info_1.ScalarType; } })); Object.defineProperty(exports, "LongType", ({ enumerable: true, get: function () { return reflection_info_1.LongType; } })); Object.defineProperty(exports, "RepeatType", ({ enumerable: true, get: function () { return reflection_info_1.RepeatType; } })); @@ -49260,44 +47416,44 @@ Object.defineProperty(exports, "readFieldOptions", ({ enumerable: true, get: fun Object.defineProperty(exports, "readFieldOption", ({ enumerable: true, get: function () { return reflection_info_1.readFieldOption; } })); Object.defineProperty(exports, "readMessageOption", ({ enumerable: true, get: function () { return reflection_info_1.readMessageOption; } })); // Message operations via reflection -var reflection_type_check_1 = __nccwpck_require__(26308); +var reflection_type_check_1 = __nccwpck_require__(20903); Object.defineProperty(exports, "ReflectionTypeCheck", ({ enumerable: true, get: function () { return reflection_type_check_1.ReflectionTypeCheck; } })); -var reflection_create_1 = __nccwpck_require__(21293); +var reflection_create_1 = __nccwpck_require__(60390); Object.defineProperty(exports, "reflectionCreate", ({ enumerable: true, get: function () { return reflection_create_1.reflectionCreate; } })); -var reflection_scalar_default_1 = __nccwpck_require__(83353); +var reflection_scalar_default_1 = __nccwpck_require__(74863); Object.defineProperty(exports, "reflectionScalarDefault", ({ enumerable: true, get: function () { return reflection_scalar_default_1.reflectionScalarDefault; } })); -var reflection_merge_partial_1 = __nccwpck_require__(88546); +var reflection_merge_partial_1 = __nccwpck_require__(7869); Object.defineProperty(exports, "reflectionMergePartial", ({ enumerable: true, get: function () { return reflection_merge_partial_1.reflectionMergePartial; } })); -var reflection_equals_1 = __nccwpck_require__(36028); +var reflection_equals_1 = __nccwpck_require__(39473); Object.defineProperty(exports, "reflectionEquals", ({ enumerable: true, get: function () { return reflection_equals_1.reflectionEquals; } })); -var reflection_binary_reader_1 = __nccwpck_require__(51575); +var reflection_binary_reader_1 = __nccwpck_require__(91593); Object.defineProperty(exports, "ReflectionBinaryReader", ({ enumerable: true, get: function () { return reflection_binary_reader_1.ReflectionBinaryReader; } })); -var reflection_binary_writer_1 = __nccwpck_require__(78539); +var reflection_binary_writer_1 = __nccwpck_require__(57170); Object.defineProperty(exports, "ReflectionBinaryWriter", ({ enumerable: true, get: function () { return reflection_binary_writer_1.ReflectionBinaryWriter; } })); -var reflection_json_reader_1 = __nccwpck_require__(31222); +var reflection_json_reader_1 = __nccwpck_require__(229); Object.defineProperty(exports, "ReflectionJsonReader", ({ enumerable: true, get: function () { return reflection_json_reader_1.ReflectionJsonReader; } })); -var reflection_json_writer_1 = __nccwpck_require__(58041); +var reflection_json_writer_1 = __nccwpck_require__(68980); Object.defineProperty(exports, "ReflectionJsonWriter", ({ enumerable: true, get: function () { return reflection_json_writer_1.ReflectionJsonWriter; } })); -var reflection_contains_message_type_1 = __nccwpck_require__(27892); +var reflection_contains_message_type_1 = __nccwpck_require__(67317); Object.defineProperty(exports, "containsMessageType", ({ enumerable: true, get: function () { return reflection_contains_message_type_1.containsMessageType; } })); // Oneof helpers -var oneof_1 = __nccwpck_require__(41938); +var oneof_1 = __nccwpck_require__(78531); Object.defineProperty(exports, "isOneofGroup", ({ enumerable: true, get: function () { return oneof_1.isOneofGroup; } })); Object.defineProperty(exports, "setOneofValue", ({ enumerable: true, get: function () { return oneof_1.setOneofValue; } })); Object.defineProperty(exports, "getOneofValue", ({ enumerable: true, get: function () { return oneof_1.getOneofValue; } })); Object.defineProperty(exports, "clearOneofValue", ({ enumerable: true, get: function () { return oneof_1.clearOneofValue; } })); Object.defineProperty(exports, "getSelectedOneofValue", ({ enumerable: true, get: function () { return oneof_1.getSelectedOneofValue; } })); // Enum object type guard and reflection util, may be interesting to the user. -var enum_object_1 = __nccwpck_require__(3389); +var enum_object_1 = __nccwpck_require__(20085); Object.defineProperty(exports, "listEnumValues", ({ enumerable: true, get: function () { return enum_object_1.listEnumValues; } })); Object.defineProperty(exports, "listEnumNames", ({ enumerable: true, get: function () { return enum_object_1.listEnumNames; } })); Object.defineProperty(exports, "listEnumNumbers", ({ enumerable: true, get: function () { return enum_object_1.listEnumNumbers; } })); Object.defineProperty(exports, "isEnumObject", ({ enumerable: true, get: function () { return enum_object_1.isEnumObject; } })); // lowerCamelCase() is exported for plugin, rpc-runtime and other rpc packages -var lower_camel_case_1 = __nccwpck_require__(35301); +var lower_camel_case_1 = __nccwpck_require__(34772); Object.defineProperty(exports, "lowerCamelCase", ({ enumerable: true, get: function () { return lower_camel_case_1.lowerCamelCase; } })); // assertion functions are exported for plugin, may also be useful to user -var assert_1 = __nccwpck_require__(67516); +var assert_1 = __nccwpck_require__(54253); Object.defineProperty(exports, "assert", ({ enumerable: true, get: function () { return assert_1.assert; } })); Object.defineProperty(exports, "assertNever", ({ enumerable: true, get: function () { return assert_1.assertNever; } })); Object.defineProperty(exports, "assertInt32", ({ enumerable: true, get: function () { return assert_1.assertInt32; } })); @@ -49307,7 +47463,7 @@ Object.defineProperty(exports, "assertFloat32", ({ enumerable: true, get: functi /***/ }), -/***/ 44025: +/***/ 48139: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -49350,7 +47506,7 @@ exports.mergeJsonOptions = mergeJsonOptions; /***/ }), -/***/ 93522: +/***/ 70661: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -49383,7 +47539,7 @@ exports.isJsonObject = isJsonObject; /***/ }), -/***/ 35301: +/***/ 34772: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -49426,7 +47582,7 @@ exports.lowerCamelCase = lowerCamelCase; /***/ }), -/***/ 42658: +/***/ 1682: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -49444,26 +47600,27 @@ exports.MESSAGE_TYPE = Symbol.for("protobuf-ts/message-type"); /***/ }), -/***/ 64469: +/***/ 63664: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MessageType = void 0; -const reflection_info_1 = __nccwpck_require__(56095); -const reflection_type_check_1 = __nccwpck_require__(26308); -const reflection_json_reader_1 = __nccwpck_require__(31222); -const reflection_json_writer_1 = __nccwpck_require__(58041); -const reflection_binary_reader_1 = __nccwpck_require__(51575); -const reflection_binary_writer_1 = __nccwpck_require__(78539); -const reflection_create_1 = __nccwpck_require__(21293); -const reflection_merge_partial_1 = __nccwpck_require__(88546); -const json_typings_1 = __nccwpck_require__(93522); -const json_format_contract_1 = __nccwpck_require__(44025); -const reflection_equals_1 = __nccwpck_require__(36028); -const binary_writer_1 = __nccwpck_require__(65469); -const binary_reader_1 = __nccwpck_require__(76442); +const message_type_contract_1 = __nccwpck_require__(1682); +const reflection_info_1 = __nccwpck_require__(21370); +const reflection_type_check_1 = __nccwpck_require__(20903); +const reflection_json_reader_1 = __nccwpck_require__(229); +const reflection_json_writer_1 = __nccwpck_require__(68980); +const reflection_binary_reader_1 = __nccwpck_require__(91593); +const reflection_binary_writer_1 = __nccwpck_require__(57170); +const reflection_create_1 = __nccwpck_require__(60390); +const reflection_merge_partial_1 = __nccwpck_require__(7869); +const json_typings_1 = __nccwpck_require__(70661); +const json_format_contract_1 = __nccwpck_require__(48139); +const reflection_equals_1 = __nccwpck_require__(39473); +const binary_writer_1 = __nccwpck_require__(44354); +const binary_reader_1 = __nccwpck_require__(65210); /** * This standard message type provides reflection-based * operations to work with a message. @@ -49474,6 +47631,7 @@ class MessageType { this.typeName = name; this.fields = fields.map(reflection_info_1.normalizeFieldInfo); this.options = options !== null && options !== void 0 ? options : {}; + this.messagePrototype = Object.defineProperty({}, message_type_contract_1.MESSAGE_TYPE, { value: this }); this.refTypeCheck = new reflection_type_check_1.ReflectionTypeCheck(this); this.refJsonReader = new reflection_json_reader_1.ReflectionJsonReader(this); this.refJsonWriter = new reflection_json_writer_1.ReflectionJsonWriter(this); @@ -49624,7 +47782,7 @@ exports.MessageType = MessageType; /***/ }), -/***/ 41938: +/***/ 78531: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -49746,14 +47904,14 @@ exports.getSelectedOneofValue = getSelectedOneofValue; /***/ }), -/***/ 98953: +/***/ 47777: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PbLong = exports.PbULong = exports.detectBi = void 0; -const goog_varint_1 = __nccwpck_require__(27326); +const goog_varint_1 = __nccwpck_require__(30433); let BI; function detectBi() { const dv = new DataView(new ArrayBuffer(8)); @@ -49992,7 +48150,7 @@ PbLong.ZERO = new PbLong(0, 0); /***/ }), -/***/ 63626: +/***/ 95290: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -50075,17 +48233,17 @@ exports.utf8read = utf8read; /***/ }), -/***/ 51575: +/***/ 91593: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReflectionBinaryReader = void 0; -const binary_format_contract_1 = __nccwpck_require__(22646); -const reflection_info_1 = __nccwpck_require__(56095); -const reflection_long_convert_1 = __nccwpck_require__(32949); -const reflection_scalar_default_1 = __nccwpck_require__(83353); +const binary_format_contract_1 = __nccwpck_require__(84921); +const reflection_info_1 = __nccwpck_require__(21370); +const reflection_long_convert_1 = __nccwpck_require__(24612); +const reflection_scalar_default_1 = __nccwpck_require__(74863); /** * Reads proto3 messages in binary format using reflection information. * @@ -50266,17 +48424,17 @@ exports.ReflectionBinaryReader = ReflectionBinaryReader; /***/ }), -/***/ 78539: +/***/ 57170: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReflectionBinaryWriter = void 0; -const binary_format_contract_1 = __nccwpck_require__(22646); -const reflection_info_1 = __nccwpck_require__(56095); -const assert_1 = __nccwpck_require__(67516); -const pb_long_1 = __nccwpck_require__(98953); +const binary_format_contract_1 = __nccwpck_require__(84921); +const reflection_info_1 = __nccwpck_require__(21370); +const assert_1 = __nccwpck_require__(54253); +const pb_long_1 = __nccwpck_require__(47777); /** * Writes proto3 messages in binary format using reflection information. * @@ -50507,14 +48665,14 @@ exports.ReflectionBinaryWriter = ReflectionBinaryWriter; /***/ }), -/***/ 27892: +/***/ 67317: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.containsMessageType = void 0; -const message_type_contract_1 = __nccwpck_require__(42658); +const message_type_contract_1 = __nccwpck_require__(1682); /** * Check if the provided object is a proto message. * @@ -50529,22 +48687,33 @@ exports.containsMessageType = containsMessageType; /***/ }), -/***/ 21293: +/***/ 60390: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.reflectionCreate = void 0; -const reflection_scalar_default_1 = __nccwpck_require__(83353); -const message_type_contract_1 = __nccwpck_require__(42658); +const reflection_scalar_default_1 = __nccwpck_require__(74863); +const message_type_contract_1 = __nccwpck_require__(1682); /** * Creates an instance of the generic message, using the field * information. */ function reflectionCreate(type) { - const msg = {}; - Object.defineProperty(msg, message_type_contract_1.MESSAGE_TYPE, { enumerable: false, value: type }); + /** + * This ternary can be removed in the next major version. + * The `Object.create()` code path utilizes a new `messagePrototype` + * property on the `IMessageType` which has this same `MESSAGE_TYPE` + * non-enumerable property on it. Doing it this way means that we only + * pay the cost of `Object.defineProperty()` once per `IMessageType` + * class of once per "instance". The falsy code path is only provided + * for backwards compatibility in cases where the runtime library is + * updated without also updating the generated code. + */ + const msg = type.messagePrototype + ? Object.create(type.messagePrototype) + : Object.defineProperty({}, message_type_contract_1.MESSAGE_TYPE, { value: type }); for (let field of type.fields) { let name = field.localName; if (field.opt) @@ -50574,14 +48743,14 @@ exports.reflectionCreate = reflectionCreate; /***/ }), -/***/ 36028: +/***/ 39473: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.reflectionEquals = void 0; -const reflection_info_1 = __nccwpck_require__(56095); +const reflection_info_1 = __nccwpck_require__(21370); /** * Determines whether two message of the same type have the same field values. * Checks for deep equality, traversing repeated fields, oneof groups, maps @@ -50659,14 +48828,14 @@ function repeatedMsgEq(type, a, b) { /***/ }), -/***/ 56095: +/***/ 21370: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.readMessageOption = exports.readFieldOption = exports.readFieldOptions = exports.normalizeFieldInfo = exports.RepeatType = exports.LongType = exports.ScalarType = void 0; -const lower_camel_case_1 = __nccwpck_require__(35301); +const lower_camel_case_1 = __nccwpck_require__(34772); /** * Scalar value types. This is a subset of field types declared by protobuf * enum google.protobuf.FieldDescriptorProto.Type The types GROUP and MESSAGE @@ -50825,19 +48994,19 @@ exports.readMessageOption = readMessageOption; /***/ }), -/***/ 31222: +/***/ 229: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReflectionJsonReader = void 0; -const json_typings_1 = __nccwpck_require__(93522); -const base64_1 = __nccwpck_require__(54402); -const reflection_info_1 = __nccwpck_require__(56095); -const pb_long_1 = __nccwpck_require__(98953); -const assert_1 = __nccwpck_require__(67516); -const reflection_long_convert_1 = __nccwpck_require__(32949); +const json_typings_1 = __nccwpck_require__(70661); +const base64_1 = __nccwpck_require__(20196); +const reflection_info_1 = __nccwpck_require__(21370); +const pb_long_1 = __nccwpck_require__(47777); +const assert_1 = __nccwpck_require__(54253); +const reflection_long_convert_1 = __nccwpck_require__(24612); /** * Reads proto3 messages in canonical JSON format using reflection information. * @@ -51146,17 +49315,17 @@ exports.ReflectionJsonReader = ReflectionJsonReader; /***/ }), -/***/ 58041: +/***/ 68980: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReflectionJsonWriter = void 0; -const base64_1 = __nccwpck_require__(54402); -const pb_long_1 = __nccwpck_require__(98953); -const reflection_info_1 = __nccwpck_require__(56095); -const assert_1 = __nccwpck_require__(67516); +const base64_1 = __nccwpck_require__(20196); +const pb_long_1 = __nccwpck_require__(47777); +const reflection_info_1 = __nccwpck_require__(21370); +const assert_1 = __nccwpck_require__(54253); /** * Writes proto3 messages in canonical JSON format using reflection * information. @@ -51384,14 +49553,14 @@ exports.ReflectionJsonWriter = ReflectionJsonWriter; /***/ }), -/***/ 32949: +/***/ 24612: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.reflectionLongConvert = void 0; -const reflection_info_1 = __nccwpck_require__(56095); +const reflection_info_1 = __nccwpck_require__(21370); /** * Utility method to convert a PbLong or PbUlong to a JavaScript * representation during runtime. @@ -51416,7 +49585,7 @@ exports.reflectionLongConvert = reflectionLongConvert; /***/ }), -/***/ 88546: +/***/ 7869: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51514,16 +49683,16 @@ exports.reflectionMergePartial = reflectionMergePartial; /***/ }), -/***/ 83353: +/***/ 74863: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.reflectionScalarDefault = void 0; -const reflection_info_1 = __nccwpck_require__(56095); -const reflection_long_convert_1 = __nccwpck_require__(32949); -const pb_long_1 = __nccwpck_require__(98953); +const reflection_info_1 = __nccwpck_require__(21370); +const reflection_long_convert_1 = __nccwpck_require__(24612); +const pb_long_1 = __nccwpck_require__(47777); /** * Creates the default value for a scalar type. */ @@ -51559,15 +49728,15 @@ exports.reflectionScalarDefault = reflectionScalarDefault; /***/ }), -/***/ 26308: +/***/ 20903: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReflectionTypeCheck = void 0; -const reflection_info_1 = __nccwpck_require__(56095); -const oneof_1 = __nccwpck_require__(41938); +const reflection_info_1 = __nccwpck_require__(21370); +const oneof_1 = __nccwpck_require__(78531); // noinspection JSMethodCanBeStatic class ReflectionTypeCheck { constructor(info) { @@ -51797,7 +49966,7 @@ exports.ReflectionTypeCheck = ReflectionTypeCheck; /***/ }), -/***/ 85982: +/***/ 81231: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** @@ -51807,15 +49976,15 @@ exports.ReflectionTypeCheck = ReflectionTypeCheck; * Licensed under the MIT license. * https://github.com/archiverjs/node-archiver/blob/master/LICENSE-MIT */ -var fs = __nccwpck_require__(91468); +var fs = __nccwpck_require__(77758); var path = __nccwpck_require__(71017); -var flatten = __nccwpck_require__(25402); -var difference = __nccwpck_require__(23651); -var union = __nccwpck_require__(76640); -var isPlainObject = __nccwpck_require__(98466); +var flatten = __nccwpck_require__(48919); +var difference = __nccwpck_require__(89764); +var union = __nccwpck_require__(28651); +var isPlainObject = __nccwpck_require__(25723); -var glob = __nccwpck_require__(3661); +var glob = __nccwpck_require__(30095); var file = module.exports = {}; @@ -52013,7 +50182,7 @@ file.normalizeFilesArray = function(data) { /***/ }), -/***/ 9925: +/***/ 82072: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** @@ -52023,18 +50192,18 @@ file.normalizeFilesArray = function(data) { * Licensed under the MIT license. * https://github.com/archiverjs/archiver-utils/blob/master/LICENSE */ -var fs = __nccwpck_require__(91468); +var fs = __nccwpck_require__(77758); var path = __nccwpck_require__(71017); var nutil = __nccwpck_require__(73837); -var lazystream = __nccwpck_require__(9936); -var normalizePath = __nccwpck_require__(19796); -var defaults = __nccwpck_require__(14285); +var lazystream = __nccwpck_require__(12084); +var normalizePath = __nccwpck_require__(55388); +var defaults = __nccwpck_require__(11289); var Stream = (__nccwpck_require__(12781).Stream); -var PassThrough = (__nccwpck_require__(93130).PassThrough); +var PassThrough = (__nccwpck_require__(44785).PassThrough); var utils = module.exports = {}; -utils.file = __nccwpck_require__(85982); +utils.file = __nccwpck_require__(81231); function assertPath(path) { if (typeof path !== 'string') { @@ -52176,1820 +50345,1625 @@ utils.walkdir = function(dirpath, base, callback) { /***/ }), -/***/ 57607: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. +/***/ 84938: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. +exports.setopts = setopts +exports.ownProp = ownProp +exports.makeAbs = makeAbs +exports.finish = finish +exports.mark = mark +exports.isIgnored = isIgnored +exports.childrenIgnored = childrenIgnored +function ownProp (obj, field) { + return Object.prototype.hasOwnProperty.call(obj, field) +} +var fs = __nccwpck_require__(57147) +var path = __nccwpck_require__(71017) +var minimatch = __nccwpck_require__(83973) +var isAbsolute = __nccwpck_require__(38714) +var Minimatch = minimatch.Minimatch -/**/ +function alphasort (a, b) { + return a.localeCompare(b, 'en') +} -var pna = __nccwpck_require__(13817); -/**/ +function setupIgnores (self, options) { + self.ignore = options.ignore || [] -/**/ -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - keys.push(key); - }return keys; -}; -/**/ + if (!Array.isArray(self.ignore)) + self.ignore = [self.ignore] -module.exports = Duplex; + if (self.ignore.length) { + self.ignore = self.ignore.map(ignoreMap) + } +} -/**/ -var util = Object.create(__nccwpck_require__(32137)); -util.inherits = __nccwpck_require__(42991); -/**/ +// ignore patterns are always in dot:true mode. +function ignoreMap (pattern) { + var gmatcher = null + if (pattern.slice(-3) === '/**') { + var gpattern = pattern.replace(/(\/\*\*)+$/, '') + gmatcher = new Minimatch(gpattern, { dot: true }) + } -var Readable = __nccwpck_require__(63037); -var Writable = __nccwpck_require__(51080); + return { + matcher: new Minimatch(pattern, { dot: true }), + gmatcher: gmatcher + } +} -util.inherits(Duplex, Readable); +function setopts (self, pattern, options) { + if (!options) + options = {} -{ - // avoid scope creep, the keys array can then be collected - var keys = objectKeys(Writable.prototype); - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + // base-matching: just use globstar for that. + if (options.matchBase && -1 === pattern.indexOf("/")) { + if (options.noglobstar) { + throw new Error("base matching requires globstar") + } + pattern = "**/" + pattern } -} -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); + self.silent = !!options.silent + self.pattern = pattern + self.strict = options.strict !== false + self.realpath = !!options.realpath + self.realpathCache = options.realpathCache || Object.create(null) + self.follow = !!options.follow + self.dot = !!options.dot + self.mark = !!options.mark + self.nodir = !!options.nodir + if (self.nodir) + self.mark = true + self.sync = !!options.sync + self.nounique = !!options.nounique + self.nonull = !!options.nonull + self.nosort = !!options.nosort + self.nocase = !!options.nocase + self.stat = !!options.stat + self.noprocess = !!options.noprocess + self.absolute = !!options.absolute + self.fs = options.fs || fs - Readable.call(this, options); - Writable.call(this, options); + self.maxLength = options.maxLength || Infinity + self.cache = options.cache || Object.create(null) + self.statCache = options.statCache || Object.create(null) + self.symlinks = options.symlinks || Object.create(null) - if (options && options.readable === false) this.readable = false; + setupIgnores(self, options) - if (options && options.writable === false) this.writable = false; + self.changedCwd = false + var cwd = process.cwd() + if (!ownProp(options, "cwd")) + self.cwd = cwd + else { + self.cwd = path.resolve(options.cwd) + self.changedCwd = self.cwd !== cwd + } - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + self.root = options.root || path.resolve(self.cwd, "/") + self.root = path.resolve(self.root) + if (process.platform === "win32") + self.root = self.root.replace(/\\/g, "/") - this.once('end', onend); + // TODO: is an absolute `cwd` supposed to be resolved against `root`? + // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') + self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) + if (process.platform === "win32") + self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") + self.nomount = !!options.nomount + + // disable comments and negation in Minimatch. + // Note that they are not supported in Glob itself anyway. + options.nonegate = true + options.nocomment = true + // always treat \ in patterns as escapes, not path separators + options.allowWindowsEscape = false + + self.minimatch = new Minimatch(pattern, options) + self.options = self.minimatch.options } -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function () { - return this._writableState.highWaterMark; - } -}); +function finish (self) { + var nou = self.nounique + var all = nou ? [] : Object.create(null) -// the no-half-open enforcer -function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; + for (var i = 0, l = self.matches.length; i < l; i ++) { + var matches = self.matches[i] + if (!matches || Object.keys(matches).length === 0) { + if (self.nonull) { + // do like the shell, and spit out the literal glob + var literal = self.minimatch.globSet[i] + if (nou) + all.push(literal) + else + all[literal] = true + } + } else { + // had matches + var m = Object.keys(matches) + if (nou) + all.push.apply(all, m) + else + m.forEach(function (m) { + all[m] = true + }) + } + } - // no more data can be written. - // But allow more writes to happen in this tick. - pna.nextTick(onEndNT, this); -} + if (!nou) + all = Object.keys(all) -function onEndNT(self) { - self.end(); -} + if (!self.nosort) + all = all.sort(alphasort) -Object.defineProperty(Duplex.prototype, 'destroyed', { - get: function () { - if (this._readableState === undefined || this._writableState === undefined) { - return false; + // at *some* point we statted all of these + if (self.mark) { + for (var i = 0; i < all.length; i++) { + all[i] = self._mark(all[i]) } - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; + if (self.nodir) { + all = all.filter(function (e) { + var notDir = !(/\/$/.test(e)) + var c = self.cache[e] || self.cache[makeAbs(self, e)] + if (notDir && c) + notDir = c !== 'DIR' && !Array.isArray(c) + return notDir + }) } - - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; - this._writableState.destroyed = value; } -}); -Duplex.prototype._destroy = function (err, cb) { - this.push(null); - this.end(); + if (self.ignore.length) + all = all.filter(function(m) { + return !isIgnored(self, m) + }) - pna.nextTick(cb, err); -}; + self.found = all +} -/***/ }), +function mark (self, p) { + var abs = makeAbs(self, p) + var c = self.cache[abs] + var m = p + if (c) { + var isDir = c === 'DIR' || Array.isArray(c) + var slash = p.slice(-1) === '/' -/***/ 63656: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (isDir && !slash) + m += '/' + else if (!isDir && slash) + m = m.slice(0, -1) -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + if (m !== p) { + var mabs = makeAbs(self, m) + self.statCache[mabs] = self.statCache[abs] + self.cache[mabs] = self.cache[abs] + } + } -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. + return m +} +// lotta situps... +function makeAbs (self, f) { + var abs = f + if (f.charAt(0) === '/') { + abs = path.join(self.root, f) + } else if (isAbsolute(f) || f === '') { + abs = f + } else if (self.changedCwd) { + abs = path.resolve(self.cwd, f) + } else { + abs = path.resolve(f) + } + if (process.platform === 'win32') + abs = abs.replace(/\\/g, '/') -module.exports = PassThrough; + return abs +} -var Transform = __nccwpck_require__(79994); -/**/ -var util = Object.create(__nccwpck_require__(32137)); -util.inherits = __nccwpck_require__(42991); -/**/ +// Return true, if pattern ends with globstar '**', for the accompanying parent directory. +// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents +function isIgnored (self, path) { + if (!self.ignore.length) + return false -util.inherits(PassThrough, Transform); + return self.ignore.some(function(item) { + return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) + }) +} -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); +function childrenIgnored (self, path) { + if (!self.ignore.length) + return false - Transform.call(this, options); + return self.ignore.some(function(item) { + return !!(item.gmatcher && item.gmatcher.match(path)) + }) } -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; /***/ }), -/***/ 63037: +/***/ 30095: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. +// Approach: // -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: +// 1. Get the minimatch set +// 2. For each pattern in the set, PROCESS(pattern, false) +// 3. Store matches per-set, then uniq them // -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. +// PROCESS(pattern, inGlobStar) +// Get the first [n] items from pattern that are all strings +// Join these together. This is PREFIX. +// If there is no more remaining, then stat(PREFIX) and +// add to matches if it succeeds. END. // -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. +// If inGlobStar and PREFIX is symlink and points to dir +// set ENTRIES = [] +// else readdir(PREFIX) as ENTRIES +// If fail, END +// +// with ENTRIES +// If pattern[n] is GLOBSTAR +// // handle the case where the globstar match is empty +// // by pruning it out, and testing the resulting pattern +// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) +// // handle other cases. +// for ENTRY in ENTRIES (not dotfiles) +// // attach globstar + tail onto the entry +// // Mark that this entry is a globstar match +// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) +// +// else // not globstar +// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) +// Test ENTRY against pattern[n] +// If fails, continue +// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) +// +// Caveat: +// Cache all stats and readdirs results to minimize syscall. Since all +// we ever care about is existence and directory-ness, we can just keep +// `true` for files, and [children,...] for directories, or `false` for +// things that don't exist. +module.exports = glob +var rp = __nccwpck_require__(46863) +var minimatch = __nccwpck_require__(83973) +var Minimatch = minimatch.Minimatch +var inherits = __nccwpck_require__(44124) +var EE = (__nccwpck_require__(82361).EventEmitter) +var path = __nccwpck_require__(71017) +var assert = __nccwpck_require__(39491) +var isAbsolute = __nccwpck_require__(38714) +var globSync = __nccwpck_require__(57388) +var common = __nccwpck_require__(84938) +var setopts = common.setopts +var ownProp = common.ownProp +var inflight = __nccwpck_require__(52492) +var util = __nccwpck_require__(73837) +var childrenIgnored = common.childrenIgnored +var isIgnored = common.isIgnored -/**/ +var once = __nccwpck_require__(1223) -var pna = __nccwpck_require__(13817); -/**/ +function glob (pattern, options, cb) { + if (typeof options === 'function') cb = options, options = {} + if (!options) options = {} -module.exports = Readable; + if (options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return globSync(pattern, options) + } -/**/ -var isArray = __nccwpck_require__(80456); -/**/ + return new Glob(pattern, options, cb) +} -/**/ -var Duplex; -/**/ +glob.sync = globSync +var GlobSync = glob.GlobSync = globSync.GlobSync -Readable.ReadableState = ReadableState; +// old api surface +glob.glob = glob -/**/ -var EE = (__nccwpck_require__(82361).EventEmitter); +function extend (origin, add) { + if (add === null || typeof add !== 'object') { + return origin + } -var EElistenerCount = function (emitter, type) { - return emitter.listeners(type).length; -}; -/**/ + var keys = Object.keys(add) + var i = keys.length + while (i--) { + origin[keys[i]] = add[keys[i]] + } + return origin +} -/**/ -var Stream = __nccwpck_require__(33182); -/**/ +glob.hasMagic = function (pattern, options_) { + var options = extend({}, options_) + options.noprocess = true -/**/ + var g = new Glob(pattern, options) + var set = g.minimatch.set -var Buffer = (__nccwpck_require__(37514).Buffer); -var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} + if (!pattern) + return false -/**/ + if (set.length > 1) + return true -/**/ -var util = Object.create(__nccwpck_require__(32137)); -util.inherits = __nccwpck_require__(42991); -/**/ + for (var j = 0; j < set[0].length; j++) { + if (typeof set[0][j] !== 'string') + return true + } -/**/ -var debugUtil = __nccwpck_require__(73837); -var debug = void 0; -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function () {}; + return false } -/**/ -var BufferList = __nccwpck_require__(64194); -var destroyImpl = __nccwpck_require__(37421); -var StringDecoder; +glob.Glob = Glob +inherits(Glob, EE) +function Glob (pattern, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } -util.inherits(Readable, Stream); + if (options && options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return new GlobSync(pattern, options) + } -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + if (!(this instanceof Glob)) + return new Glob(pattern, options, cb) -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + setopts(this, pattern, options) + this._didRealPath = false - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} + // process each pattern in the minimatch set + var n = this.minimatch.set.length -function ReadableState(options, stream) { - Duplex = Duplex || __nccwpck_require__(57607); + // The matches are stored as {: true,...} so that + // duplicates are automagically pruned. + // Later, we do an Object.keys() on these. + // Keep them as a list so we can fill in when nonull is set. + this.matches = new Array(n) - options = options || {}; + if (typeof cb === 'function') { + cb = once(cb) + this.on('error', cb) + this.on('end', function (matches) { + cb(null, matches) + }) + } - // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - var isDuplex = stream instanceof Duplex; + var self = this + this._processing = 0 - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; + this._emitQueue = [] + this._processQueue = [] + this.paused = false - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + if (this.noprocess) + return this - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var readableHwm = options.readableHighWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; + if (n === 0) + return done() - if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; + var sync = true + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false, done) + } + sync = false - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); + function done () { + --self._processing + if (self._processing <= 0) { + if (sync) { + process.nextTick(function () { + self._finish() + }) + } else { + self._finish() + } + } + } +} - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; +Glob.prototype._finish = function () { + assert(this instanceof Glob) + if (this.aborted) + return - // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - this.sync = true; + if (this.realpath && !this._didRealpath) + return this._realpath() - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; + common.finish(this) + this.emit('end', this.found) +} - // has it been destroyed - this.destroyed = false; +Glob.prototype._realpath = function () { + if (this._didRealpath) + return - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + this._didRealpath = true - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; + var n = this.matches.length + if (n === 0) + return this._finish() - // if true, a maybeReadMore has been scheduled - this.readingMore = false; + var self = this + for (var i = 0; i < this.matches.length; i++) + this._realpathSet(i, next) - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) StringDecoder = (__nccwpck_require__(50823)/* .StringDecoder */ .s); - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; + function next () { + if (--n === 0) + self._finish() } } -function Readable(options) { - Duplex = Duplex || __nccwpck_require__(57607); +Glob.prototype._realpathSet = function (index, cb) { + var matchset = this.matches[index] + if (!matchset) + return cb() - if (!(this instanceof Readable)) return new Readable(options); + var found = Object.keys(matchset) + var self = this + var n = found.length - this._readableState = new ReadableState(options, this); + if (n === 0) + return cb() - // legacy - this.readable = true; + var set = this.matches[index] = Object.create(null) + found.forEach(function (p, i) { + // If there's a problem with the stat, then it means that + // one or more of the links in the realpath couldn't be + // resolved. just return the abs value in that case. + p = self._makeAbs(p) + rp.realpath(p, self.realpathCache, function (er, real) { + if (!er) + set[real] = true + else if (er.syscall === 'stat') + set[p] = true + else + self.emit('error', er) // srsly wtf right here - if (options) { - if (typeof options.read === 'function') this._read = options.read; + if (--n === 0) { + self.matches[index] = set + cb() + } + }) + }) +} - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } +Glob.prototype._mark = function (p) { + return common.mark(this, p) +} - Stream.call(this); +Glob.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) } -Object.defineProperty(Readable.prototype, 'destroyed', { - get: function () { - if (this._readableState === undefined) { - return false; - } - return this._readableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } +Glob.prototype.abort = function () { + this.aborted = true + this.emit('abort') +} - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; +Glob.prototype.pause = function () { + if (!this.paused) { + this.paused = true + this.emit('pause') } -}); - -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; -Readable.prototype._destroy = function (err, cb) { - this.push(null); - cb(err); -}; - -// Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; +} - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; +Glob.prototype.resume = function () { + if (this.paused) { + this.emit('resume') + this.paused = false + if (this._emitQueue.length) { + var eq = this._emitQueue.slice(0) + this._emitQueue.length = 0 + for (var i = 0; i < eq.length; i ++) { + var e = eq[i] + this._emitMatch(e[0], e[1]) + } + } + if (this._processQueue.length) { + var pq = this._processQueue.slice(0) + this._processQueue.length = 0 + for (var i = 0; i < pq.length; i ++) { + var p = pq[i] + this._processing-- + this._process(p[0], p[1], p[2], p[3]) } - skipChunkCheck = true; } - } else { - skipChunkCheck = true; } +} - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; +Glob.prototype._process = function (pattern, index, inGlobStar, cb) { + assert(this instanceof Glob) + assert(typeof cb === 'function') -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; + if (this.aborted) + return -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - var state = stream._readableState; - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } + this._processing++ + if (this.paused) { + this._processQueue.push([pattern, index, inGlobStar, cb]) + return + } - if (addToFront) { - if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); - } else if (state.ended) { - stream.emit('error', new Error('stream.push() after EOF')); - } else { - state.reading = false; - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - } + //console.error('PROCESS %d', this._processing, pattern) + + // Get the first [n] parts of pattern that are all strings. + var n = 0 + while (typeof pattern[n] === 'string') { + n ++ } + // now n is the index of the first one that is *not* a string. - return needMoreData(state); -} + // see if there's anything else + var prefix + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index, cb) + return -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null + break - if (state.needReadable) emitReadable(stream); + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/') + break } - maybeReadMore(stream, state); -} -function chunkInvalid(state, chunk) { - var er; - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; -} + var remain = pattern.slice(n) -// if it's past the high water mark, we can push in some more. -// Also, if we have no data yet, we can stand some -// more bytes. This is to work around cases where hwm=0, -// such as the repl. Also, if the push() triggered a -// readable event, and the user called read(largeNumber) such that -// needReadable was set, then we ought to push more, so that another -// 'readable' event will be triggered. -function needMoreData(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); -} + // get the list of entries. + var read + if (prefix === null) + read = '.' + else if (isAbsolute(prefix) || + isAbsolute(pattern.map(function (p) { + return typeof p === 'string' ? p : '[*]' + }).join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix + read = prefix + } else + read = prefix -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; + var abs = this._makeAbs(read) -// backwards compatibility. -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = (__nccwpck_require__(50823)/* .StringDecoder */ .s); - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; - return this; -}; + //if ignored, skip _processing + if (childrenIgnored(this, read)) + return cb() -// Don't raise the hwm > 8MB -var MAX_HWM = 0x800000; -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - return n; + var isGlobStar = remain[0] === minimatch.GLOBSTAR + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) } -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; - } - return state.length; +Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) } -// you can override either this method, or the async _read(n) below. -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; +Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { - if (n !== 0) state.emittedReadable = false; + // if the abs isn't a dir, then nothing can match! + if (!entries) + return cb() - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0] + var negate = !!this.minimatch.negate + var rawGlob = pn._glob + var dotOk = this.dot || rawGlob.charAt(0) === '.' + + var matchedEntries = [] + for (var i = 0; i < entries.length; i++) { + var e = entries[i] + if (e.charAt(0) !== '.' || dotOk) { + var m + if (negate && !prefix) { + m = !e.match(pn) + } else { + m = e.match(pn) + } + if (m) + matchedEntries.push(e) + } } - n = howMuchToRead(n, state); + //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } + var len = matchedEntries.length + // If there are no matched entries, then nothing matches. + if (len === 0) + return cb() - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug('need readable', doRead); + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null) - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e + else + e = prefix + e + } - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state); + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e) + } + this._emitMatch(index, e) + } + // This was the last one, and no stats were needed + return cb() } - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = true; - n = 0; - } else { - state.length -= n; + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift() + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + var newPattern + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + this._process([e].concat(remain), index, inGlobStar, cb) } + cb() +} - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; +Glob.prototype._emitMatch = function (index, e) { + if (this.aborted) + return - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this); + if (isIgnored(this, e)) + return + + if (this.paused) { + this._emitQueue.push([index, e]) + return } - if (ret !== null) this.emit('data', ret); + var abs = isAbsolute(e) ? e : this._makeAbs(e) - return ret; -}; + if (this.mark) + e = this._mark(e) -function onEofChunk(stream, state) { - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; + if (this.absolute) + e = abs - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); -} + if (this.matches[index][e]) + return -// Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); + if (this.nodir) { + var c = this.cache[abs] + if (c === 'DIR' || Array.isArray(c)) + return } -} -function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); - flow(stream); -} + this.matches[index][e] = true -// at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - pna.nextTick(maybeReadMore_, stream, state); - } -} + var st = this.statCache[abs] + if (st) + this.emit('stat', e, st) -function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; - } - state.readingMore = false; + this.emit('match', e) } -// abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. -Readable.prototype._read = function (n) { - this.emit('error', new Error('_read() is not implemented')); -}; +Glob.prototype._readdirInGlobStar = function (abs, cb) { + if (this.aborted) + return -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false, cb) - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var lstatkey = 'lstat\0' + abs + var self = this + var lstatcb = inflight(lstatkey, lstatcb_) - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + if (lstatcb) + self.fs.lstat(abs, lstatcb) - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); + function lstatcb_ (er, lstat) { + if (er && er.code === 'ENOENT') + return cb() - dest.on('unpipe', onunpipe); - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } + var isSym = lstat && lstat.isSymbolicLink() + self.symlinks[abs] = isSym - function onend() { - debug('onend'); - dest.end(); + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) { + self.cache[abs] = 'FILE' + cb() + } else + self._readdir(abs, false, cb) } +} - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); +Glob.prototype._readdir = function (abs, inGlobStar, cb) { + if (this.aborted) + return - var cleanedUp = false; - function cleanup() { - debug('cleanup'); - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); + cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) + if (!cb) + return - cleanedUp = true; + //console.error('RD %j %j', +inGlobStar, abs) + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs, cb) - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } + if (ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (!c || c === 'FILE') + return cb() - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on('data', ondata); - function ondata(chunk) { - debug('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', state.awaitDrain); - state.awaitDrain++; - increasedAwaitDrain = true; - } - src.pause(); - } + if (Array.isArray(c)) + return cb(null, c) } - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + var self = this + self.fs.readdir(abs, readdirCb(this, abs, cb)) +} + +function readdirCb (self, abs, cb) { + return function (er, entries) { + if (er) + self._readdirError(abs, er, cb) + else + self._readdirEntries(abs, entries, cb) } +} - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); +Glob.prototype._readdirEntries = function (abs, entries, cb) { + if (this.aborted) + return - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i] + if (abs === '/') + e = abs + e + else + e = abs + '/' + e + this.cache[e] = true + } } - dest.once('finish', onfinish); - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } + this.cache[abs] = entries + return cb(null, entries) +} - // tell the dest that it's being piped to - dest.emit('pipe', src); +Glob.prototype._readdirError = function (f, er, cb) { + if (this.aborted) + return - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug('pipe resume'); - src.resume(); + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f) + this.cache[abs] = 'FILE' + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd) + error.path = this.cwd + error.code = er.code + this.emit('error', error) + this.abort() + } + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false + if (this.strict) { + this.emit('error', er) + // If the error is handled, then we abort + // if not, we threw out of here + this.abort() + } + if (!this.silent) + console.error('glob error', er) + break } - return dest; -}; + return cb() +} -function pipeOnDrain(src) { - return function () { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; +Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) } -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { hasUnpiped: false }; - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; +Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + //console.error('pgs2', prefix, remain[0], entries) - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return cb() - if (!dest) dest = state.pipes; + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false, cb) - // slow case. multiple pipe destinations. + var isSym = this.symlinks[abs] + var len = entries.length - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return cb() - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { hasUnpiped: false }); - }return this; - } + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) + continue - // try to find the right one. - var index = indexOf(state.pipes, dest); - if (index === -1) return this; + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true, cb) - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; + var below = gspref.concat(entries[i], remain) + this._process(below, index, true, cb) + } - dest.emit('unpipe', this, unpipeInfo); + cb() +} - return this; -}; +Glob.prototype._processSimple = function (prefix, index, cb) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var self = this + this._stat(prefix, function (er, exists) { + self._processSimple2(prefix, index, er, exists, cb) + }) +} +Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { -// set up data events if they are asked for -// Ensure readable listeners eventually get something -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); + //console.error('ps2', prefix, exists) - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - pna.nextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable(this); - } - } - } + if (!this.matches[index]) + this.matches[index] = Object.create(null) - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; - -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} - -// pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. -Readable.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug('resume'); - state.flowing = true; - resume(this, state); - } - return this; -}; - -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - pna.nextTick(resume_, stream, state); - } -} + // If it doesn't exist, then just mark the lack of results + if (!exists) + return cb() -function resume_(stream, state) { - if (!state.reading) { - debug('resume read 0'); - stream.read(0); + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) + } else { + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' + } } - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} - -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - return this; -}; + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - while (state.flowing && stream.read() !== null) {} + // Mark this as a match + this._emitMatch(index, prefix) + cb() } -// wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. -Readable.prototype.wrap = function (stream) { - var _this = this; - - var state = this._readableState; - var paused = false; - - stream.on('end', function () { - debug('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } +// Returns either 'DIR', 'FILE', or false +Glob.prototype._stat = function (f, cb) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' - _this.push(null); - }); + if (f.length > this.maxLength) + return cb() - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + if (Array.isArray(c)) + c = 'DIR' - var ret = _this.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return cb(null, c) - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } + if (needDir && c === 'FILE') + return cb() - // proxy certain important events. - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. } - // when we try to consume some more bytes, simply unpause the - // underlying stream. - this._read = function (n) { - debug('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); + var exists + var stat = this.statCache[abs] + if (stat !== undefined) { + if (stat === false) + return cb(null, stat) + else { + var type = stat.isDirectory() ? 'DIR' : 'FILE' + if (needDir && type === 'FILE') + return cb() + else + return cb(null, type, stat) } - }; - - return this; -}; - -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function () { - return this._readableState.highWaterMark; - } -}); - -// exposed for testing purposes only. -Readable._fromList = fromList; - -// Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); } - return ret; -} - -// Extracts only enough buffered data to satisfy the amount requested. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); - } - return ret; -} + var self = this + var statcb = inflight('stat\0' + abs, lstatcb_) + if (statcb) + self.fs.lstat(abs, statcb) -// Copies a specified amount of characters from the list of buffered data -// chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; + function lstatcb_ (er, lstat) { + if (lstat && lstat.isSymbolicLink()) { + // If it's a symlink, then treat it as the target, unless + // the target does not exist, then treat it as a file. + return self.fs.stat(abs, function (er, stat) { + if (er) + self._stat2(f, abs, null, lstat, cb) + else + self._stat2(f, abs, er, stat, cb) + }) + } else { + self._stat2(f, abs, er, lstat, cb) } - ++c; } - list.length -= c; - return ret; } -// Copies a specified amount of bytes from the list of buffered data chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBuffer(n, list) { - var ret = Buffer.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); - } - break; - } - ++c; +Glob.prototype._stat2 = function (f, abs, er, stat, cb) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false + return cb() } - list.length -= c; - return ret; -} -function endReadable(stream) { - var state = stream._readableState; + var needDir = f.slice(-1) === '/' + this.statCache[abs] = stat - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) + return cb(null, false, stat) - if (!state.endEmitted) { - state.ended = true; - pna.nextTick(endReadableNT, state, stream); - } -} + var c = true + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE' + this.cache[abs] = this.cache[abs] || c -function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } -} + if (needDir && c === 'FILE') + return cb() -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; + return cb(null, c, stat) } + /***/ }), -/***/ 79994: +/***/ 57388: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. +module.exports = globSync +globSync.GlobSync = GlobSync +var rp = __nccwpck_require__(46863) +var minimatch = __nccwpck_require__(83973) +var Minimatch = minimatch.Minimatch +var Glob = (__nccwpck_require__(30095).Glob) +var util = __nccwpck_require__(73837) +var path = __nccwpck_require__(71017) +var assert = __nccwpck_require__(39491) +var isAbsolute = __nccwpck_require__(38714) +var common = __nccwpck_require__(84938) +var setopts = common.setopts +var ownProp = common.ownProp +var childrenIgnored = common.childrenIgnored +var isIgnored = common.isIgnored +function globSync (pattern, options) { + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') -module.exports = Transform; + return new GlobSync(pattern, options).found +} -var Duplex = __nccwpck_require__(57607); +function GlobSync (pattern, options) { + if (!pattern) + throw new Error('must provide pattern') -/**/ -var util = Object.create(__nccwpck_require__(32137)); -util.inherits = __nccwpck_require__(42991); -/**/ + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') -util.inherits(Transform, Duplex); + if (!(this instanceof GlobSync)) + return new GlobSync(pattern, options) -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; + setopts(this, pattern, options) - var cb = ts.writecb; + if (this.noprocess) + return this - if (!cb) { - return this.emit('error', new Error('write callback called multiple times')); + var n = this.minimatch.set.length + this.matches = new Array(n) + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false) } + this._finish() +} - ts.writechunk = null; - ts.writecb = null; - - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - - cb(er); - - var rs = this._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); +GlobSync.prototype._finish = function () { + assert.ok(this instanceof GlobSync) + if (this.realpath) { + var self = this + this.matches.forEach(function (matchset, index) { + var set = self.matches[index] = Object.create(null) + for (var p in matchset) { + try { + p = self._makeAbs(p) + var real = rp.realpathSync(p, self.realpathCache) + set[real] = true + } catch (er) { + if (er.syscall === 'stat') + set[self._makeAbs(p)] = true + else + throw er + } + } + }) } + common.finish(this) } -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - - Duplex.call(this, options); - - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; - - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; - - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; +GlobSync.prototype._process = function (pattern, index, inGlobStar) { + assert.ok(this instanceof GlobSync) - if (typeof options.flush === 'function') this._flush = options.flush; + // Get the first [n] parts of pattern that are all strings. + var n = 0 + while (typeof pattern[n] === 'string') { + n ++ } + // now n is the index of the first one that is *not* a string. - // When the writable side finishes, then flush out anything remaining. - this.on('prefinish', prefinish); -} + // See if there's anything else + var prefix + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index) + return -function prefinish() { - var _this = this; + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null + break - if (typeof this._flush === 'function') { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/') + break } -} -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; + var remain = pattern.slice(n) -// This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. -Transform.prototype._transform = function (chunk, encoding, cb) { - throw new Error('_transform() is not implemented'); -}; + // get the list of entries. + var read + if (prefix === null) + read = '.' + else if (isAbsolute(prefix) || + isAbsolute(pattern.map(function (p) { + return typeof p === 'string' ? p : '[*]' + }).join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix + read = prefix + } else + read = prefix -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; + var abs = this._makeAbs(read) -// Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. -Transform.prototype._read = function (n) { - var ts = this._transformState; + //if ignored, skip processing + if (childrenIgnored(this, read)) + return - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; + var isGlobStar = remain[0] === minimatch.GLOBSTAR + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar) +} -Transform.prototype._destroy = function (err, cb) { - var _this2 = this; - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - _this2.emit('close'); - }); -}; +GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { + var entries = this._readdir(abs, inGlobStar) -function done(stream, er, data) { - if (er) return stream.emit('error', er); + // if the abs isn't a dir, then nothing can match! + if (!entries) + return - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0] + var negate = !!this.minimatch.negate + var rawGlob = pn._glob + var dotOk = this.dot || rawGlob.charAt(0) === '.' - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); + var matchedEntries = [] + for (var i = 0; i < entries.length; i++) { + var e = entries[i] + if (e.charAt(0) !== '.' || dotOk) { + var m + if (negate && !prefix) { + m = !e.match(pn) + } else { + m = e.match(pn) + } + if (m) + matchedEntries.push(e) + } + } - if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); + var len = matchedEntries.length + // If there are no matched entries, then nothing matches. + if (len === 0) + return - return stream.push(null); -} + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. -/***/ }), + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null) -/***/ 51080: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + if (prefix) { + if (prefix.slice(-1) !== '/') + e = prefix + '/' + e + else + e = prefix + e + } -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e) + } + this._emitMatch(index, e) + } + // This was the last one, and no stats were needed + return + } -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift() + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + var newPattern + if (prefix) + newPattern = [prefix, e] + else + newPattern = [e] + this._process(newPattern.concat(remain), index, inGlobStar) + } +} +GlobSync.prototype._emitMatch = function (index, e) { + if (isIgnored(this, e)) + return -/**/ + var abs = this._makeAbs(e) -var pna = __nccwpck_require__(13817); -/**/ + if (this.mark) + e = this._mark(e) -module.exports = Writable; + if (this.absolute) { + e = abs + } -/* */ -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} + if (this.matches[index][e]) + return -// It seems a linked list but it is not -// there will be only 2 of these for each stream -function CorkedRequest(state) { - var _this = this; + if (this.nodir) { + var c = this.cache[abs] + if (c === 'DIR' || Array.isArray(c)) + return + } - this.next = null; - this.entry = null; - this.finish = function () { - onCorkedFinish(_this, state); - }; + this.matches[index][e] = true + + if (this.stat) + this._stat(e) } -/* */ -/**/ -var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; -/**/ -/**/ -var Duplex; -/**/ +GlobSync.prototype._readdirInGlobStar = function (abs) { + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false) -Writable.WritableState = WritableState; + var entries + var lstat + var stat + try { + lstat = this.fs.lstatSync(abs) + } catch (er) { + if (er.code === 'ENOENT') { + // lstat failed, doesn't exist + return null + } + } -/**/ -var util = Object.create(__nccwpck_require__(32137)); -util.inherits = __nccwpck_require__(42991); -/**/ + var isSym = lstat && lstat.isSymbolicLink() + this.symlinks[abs] = isSym -/**/ -var internalUtil = { - deprecate: __nccwpck_require__(98485) -}; -/**/ + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) + this.cache[abs] = 'FILE' + else + entries = this._readdir(abs, false) -/**/ -var Stream = __nccwpck_require__(33182); -/**/ + return entries +} -/**/ +GlobSync.prototype._readdir = function (abs, inGlobStar) { + var entries -var Buffer = (__nccwpck_require__(37514).Buffer); -var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs) -/**/ + if (ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (!c || c === 'FILE') + return null -var destroyImpl = __nccwpck_require__(37421); + if (Array.isArray(c)) + return c + } -util.inherits(Writable, Stream); + try { + return this._readdirEntries(abs, this.fs.readdirSync(abs)) + } catch (er) { + this._readdirError(abs, er) + return null + } +} -function nop() {} +GlobSync.prototype._readdirEntries = function (abs, entries) { + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i] + if (abs === '/') + e = abs + e + else + e = abs + '/' + e + this.cache[e] = true + } + } -function WritableState(options, stream) { - Duplex = Duplex || __nccwpck_require__(57607); + this.cache[abs] = entries - options = options || {}; + // mark and cache dir-ness + return entries +} - // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - var isDuplex = stream instanceof Duplex; +GlobSync.prototype._readdirError = function (f, er) { + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f) + this.cache[abs] = 'FILE' + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd) + error.path = this.cwd + error.code = er.code + throw error + } + break - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false + break - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false + if (this.strict) + throw er + if (!this.silent) + console.error('glob error', er) + break + } +} - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var writableHwm = options.writableHighWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; +GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { - if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; + var entries = this._readdir(abs, inGlobStar) - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return - // if _final has been called - this.finalCalled = false; + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) - // drain event flag. - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false) - // has it been destroyed - this.destroyed = false; + var len = entries.length + var isSym = this.symlinks[abs] - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) + continue - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true) - // a flag to see when we're in the middle of a write. - this.writing = false; + var below = gspref.concat(entries[i], remain) + this._process(below, index, true) + } +} - // when true all writes will be buffered until .uncork() call - this.corked = 0; +GlobSync.prototype._processSimple = function (prefix, index) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var exists = this._stat(prefix) - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; + if (!this.matches[index]) + this.matches[index] = Object.create(null) - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; + // If it doesn't exist, then just mark the lack of results + if (!exists) + return - // the callback that's passed to _write(chunk,cb) - this.onwrite = function (er) { - onwrite(stream, er); - }; + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) + } else { + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' + } + } - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') - // the amount that is being written when _write is called. - this.writelen = 0; + // Mark this as a match + this._emitMatch(index, prefix) +} - this.bufferedRequest = null; - this.lastBufferedRequest = null; +// Returns either 'DIR', 'FILE', or false +GlobSync.prototype._stat = function (f) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; + if (f.length > this.maxLength) + return false - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; + if (Array.isArray(c)) + c = 'DIR' - // count buffered requests - this.bufferedRequestCount = 0; + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return c - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); -} + if (needDir && c === 'FILE') + return false -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. } - return out; -}; -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function () { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); + var exists + var stat = this.statCache[abs] + if (!stat) { + var lstat + try { + lstat = this.fs.lstatSync(abs) + } catch (er) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false + return false + } + } -// Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. -var realHasInstance; -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function (object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; - - return object && object._writableState instanceof WritableState; + if (lstat && lstat.isSymbolicLink()) { + try { + stat = this.fs.statSync(abs) + } catch (er) { + stat = lstat + } + } else { + stat = lstat } - }); -} else { - realHasInstance = function (object) { - return object instanceof this; - }; -} - -function Writable(options) { - Duplex = Duplex || __nccwpck_require__(57607); - - // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { - return new Writable(options); } - this._writableState = new WritableState(options, this); - - // legacy. - this.writable = true; - - if (options) { - if (typeof options.write === 'function') this._write = options.write; + this.statCache[abs] = stat - if (typeof options.writev === 'function') this._writev = options.writev; + var c = true + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE' - if (typeof options.destroy === 'function') this._destroy = options.destroy; + this.cache[abs] = this.cache[abs] || c - if (typeof options.final === 'function') this._final = options.final; - } + if (needDir && c === 'FILE') + return false - Stream.call(this); + return c } -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); -}; +GlobSync.prototype._mark = function (p) { + return common.mark(this, p) +} -function writeAfterEnd(stream, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - pna.nextTick(cb, er); +GlobSync.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) } -// Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. -function validChunk(stream, state, chunk, cb) { - var valid = true; - var er = false; - if (chunk === null) { - er = new TypeError('May not write null values to stream'); - } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - if (er) { - stream.emit('error', er); - pna.nextTick(cb, er); - valid = false; - } - return valid; -} +/***/ }), -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - var isBuf = !state.objectMode && _isUint8Array(chunk); +/***/ 5364: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop; - if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } +/**/ - return ret; +var pna = __nccwpck_require__(47810); +/**/ + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; }; +/**/ -Writable.prototype.cork = function () { - var state = this._writableState; +module.exports = Duplex; - state.corked++; -}; +/**/ +var util = Object.create(__nccwpck_require__(95898)); +util.inherits = __nccwpck_require__(44124); +/**/ -Writable.prototype.uncork = function () { - var state = this._writableState; +var Readable = __nccwpck_require__(19647); +var Writable = __nccwpck_require__(33369); - if (state.corked) { - state.corked--; +util.inherits(Duplex, Readable); - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); +{ + // avoid scope creep, the keys array can then be collected + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } -}; +} -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - return chunk; + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); } -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail @@ -53999,7616 +51973,4879 @@ Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { } }); -// if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } - var len = state.objectMode ? 1 : chunk.length; +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; - state.length += len; + // no more data can be written. + // But allow more writes to happen in this tick. + pna.nextTick(onEndNT, this); +} - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; +function onEndNT(self) { + self.end(); +} - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; +Object.defineProperty(Duplex.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined || this._writableState === undefined) { + return false; } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; } +}); - return ret; -} +Duplex.prototype._destroy = function (err, cb) { + this.push(null); + this.end(); -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} + pna.nextTick(cb, err); +}; -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; +/***/ }), - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - pna.nextTick(cb, er); - // this can emit finish, and it will always happen - // after error - pna.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - stream.emit('error', er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - stream.emit('error', er); - // this can emit finish, but finish must - // always follow error - finishMaybe(stream, state); - } -} +/***/ 47905: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. - onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state); - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } +module.exports = PassThrough; - if (sync) { - /**/ - asyncWrite(afterWrite, stream, state, finished, cb); - /**/ - } else { - afterWrite(stream, state, finished, cb); - } - } -} +var Transform = __nccwpck_require__(95401); -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} +/**/ +var util = Object.create(__nccwpck_require__(95898)); +util.inherits = __nccwpck_require__(44124); +/**/ -// Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} +util.inherits(PassThrough, Transform); -// if there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; + Transform.call(this, options); +} - var count = 0; - var allBuffers = true; - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - buffer.allBuffers = allBuffers; +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); +/***/ }), - // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; +/***/ 19647: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - break; - } - } +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - if (entry === null) state.lastBufferedRequest = null; - } - state.bufferedRequest = entry; - state.bufferProcessing = false; -} -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new Error('_write() is not implemented')); -}; +/**/ -Writable.prototype._writev = null; +var pna = __nccwpck_require__(47810); +/**/ -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; +module.exports = Readable; - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } +/**/ +var isArray = __nccwpck_require__(20893); +/**/ - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); +/**/ +var Duplex; +/**/ - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } +Readable.ReadableState = ReadableState; - // ignore unnecessary end() calls. - if (!state.ending) endWritable(this, state, cb); +/**/ +var EE = (__nccwpck_require__(82361).EventEmitter); + +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; }; +/**/ -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +/**/ +var Stream = __nccwpck_require__(41715); +/**/ + +/**/ + +var Buffer = (__nccwpck_require__(36476).Buffer); +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); } -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - if (err) { - stream.emit('error', err); - } - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function') { - state.pendingcb++; - state.finalCalled = true; - pna.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } -} - -function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - prefinish(stream, state); - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - } - } - return need; +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); - } - state.ended = true; - stream.writable = false; -} +/**/ -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } +/**/ +var util = Object.create(__nccwpck_require__(95898)); +util.inherits = __nccwpck_require__(44124); +/**/ - // reuse the free corkReq. - state.corkedRequestsFree.next = corkReq; +/**/ +var debugUtil = __nccwpck_require__(73837); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; } +/**/ -Object.defineProperty(Writable.prototype, 'destroyed', { - get: function () { - if (this._writableState === undefined) { - return false; - } - return this._writableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } +var BufferList = __nccwpck_require__(37898); +var destroyImpl = __nccwpck_require__(71890); +var StringDecoder; - // backward compatibility, the user is explicitly - // managing destroyed - this._writableState.destroyed = value; - } -}); +util.inherits(Readable, Stream); -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; -Writable.prototype._destroy = function (err, cb) { - this.end(); - cb(err); -}; +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; -/***/ }), +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); -/***/ 64194: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} -"use strict"; +function ReadableState(options, stream) { + Duplex = Duplex || __nccwpck_require__(5364); + options = options || {}; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; -var Buffer = (__nccwpck_require__(37514).Buffer); -var util = __nccwpck_require__(73837); + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; -function copyBuffer(src, target, offset) { - src.copy(target, offset); -} + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; -module.exports = function () { - function BufferList() { - _classCallCheck(this, BufferList); + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var readableHwm = options.readableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.head = null; - this.tail = null; - this.length = 0; - } + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; - BufferList.prototype.push = function push(v) { - var entry = { data: v, next: null }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - }; + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); - BufferList.prototype.unshift = function unshift(v) { - var entry = { data: v, next: this.head }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - }; + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; - BufferList.prototype.shift = function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - }; + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; - BufferList.prototype.clear = function clear() { - this.head = this.tail = null; - this.length = 0; - }; + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; - BufferList.prototype.join = function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - while (p = p.next) { - ret += s + p.data; - }return ret; - }; + // has it been destroyed + this.destroyed = false; - BufferList.prototype.concat = function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - return ret; - }; + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - return BufferList; -}(); + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; -if (util && util.inspect && util.inspect.custom) { - module.exports.prototype[util.inspect.custom] = function () { - var obj = util.inspect({ length: this.length }); - return this.constructor.name + ' ' + obj; - }; -} + // if true, a maybeReadMore has been scheduled + this.readingMore = false; -/***/ }), + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = (__nccwpck_require__(99708)/* .StringDecoder */ .s); + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} -/***/ 37421: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function Readable(options) { + Duplex = Duplex || __nccwpck_require__(5364); -"use strict"; + if (!(this instanceof Readable)) return new Readable(options); + this._readableState = new ReadableState(options, this); -/**/ + // legacy + this.readable = true; -var pna = __nccwpck_require__(13817); -/**/ + if (options) { + if (typeof options.read === 'function') this._read = options.read; -// undocumented cb() API, needed for core, not for public API -function destroy(err, cb) { - var _this = this; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; + Stream.call(this); +} - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - pna.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - pna.nextTick(emitErrorNT, this, err); - } +Object.defineProperty(Readable.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; } - return this; + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; } +}); - // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - if (this._readableState) { - this._readableState.destroyed = true; - } +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + this.push(null); + cb(err); +}; - // if this is a duplex stream mark the writable part as destroyed as well - if (this._writableState) { - this._writableState.destroyed = true; - } +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - pna.nextTick(emitErrorNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - pna.nextTick(emitErrorNT, _this, err); + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; } - } else if (cb) { - cb(err); + skipChunkCheck = true; } - }); - - return this; -} - -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; + } else { + skipChunkCheck = true; } -} - -function emitErrorNT(self, err) { - self.emit('error', err); -} -module.exports = { - destroy: destroy, - undestroy: undestroy + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); }; -/***/ }), - -/***/ 33182: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = __nccwpck_require__(12781); - +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; -/***/ }), +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } -/***/ 93130: -/***/ ((module, exports, __nccwpck_require__) => { + if (addToFront) { + if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit('error', new Error('stream.push() after EOF')); + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + } + } -var Stream = __nccwpck_require__(12781); -if (process.env.READABLE_STREAM === 'disable' && Stream) { - module.exports = Stream; - exports = module.exports = Stream.Readable; - exports.Readable = Stream.Readable; - exports.Writable = Stream.Writable; - exports.Duplex = Stream.Duplex; - exports.Transform = Stream.Transform; - exports.PassThrough = Stream.PassThrough; - exports.Stream = Stream; -} else { - exports = module.exports = __nccwpck_require__(63037); - exports.Stream = Stream || exports; - exports.Readable = exports; - exports.Writable = __nccwpck_require__(51080); - exports.Duplex = __nccwpck_require__(57607); - exports.Transform = __nccwpck_require__(79994); - exports.PassThrough = __nccwpck_require__(63656); + return needMoreData(state); } +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); -/***/ }), - -/***/ 37514: -/***/ ((module, exports, __nccwpck_require__) => { - -/* eslint-disable node/no-deprecated-api */ -var buffer = __nccwpck_require__(14300) -var Buffer = buffer.Buffer - -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] + if (state.needReadable) emitReadable(stream); } + maybeReadMore(stream, state); } -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer + +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; } -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); } -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = (__nccwpck_require__(99708)/* .StringDecoder */ .s); + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; } else { - buf.fill(0) + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; } - return buf + return n; } -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; } - return Buffer(size) -} - -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; } - return buffer.SlowBuffer(size) + return state.length; } +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; -/***/ }), - -/***/ 50823: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (n !== 0) state.emittedReadable = false; -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + n = howMuchToRead(n, state); + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } -/**/ + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. -var Buffer = (__nccwpck_require__(37514).Buffer); -/**/ + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); -var isEncoding = Buffer.isEncoding || function (encoding) { - encoding = '' + encoding; - switch (encoding && encoding.toLowerCase()) { - case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': - return true; - default: - return false; + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); } -}; -function _normalizeEncoding(enc) { - if (!enc) return 'utf8'; - var retried; - while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; - } + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); } -}; - -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; -} -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.s = StringDecoder; -function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case 'utf16le': - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case 'utf8': - this.fillLast = utf8FillLast; - nb = 4; - break; - case 'base64': - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer.allocUnsafe(nb); -} + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; -StringDecoder.prototype.write = function (buf) { - if (buf.length === 0) return ''; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ''; - i = this.lastNeed; - this.lastNeed = 0; + if (ret === null) { + state.needReadable = true; + n = 0; } else { - i = 0; + state.length -= n; } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; -}; - -StringDecoder.prototype.end = utf8End; -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; -}; -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. If an invalid byte is detected, -2 is returned. -function utf8CheckByte(byte) { - if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return byte >> 6 === 0x02 ? -1 : -2; -} + if (ret !== null) this.emit('data', ret); -// Checks at most 3 bytes at the end of a Buffer in order to detect an -// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) -// needed to complete the UTF-8 character (if applicable) are returned. -function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; - } - return nb; - } - return 0; -} + return ret; +}; -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding -// behavior. The continuation byte check is included three times in the case -// where all of the continuation bytes for a character exist in the same buffer. -// It is also done this way as a slight performance increase instead of using a -// loop. -function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xC0) !== 0x80) { - self.lastNeed = 0; - return '\ufffd'; - } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'; - } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'; - } +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; } } -} - -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; -} - -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -function utf8Text(buf, i) { - var total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString('utf8', i); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString('utf8', i, end); -} + state.ended = true; -// For UTF-8, a replacement character is added when ending on a partial -// character. -function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'; - return r; + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); } -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -function utf16Text(buf, i) { - if ((buf.length - i) % 2 === 0) { - var r = buf.toString('utf16le', i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 0xD800 && c <= 0xDBFF) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } - } - return r; +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); } -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString('utf16le', 0, end); - } - return r; +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); } -function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString('base64', i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + pna.nextTick(maybeReadMore_, stream, state); } - return buf.toString('base64', i, buf.length - n); -} - -function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); - return r; -} - -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); } -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; } -/***/ }), - -/***/ 71160: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/** - * Archiver Vending - * - * @ignore - * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} - * @copyright (c) 2012-2014 Chris Talkington, contributors. - */ -var Archiver = __nccwpck_require__(90936); - -var formats = {}; - -/** - * Dispenses a new Archiver instance. - * - * @constructor - * @param {String} format The archive format to use. - * @param {Object} options See [Archiver]{@link Archiver} - * @return {Archiver} - */ -var vending = function(format, options) { - return vending.create(format, options); +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('_read() is not implemented')); }; -/** - * Creates a new Archiver instance. - * - * @param {String} format The archive format to use. - * @param {Object} options See [Archiver]{@link Archiver} - * @return {Archiver} - */ -vending.create = function(format, options) { - if (formats[format]) { - var instance = new Archiver(format, options); - instance.setFormat(format); - instance.setModule(new formats[format](options)); +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; - return instance; - } else { - throw new Error('create(' + format + '): format not registered'); + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; } -}; + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); -/** - * Registers a format for use with archiver. - * - * @param {String} format The name of the format. - * @param {Function} module The function for archiver to interact with. - * @return void - */ -vending.registerFormat = function(format, module) { - if (formats[format]) { - throw new Error('register(' + format + '): format already registered'); - } + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - if (typeof module !== 'function') { - throw new Error('register(' + format + '): format module invalid'); - } + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); - if (typeof module.prototype.append !== 'function' || typeof module.prototype.finalize !== 'function') { - throw new Error('register(' + format + '): format module missing methods'); + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } } - formats[format] = module; -}; - -/** - * Check if the format is already registered. - * - * @param {String} format the name of the format. - * @return boolean - */ -vending.isRegisteredFormat = function (format) { - if (formats[format]) { - return true; + function onend() { + debug('onend'); + dest.end(); } - - return false; -}; -vending.registerFormat('zip', __nccwpck_require__(36926)); -vending.registerFormat('tar', __nccwpck_require__(4134)); -vending.registerFormat('json', __nccwpck_require__(86239)); - -module.exports = vending; + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); -/***/ }), + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); -/***/ 90936: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + cleanedUp = true; -/** - * Archiver Core - * - * @ignore - * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} - * @copyright (c) 2012-2014 Chris Talkington, contributors. - */ -var fs = __nccwpck_require__(57147); -var glob = __nccwpck_require__(84797); -var async = __nccwpck_require__(81073); -var path = __nccwpck_require__(71017); -var util = __nccwpck_require__(9925); - -var inherits = (__nccwpck_require__(73837).inherits); -var ArchiverError = __nccwpck_require__(18976); -var Transform = (__nccwpck_require__(84123).Transform); - -var win32 = process.platform === 'win32'; - -/** - * @constructor - * @param {String} format The archive format to use. - * @param {(CoreOptions|TransformOptions)} options See also {@link ZipOptions} and {@link TarOptions}. - */ -var Archiver = function(format, options) { - if (!(this instanceof Archiver)) { - return new Archiver(format, options); + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } - if (typeof format !== 'string') { - options = format; - format = 'zip'; + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } } - options = this.options = util.defaults(options, { - highWaterMark: 1024 * 1024, - statConcurrency: 4 - }); - - Transform.call(this, options); + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } - this._format = false; - this._module = false; - this._pending = 0; - this._pointer = 0; + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); - this._entriesCount = 0; - this._entriesProcessedCount = 0; - this._fsEntriesTotalBytes = 0; - this._fsEntriesProcessedBytes = 0; + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); - this._queue = async.queue(this._onQueueTask.bind(this), 1); - this._queue.drain(this._onQueueDrain.bind(this)); + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } - this._statQueue = async.queue(this._onStatQueueTask.bind(this), options.statConcurrency); - this._statQueue.drain(this._onQueueDrain.bind(this)); + // tell the dest that it's being piped to + dest.emit('pipe', src); - this._state = { - aborted: false, - finalize: false, - finalizing: false, - finalized: false, - modulePiped: false - }; + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } - this._streams = []; + return dest; }; -inherits(Archiver, Transform); +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} -/** - * Internal logic for `abort`. - * - * @private - * @return void - */ -Archiver.prototype._abort = function() { - this._state.aborted = true; - this._queue.kill(); - this._statQueue.kill(); +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; - if (this._queue.idle()) { - this._shutdown(); - } -}; + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; -/** - * Internal helper for appending files. - * - * @private - * @param {String} filepath The source filepath. - * @param {EntryData} data The entry data. - * @return void - */ -Archiver.prototype._append = function(filepath, data) { - data = data || {}; + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; - var task = { - source: null, - filepath: filepath - }; + if (!dest) dest = state.pipes; - if (!data.name) { - data.name = filepath; + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; } - data.sourcePath = filepath; - task.data = data; - this._entriesCount++; + // slow case. multiple pipe destinations. - if (data.stats && data.stats instanceof fs.Stats) { - task = this._updateQueueTaskWithStats(task, data.stats); - if (task) { - if (data.stats.size) { - this._fsEntriesTotalBytes += data.stats.size; - } + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; - this._queue.push(task); - } - } else { - this._statQueue.push(task); + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, { hasUnpiped: false }); + }return this; } -}; -/** - * Internal logic for `finalize`. - * - * @private - * @return void - */ -Archiver.prototype._finalize = function() { - if (this._state.finalizing || this._state.finalized || this._state.aborted) { - return; - } + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; - this._state.finalizing = true; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; - this._moduleFinalize(); + dest.emit('unpipe', this, unpipeInfo); - this._state.finalizing = false; - this._state.finalized = true; + return this; }; -/** - * Checks the various state variables to determine if we can `finalize`. - * - * @private - * @return {Boolean} - */ -Archiver.prototype._maybeFinalize = function() { - if (this._state.finalizing || this._state.finalized || this._state.aborted) { - return false; - } +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); - if (this._state.finalize && this._pending === 0 && this._queue.idle() && this._statQueue.idle()) { - this._finalize(); - return true; + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + pna.nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } } - return false; + return res; }; +Readable.prototype.addListener = Readable.prototype.on; -/** - * Appends an entry to the module. - * - * @private - * @fires Archiver#entry - * @param {(Buffer|Stream)} source - * @param {EntryData} data - * @param {Function} callback - * @return void - */ -Archiver.prototype._moduleAppend = function(source, data, callback) { - if (this._state.aborted) { - callback(); - return; - } - - this._module.append(source, data, function(err) { - this._task = null; - - if (this._state.aborted) { - this._shutdown(); - return; - } - - if (err) { - this.emit('error', err); - setImmediate(callback); - return; - } +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} - /** - * Fires when the entry's input has been processed and appended to the archive. - * - * @event Archiver#entry - * @type {EntryData} - */ - this.emit('entry', data); - this._entriesProcessedCount++; +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; - if (data.stats && data.stats.size) { - this._fsEntriesProcessedBytes += data.stats.size; - } +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + pna.nextTick(resume_, stream, state); + } +} - /** - * @event Archiver#progress - * @type {ProgressData} - */ - this.emit('progress', { - entries: { - total: this._entriesCount, - processed: this._entriesProcessedCount - }, - fs: { - totalBytes: this._fsEntriesTotalBytes, - processedBytes: this._fsEntriesProcessedBytes - } - }); +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } - setImmediate(callback); - }.bind(this)); -}; + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} -/** - * Finalizes the module. - * - * @private - * @return void - */ -Archiver.prototype._moduleFinalize = function() { - if (typeof this._module.finalize === 'function') { - this._module.finalize(); - } else if (typeof this._module.end === 'function') { - this._module.end(); - } else { - this.emit('error', new ArchiverError('NOENDMETHOD')); +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); } + return this; }; -/** - * Pipes the module to our internal stream with error bubbling. - * - * @private - * @return void - */ -Archiver.prototype._modulePipe = function() { - this._module.on('error', this._onModuleError.bind(this)); - this._module.pipe(this); - this._state.modulePiped = true; -}; +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} -/** - * Determines if the current module supports a defined feature. - * - * @private - * @param {String} key - * @return {Boolean} - */ -Archiver.prototype._moduleSupports = function(key) { - if (!this._module.supports || !this._module.supports[key]) { - return false; - } +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; - return this._module.supports[key]; -}; + var state = this._readableState; + var paused = false; -/** - * Unpipes the module from our internal stream. - * - * @private - * @return void - */ -Archiver.prototype._moduleUnpipe = function() { - this._module.unpipe(this); - this._state.modulePiped = false; -}; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } -/** - * Normalizes entry data with fallbacks for key properties. - * - * @private - * @param {Object} data - * @param {fs.Stats} stats - * @return {Object} - */ -Archiver.prototype._normalizeEntryData = function(data, stats) { - data = util.defaults(data, { - type: 'file', - name: null, - date: null, - mode: null, - prefix: null, - sourcePath: null, - stats: false + _this.push(null); }); - if (stats && data.stats === false) { - data.stats = stats; - } + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); - var isDir = data.type === 'directory'; + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - if (data.name) { - if (typeof data.prefix === 'string' && '' !== data.prefix) { - data.name = data.prefix + '/' + data.name; - data.prefix = null; + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); } + }); - data.name = util.sanitizePath(data.name); - - if (data.type !== 'symlink' && data.name.slice(-1) === '/') { - isDir = true; - data.type = 'directory'; - } else if (isDir) { - data.name += '/'; + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); } } - // 511 === 0777; 493 === 0755; 438 === 0666; 420 === 0644 - if (typeof data.mode === 'number') { - if (win32) { - data.mode &= 511; - } else { - data.mode &= 4095 - } - } else if (data.stats && data.mode === null) { - if (win32) { - data.mode = data.stats.mode & 511; - } else { - data.mode = data.stats.mode & 4095; - } + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } - // stat isn't reliable on windows; force 0755 for dir - if (win32 && isDir) { - data.mode = 493; + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); } - } else if (data.mode === null) { - data.mode = isDir ? 493 : 420; - } + }; - if (data.stats && data.date === null) { - data.date = data.stats.mtime; - } else { - data.date = util.dateify(data.date); + return this; +}; + +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._readableState.highWaterMark; } +}); - return data; -}; +// exposed for testing purposes only. +Readable._fromList = fromList; -/** - * Error listener that re-emits error on to our internal stream. - * - * @private - * @param {Error} err - * @return void - */ -Archiver.prototype._onModuleError = function(err) { - /** - * @event Archiver#error - * @type {ErrorData} - */ - this.emit('error', err); -}; +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; -/** - * Checks the various state variables after queue has drained to determine if - * we need to `finalize`. - * - * @private - * @return void - */ -Archiver.prototype._onQueueDrain = function() { - if (this._state.finalizing || this._state.finalized || this._state.aborted) { - return; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); } - if (this._state.finalize && this._pending === 0 && this._queue.idle() && this._statQueue.idle()) { - this._finalize(); + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); } -}; + return ret; +} -/** - * Appends each queue task to the module. - * - * @private - * @param {Object} task - * @param {Function} callback - * @return void - */ -Archiver.prototype._onQueueTask = function(task, callback) { - var fullCallback = () => { - if(task.data.callback) { - task.data.callback(); +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; } - callback(); + ++c; } + list.length -= c; + return ret; +} - if (this._state.finalizing || this._state.finalized || this._state.aborted) { - fullCallback(); - return; +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; } + list.length -= c; + return ret; +} - this._task = task; - this._moduleAppend(task.source, task.data, fullCallback); -}; +function endReadable(stream) { + var state = stream._readableState; -/** - * Performs a file stat and reinjects the task back into the queue. - * - * @private - * @param {Object} task - * @param {Function} callback - * @return void - */ -Archiver.prototype._onStatQueueTask = function(task, callback) { - if (this._state.finalizing || this._state.finalized || this._state.aborted) { - callback(); - return; + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + pna.nextTick(endReadableNT, state, stream); } +} - fs.lstat(task.filepath, function(err, stats) { - if (this._state.aborted) { - setImmediate(callback); - return; - } +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} - if (err) { - this._entriesCount--; +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} - /** - * @event Archiver#warning - * @type {ErrorData} - */ - this.emit('warning', err); - setImmediate(callback); - return; - } +/***/ }), - task = this._updateQueueTaskWithStats(task, stats); +/***/ 95401: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (task) { - if (stats.size) { - this._fsEntriesTotalBytes += stats.size; - } +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - this._queue.push(task); - } +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. - setImmediate(callback); - }.bind(this)); -}; -/** - * Unpipes the module and ends our internal stream. - * - * @private - * @return void - */ -Archiver.prototype._shutdown = function() { - this._moduleUnpipe(); - this.end(); -}; -/** - * Tracks the bytes emitted by our internal stream. - * - * @private - * @param {Buffer} chunk - * @param {String} encoding - * @param {Function} callback - * @return void - */ -Archiver.prototype._transform = function(chunk, encoding, callback) { - if (chunk) { - this._pointer += chunk.length; - } +module.exports = Transform; - callback(null, chunk); -}; +var Duplex = __nccwpck_require__(5364); -/** - * Updates and normalizes a queue task using stats data. - * - * @private - * @param {Object} task - * @param {fs.Stats} stats - * @return {Object} - */ -Archiver.prototype._updateQueueTaskWithStats = function(task, stats) { - if (stats.isFile()) { - task.data.type = 'file'; - task.data.sourceType = 'stream'; - task.source = util.lazyReadStream(task.filepath); - } else if (stats.isDirectory() && this._moduleSupports('directory')) { - task.data.name = util.trailingSlashIt(task.data.name); - task.data.type = 'directory'; - task.data.sourcePath = util.trailingSlashIt(task.filepath); - task.data.sourceType = 'buffer'; - task.source = Buffer.concat([]); - } else if (stats.isSymbolicLink() && this._moduleSupports('symlink')) { - var linkPath = fs.readlinkSync(task.filepath); - var dirName = path.dirname(task.filepath); - task.data.type = 'symlink'; - task.data.linkname = path.relative(dirName, path.resolve(dirName, linkPath)); - task.data.sourceType = 'buffer'; - task.source = Buffer.concat([]); - } else { - if (stats.isDirectory()) { - this.emit('warning', new ArchiverError('DIRECTORYNOTSUPPORTED', task.data)); - } else if (stats.isSymbolicLink()) { - this.emit('warning', new ArchiverError('SYMLINKNOTSUPPORTED', task.data)); - } else { - this.emit('warning', new ArchiverError('ENTRYNOTSUPPORTED', task.data)); - } +/**/ +var util = Object.create(__nccwpck_require__(95898)); +util.inherits = __nccwpck_require__(44124); +/**/ - return null; - } +util.inherits(Transform, Duplex); - task.data = this._normalizeEntryData(task.data, stats); +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; - return task; -}; + var cb = ts.writecb; -/** - * Aborts the archiving process, taking a best-effort approach, by: - * - * - removing any pending queue tasks - * - allowing any active queue workers to finish - * - detaching internal module pipes - * - ending both sides of the Transform stream - * - * It will NOT drain any remaining sources. - * - * @return {this} - */ -Archiver.prototype.abort = function() { - if (this._state.aborted || this._state.finalized) { - return this; + if (!cb) { + return this.emit('error', new Error('write callback called multiple times')); } - this._abort(); - - return this; -}; + ts.writechunk = null; + ts.writecb = null; -/** - * Appends an input source (text string, buffer, or stream) to the instance. - * - * When the instance has received, processed, and emitted the input, the `entry` - * event is fired. - * - * @fires Archiver#entry - * @param {(Buffer|Stream|String)} source The input source. - * @param {EntryData} data See also {@link ZipEntryData} and {@link TarEntryData}. - * @return {this} - */ -Archiver.prototype.append = function(source, data) { - if (this._state.finalize || this._state.aborted) { - this.emit('error', new ArchiverError('QUEUECLOSED')); - return this; - } + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); - data = this._normalizeEntryData(data); + cb(er); - if (typeof data.name !== 'string' || data.name.length === 0) { - this.emit('error', new ArchiverError('ENTRYNAMEREQUIRED')); - return this; + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); } +} - if (data.type === 'directory' && !this._moduleSupports('directory')) { - this.emit('error', new ArchiverError('DIRECTORYNOTSUPPORTED', { name: data.name })); - return this; - } +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); - source = util.normalizeInputSource(source); + Duplex.call(this, options); - if (Buffer.isBuffer(source)) { - data.sourceType = 'buffer'; - } else if (util.isStream(source)) { - data.sourceType = 'stream'; - } else { - this.emit('error', new ArchiverError('INPUTSTEAMBUFFERREQUIRED', { name: data.name })); - return this; - } + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; - this._entriesCount++; - this._queue.push({ - data: data, - source: source - }); + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; - return this; -}; + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; -/** - * Appends a directory and its files, recursively, given its dirpath. - * - * @param {String} dirpath The source directory path. - * @param {String} destpath The destination path within the archive. - * @param {(EntryData|Function)} data See also [ZipEntryData]{@link ZipEntryData} and - * [TarEntryData]{@link TarEntryData}. - * @return {this} - */ -Archiver.prototype.directory = function(dirpath, destpath, data) { - if (this._state.finalize || this._state.aborted) { - this.emit('error', new ArchiverError('QUEUECLOSED')); - return this; - } + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof dirpath !== 'string' || dirpath.length === 0) { - this.emit('error', new ArchiverError('DIRECTORYDIRPATHREQUIRED')); - return this; + if (typeof options.flush === 'function') this._flush = options.flush; } - this._pending++; + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); +} - if (destpath === false) { - destpath = ''; - } else if (typeof destpath !== 'string'){ - destpath = dirpath; - } +function prefinish() { + var _this = this; - var dataFunction = false; - if (typeof data === 'function') { - dataFunction = data; - data = {}; - } else if (typeof data !== 'object') { - data = {}; + if (typeof this._flush === 'function') { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); } +} - var globOptions = { - stat: true, - dot: true - }; +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; - function onGlobEnd() { - this._pending--; - this._maybeFinalize(); - } +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('_transform() is not implemented'); +}; - function onGlobError(err) { - this.emit('error', err); +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } +}; - function onGlobMatch(match){ - globber.pause(); +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; - var ignoreMatch = false; - var entryData = Object.assign({}, data); - entryData.name = match.relative; - entryData.prefix = destpath; - entryData.stats = match.stat; - entryData.callback = globber.resume.bind(globber); - - try { - if (dataFunction) { - entryData = dataFunction(entryData); - - if (entryData === false) { - ignoreMatch = true; - } else if (typeof entryData !== 'object') { - throw new ArchiverError('DIRECTORYFUNCTIONINVALIDDATA', { dirpath: dirpath }); - } - } - } catch(e) { - this.emit('error', e); - return; - } - - if (ignoreMatch) { - globber.resume(); - return; - } - - this._append(match.absolute, entryData); + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; } +}; - var globber = glob(dirpath, globOptions); - globber.on('error', onGlobError.bind(this)); - globber.on('match', onGlobMatch.bind(this)); - globber.on('end', onGlobEnd.bind(this)); +Transform.prototype._destroy = function (err, cb) { + var _this2 = this; - return this; + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + _this2.emit('close'); + }); }; -/** - * Appends a file given its filepath using a - * [lazystream]{@link https://github.com/jpommerening/node-lazystream} wrapper to - * prevent issues with open file limits. - * - * When the instance has received, processed, and emitted the file, the `entry` - * event is fired. - * - * @param {String} filepath The source filepath. - * @param {EntryData} data See also [ZipEntryData]{@link ZipEntryData} and - * [TarEntryData]{@link TarEntryData}. - * @return {this} - */ -Archiver.prototype.file = function(filepath, data) { - if (this._state.finalize || this._state.aborted) { - this.emit('error', new ArchiverError('QUEUECLOSED')); - return this; - } - - if (typeof filepath !== 'string' || filepath.length === 0) { - this.emit('error', new ArchiverError('FILEFILEPATHREQUIRED')); - return this; - } +function done(stream, er, data) { + if (er) return stream.emit('error', er); - this._append(filepath, data); + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); - return this; -}; + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); -/** - * Appends multiple files that match a glob pattern. - * - * @param {String} pattern The [glob pattern]{@link https://github.com/isaacs/minimatch} to match. - * @param {Object} options See [node-readdir-glob]{@link https://github.com/yqnn/node-readdir-glob#options}. - * @param {EntryData} data See also [ZipEntryData]{@link ZipEntryData} and - * [TarEntryData]{@link TarEntryData}. - * @return {this} - */ -Archiver.prototype.glob = function(pattern, options, data) { - this._pending++; + if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); - options = util.defaults(options, { - stat: true, - pattern: pattern - }); + return stream.push(null); +} - function onGlobEnd() { - this._pending--; - this._maybeFinalize(); - } +/***/ }), - function onGlobError(err) { - this.emit('error', err); - } +/***/ 33369: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function onGlobMatch(match){ - globber.pause(); - var entryData = Object.assign({}, data); - entryData.callback = globber.resume.bind(globber); - entryData.stats = match.stat; - entryData.name = match.relative; +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - this._append(match.absolute, entryData); - } +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. - var globber = glob(options.cwd || '.', options); - globber.on('error', onGlobError.bind(this)); - globber.on('match', onGlobMatch.bind(this)); - globber.on('end', onGlobEnd.bind(this)); - return this; -}; -/** - * Finalizes the instance and prevents further appending to the archive - * structure (queue will continue til drained). - * - * The `end`, `close` or `finish` events on the destination stream may fire - * right after calling this method so you should set listeners beforehand to - * properly detect stream completion. - * - * @return {Promise} - */ -Archiver.prototype.finalize = function() { - if (this._state.aborted) { - var abortedError = new ArchiverError('ABORTED'); - this.emit('error', abortedError); - return Promise.reject(abortedError); - } +/**/ - if (this._state.finalize) { - var finalizingError = new ArchiverError('FINALIZING'); - this.emit('error', finalizingError); - return Promise.reject(finalizingError); - } +var pna = __nccwpck_require__(47810); +/**/ - this._state.finalize = true; +module.exports = Writable; - if (this._pending === 0 && this._queue.idle() && this._statQueue.idle()) { - this._finalize(); - } +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} - var self = this; +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; - return new Promise(function(resolve, reject) { - var errored; + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ - self._module.on('end', function() { - if (!errored) { - resolve(); - } - }) +/**/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; +/**/ - self._module.on('error', function(err) { - errored = true; - reject(err); - }) - }) -}; +/**/ +var Duplex; +/**/ -/** - * Sets the module format name used for archiving. - * - * @param {String} format The name of the format. - * @return {this} - */ -Archiver.prototype.setFormat = function(format) { - if (this._format) { - this.emit('error', new ArchiverError('FORMATSET')); - return this; - } +Writable.WritableState = WritableState; - this._format = format; +/**/ +var util = Object.create(__nccwpck_require__(95898)); +util.inherits = __nccwpck_require__(44124); +/**/ - return this; +/**/ +var internalUtil = { + deprecate: __nccwpck_require__(65278) }; +/**/ -/** - * Sets the module used for archiving. - * - * @param {Function} module The function for archiver to interact with. - * @return {this} - */ -Archiver.prototype.setModule = function(module) { - if (this._state.aborted) { - this.emit('error', new ArchiverError('ABORTED')); - return this; - } - - if (this._state.module) { - this.emit('error', new ArchiverError('MODULESET')); - return this; - } +/**/ +var Stream = __nccwpck_require__(41715); +/**/ - this._module = module; - this._modulePipe(); +/**/ - return this; -}; +var Buffer = (__nccwpck_require__(36476).Buffer); +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} -/** - * Appends a symlink to the instance. - * - * This does NOT interact with filesystem and is used for programmatically creating symlinks. - * - * @param {String} filepath The symlink path (within archive). - * @param {String} target The target path (within archive). - * @param {Number} mode Sets the entry permissions. - * @return {this} - */ -Archiver.prototype.symlink = function(filepath, target, mode) { - if (this._state.finalize || this._state.aborted) { - this.emit('error', new ArchiverError('QUEUECLOSED')); - return this; - } +/**/ - if (typeof filepath !== 'string' || filepath.length === 0) { - this.emit('error', new ArchiverError('SYMLINKFILEPATHREQUIRED')); - return this; - } +var destroyImpl = __nccwpck_require__(71890); - if (typeof target !== 'string' || target.length === 0) { - this.emit('error', new ArchiverError('SYMLINKTARGETREQUIRED', { filepath: filepath })); - return this; - } +util.inherits(Writable, Stream); - if (!this._moduleSupports('symlink')) { - this.emit('error', new ArchiverError('SYMLINKNOTSUPPORTED', { filepath: filepath })); - return this; - } +function nop() {} - var data = {}; - data.type = 'symlink'; - data.name = filepath.replace(/\\/g, '/'); - data.linkname = target.replace(/\\/g, '/'); - data.sourceType = 'buffer'; +function WritableState(options, stream) { + Duplex = Duplex || __nccwpck_require__(5364); - if (typeof mode === "number") { - data.mode = mode; - } + options = options || {}; - this._entriesCount++; - this._queue.push({ - data: data, - source: Buffer.concat([]) - }); + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; - return this; -}; + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; -/** - * Returns the current length (in bytes) that has been emitted. - * - * @return {Number} - */ -Archiver.prototype.pointer = function() { - return this._pointer; -}; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; -/** - * Middleware-like helper that has yet to be fully implemented. - * - * @private - * @param {Function} plugin - * @return {this} - */ -Archiver.prototype.use = function(plugin) { - this._streams.push(plugin); - return this; -}; + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var writableHwm = options.writableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; -module.exports = Archiver; + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; -/** - * @typedef {Object} CoreOptions - * @global - * @property {Number} [statConcurrency=4] Sets the number of workers used to - * process the internal fs stat queue. - */ + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); -/** - * @typedef {Object} TransformOptions - * @property {Boolean} [allowHalfOpen=true] If set to false, then the stream - * will automatically end the readable side when the writable side ends and vice - * versa. - * @property {Boolean} [readableObjectMode=false] Sets objectMode for readable - * side of the stream. Has no effect if objectMode is true. - * @property {Boolean} [writableObjectMode=false] Sets objectMode for writable - * side of the stream. Has no effect if objectMode is true. - * @property {Boolean} [decodeStrings=true] Whether or not to decode strings - * into Buffers before passing them to _write(). `Writable` - * @property {String} [encoding=NULL] If specified, then buffers will be decoded - * to strings using the specified encoding. `Readable` - * @property {Number} [highWaterMark=16kb] The maximum number of bytes to store - * in the internal buffer before ceasing to read from the underlying resource. - * `Readable` `Writable` - * @property {Boolean} [objectMode=false] Whether this stream should behave as a - * stream of objects. Meaning that stream.read(n) returns a single value instead - * of a Buffer of size n. `Readable` `Writable` - */ + // if _final has been called + this.finalCalled = false; -/** - * @typedef {Object} EntryData - * @property {String} name Sets the entry name including internal path. - * @property {(String|Date)} [date=NOW()] Sets the entry date. - * @property {Number} [mode=D:0755/F:0644] Sets the entry permissions. - * @property {String} [prefix] Sets a path prefix for the entry name. Useful - * when working with methods like `directory` or `glob`. - * @property {fs.Stats} [stats] Sets the fs stat data for this entry allowing - * for reduction of fs stat calls when stat data is already known. - */ + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; -/** - * @typedef {Object} ErrorData - * @property {String} message The message of the error. - * @property {String} code The error code assigned to this error. - * @property {String} data Additional data provided for reporting or debugging (where available). - */ + // has it been destroyed + this.destroyed = false; -/** - * @typedef {Object} ProgressData - * @property {Object} entries - * @property {Number} entries.total Number of entries that have been appended. - * @property {Number} entries.processed Number of entries that have been processed. - * @property {Object} fs - * @property {Number} fs.totalBytes Number of bytes that have been appended. Calculated asynchronously and might not be accurate: it growth while entries are added. (based on fs.Stats) - * @property {Number} fs.processedBytes Number of bytes that have been processed. (based on fs.Stats) - */ + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; -/***/ }), + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; -/***/ 18976: -/***/ ((module, exports, __nccwpck_require__) => { + // a flag to see when we're in the middle of a write. + this.writing = false; -/** - * Archiver Core - * - * @ignore - * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} - * @copyright (c) 2012-2014 Chris Talkington, contributors. - */ + // when true all writes will be buffered until .uncork() call + this.corked = 0; -var util = __nccwpck_require__(73837); + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; -const ERROR_CODES = { - 'ABORTED': 'archive was aborted', - 'DIRECTORYDIRPATHREQUIRED': 'diretory dirpath argument must be a non-empty string value', - 'DIRECTORYFUNCTIONINVALIDDATA': 'invalid data returned by directory custom data function', - 'ENTRYNAMEREQUIRED': 'entry name must be a non-empty string value', - 'FILEFILEPATHREQUIRED': 'file filepath argument must be a non-empty string value', - 'FINALIZING': 'archive already finalizing', - 'QUEUECLOSED': 'queue closed', - 'NOENDMETHOD': 'no suitable finalize/end method defined by module', - 'DIRECTORYNOTSUPPORTED': 'support for directory entries not defined by module', - 'FORMATSET': 'archive format already set', - 'INPUTSTEAMBUFFERREQUIRED': 'input source must be valid Stream or Buffer instance', - 'MODULESET': 'module already set', - 'SYMLINKNOTSUPPORTED': 'support for symlink entries not defined by module', - 'SYMLINKFILEPATHREQUIRED': 'symlink filepath argument must be a non-empty string value', - 'SYMLINKTARGETREQUIRED': 'symlink target argument must be a non-empty string value', - 'ENTRYNOTSUPPORTED': 'entry not supported' -}; + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; -function ArchiverError(code, data) { - Error.captureStackTrace(this, this.constructor); - //this.name = this.constructor.name; - this.message = ERROR_CODES[code] || code; - this.code = code; - this.data = data; -} + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; -util.inherits(ArchiverError, Error); + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; -exports = module.exports = ArchiverError; + // the amount that is being written when _write is called. + this.writelen = 0; -/***/ }), + this.bufferedRequest = null; + this.lastBufferedRequest = null; -/***/ 86239: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; -/** - * JSON Format Plugin - * - * @module plugins/json - * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} - * @copyright (c) 2012-2014 Chris Talkington, contributors. - */ -var inherits = (__nccwpck_require__(73837).inherits); -var Transform = (__nccwpck_require__(84123).Transform); + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; -var crc32 = __nccwpck_require__(6075); -var util = __nccwpck_require__(9925); + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; -/** - * @constructor - * @param {(JsonOptions|TransformOptions)} options - */ -var Json = function(options) { - if (!(this instanceof Json)) { - return new Json(options); - } + // count buffered requests + this.bufferedRequestCount = 0; - options = this.options = util.defaults(options, {}); + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} - Transform.call(this, options); +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; - this.supports = { - directory: true, - symlink: true - }; +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); - this.files = []; -}; +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function (object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; -inherits(Json, Transform); + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function (object) { + return object instanceof this; + }; +} -/** - * [_transform description] - * - * @private - * @param {Buffer} chunk - * @param {String} encoding - * @param {Function} callback - * @return void - */ -Json.prototype._transform = function(chunk, encoding, callback) { - callback(null, chunk); -}; +function Writable(options) { + Duplex = Duplex || __nccwpck_require__(5364); -/** - * [_writeStringified description] - * - * @private - * @return void - */ -Json.prototype._writeStringified = function() { - var fileString = JSON.stringify(this.files); - this.write(fileString); -}; + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. -/** - * [append description] - * - * @param {(Buffer|Stream)} source - * @param {EntryData} data - * @param {Function} callback - * @return void - */ -Json.prototype.append = function(source, data, callback) { - var self = this; + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { + return new Writable(options); + } - data.crc32 = 0; + this._writableState = new WritableState(options, this); - function onend(err, sourceBuffer) { - if (err) { - callback(err); - return; - } + // legacy. + this.writable = true; - data.size = sourceBuffer.length || 0; - data.crc32 = crc32.unsigned(sourceBuffer); + if (options) { + if (typeof options.write === 'function') this._write = options.write; - self.files.push(data); + if (typeof options.writev === 'function') this._writev = options.writev; - callback(null, data); - } + if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (data.sourceType === 'buffer') { - onend(null, source); - } else if (data.sourceType === 'stream') { - util.collectStream(source, onend); + if (typeof options.final === 'function') this._final = options.final; } -}; -/** - * [finalize description] - * - * @return void - */ -Json.prototype.finalize = function() { - this._writeStringified(); - this.end(); + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); }; -module.exports = Json; +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + pna.nextTick(cb, er); +} -/** - * @typedef {Object} JsonOptions - * @global - */ +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + pna.nextTick(cb, er); + valid = false; + } + return valid; +} -/***/ }), +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); -/***/ 4134: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } -/** - * TAR Format Plugin - * - * @module plugins/tar - * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} - * @copyright (c) 2012-2014 Chris Talkington, contributors. - */ -var zlib = __nccwpck_require__(59796); + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } -var engine = __nccwpck_require__(69658); -var util = __nccwpck_require__(9925); + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; -/** - * @constructor - * @param {TarOptions} options - */ -var Tar = function(options) { - if (!(this instanceof Tar)) { - return new Tar(options); + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); } - options = this.options = util.defaults(options, { - gzip: false - }); + return ret; +}; - if (typeof options.gzipOptions !== 'object') { - options.gzipOptions = {}; - } +Writable.prototype.cork = function () { + var state = this._writableState; - this.supports = { - directory: true, - symlink: true - }; + state.corked++; +}; - this.engine = engine.pack(options); - this.compressor = false; +Writable.prototype.uncork = function () { + var state = this._writableState; - if (options.gzip) { - this.compressor = zlib.createGzip(options.gzipOptions); - this.compressor.on('error', this._onCompressorError.bind(this)); + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); } }; -/** - * [_onCompressorError description] - * - * @private - * @param {Error} err - * @return void - */ -Tar.prototype._onCompressorError = function(err) { - this.engine.emit('error', err); +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; }; -/** - * [append description] - * - * @param {(Buffer|Stream)} source - * @param {TarEntryData} data - * @param {Function} callback - * @return void - */ -Tar.prototype.append = function(source, data, callback) { - var self = this; +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} - data.mtime = data.date; +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); - function append(err, sourceBuffer) { - if (err) { - callback(err); - return; +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; } - - self.engine.entry(data, sourceBuffer, function(err) { - callback(err, data); - }); } + var len = state.objectMode ? 1 : chunk.length; - if (data.sourceType === 'buffer') { - append(null, source); - } else if (data.sourceType === 'stream' && data.stats) { - data.size = data.stats.size; + state.length += len; - var entry = self.engine.entry(data, function(err) { - callback(err, data); - }); + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; - source.pipe(entry); - } else if (data.sourceType === 'stream') { - util.collectStream(source, append); + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); } -}; -/** - * [finalize description] - * - * @return void - */ -Tar.prototype.finalize = function() { - this.engine.finalize(); -}; + return ret; +} -/** - * [on description] - * - * @return this.engine - */ -Tar.prototype.on = function() { - return this.engine.on.apply(this.engine, arguments); -}; +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} -/** - * [pipe description] - * - * @param {String} destination - * @param {Object} options - * @return this.engine - */ -Tar.prototype.pipe = function(destination, options) { - if (this.compressor) { - return this.engine.pipe.apply(this.engine, [this.compressor]).pipe(destination, options); - } else { - return this.engine.pipe.apply(this.engine, arguments); - } -}; +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; -/** - * [unpipe description] - * - * @return this.engine - */ -Tar.prototype.unpipe = function() { - if (this.compressor) { - return this.compressor.unpipe.apply(this.compressor, arguments); + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + pna.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + pna.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit('error', er); } else { - return this.engine.unpipe.apply(this.engine, arguments); + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); } -}; - -module.exports = Tar; +} -/** - * @typedef {Object} TarOptions - * @global - * @property {Boolean} [gzip=false] Compress the tar archive using gzip. - * @property {Object} [gzipOptions] Passed to [zlib]{@link https://nodejs.org/api/zlib.html#zlib_class_options} - * to control compression. - * @property {*} [*] See [tar-stream]{@link https://github.com/mafintosh/tar-stream} documentation for additional properties. - */ +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} -/** - * @typedef {Object} TarEntryData - * @global - * @property {String} name Sets the entry name including internal path. - * @property {(String|Date)} [date=NOW()] Sets the entry date. - * @property {Number} [mode=D:0755/F:0644] Sets the entry permissions. - * @property {String} [prefix] Sets a path prefix for the entry name. Useful - * when working with methods like `directory` or `glob`. - * @property {fs.Stats} [stats] Sets the fs stat data for this entry allowing - * for reduction of fs stat calls when stat data is already known. - */ +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; -/** - * TarStream Module - * @external TarStream - * @see {@link https://github.com/mafintosh/tar-stream} - */ + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); -/***/ }), + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } -/***/ 36926: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} -/** - * ZIP Format Plugin - * - * @module plugins/zip - * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} - * @copyright (c) 2012-2014 Chris Talkington, contributors. - */ -var engine = __nccwpck_require__(79293); -var util = __nccwpck_require__(9925); +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} -/** - * @constructor - * @param {ZipOptions} [options] - * @param {String} [options.comment] Sets the zip archive comment. - * @param {Boolean} [options.forceLocalTime=false] Forces the archive to contain local file times instead of UTC. - * @param {Boolean} [options.forceZip64=false] Forces the archive to contain ZIP64 headers. - * @param {Boolean} [options.namePrependSlash=false] Prepends a forward slash to archive file paths. - * @param {Boolean} [options.store=false] Sets the compression method to STORE. - * @param {Object} [options.zlib] Passed to [zlib]{@link https://nodejs.org/api/zlib.html#zlib_class_options} - */ -var Zip = function(options) { - if (!(this instanceof Zip)) { - return new Zip(options); +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); } +} - options = this.options = util.defaults(options, { - comment: '', - forceUTC: false, - namePrependSlash: false, - store: false - }); +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; - this.supports = { - directory: true, - symlink: true - }; + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; - this.engine = new engine(options); -}; + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; -/** - * @param {(Buffer|Stream)} source - * @param {ZipEntryData} data - * @param {String} data.name Sets the entry name including internal path. - * @param {(String|Date)} [data.date=NOW()] Sets the entry date. - * @param {Number} [data.mode=D:0755/F:0644] Sets the entry permissions. - * @param {String} [data.prefix] Sets a path prefix for the entry name. Useful - * when working with methods like `directory` or `glob`. - * @param {fs.Stats} [data.stats] Sets the fs stat data for this entry allowing - * for reduction of fs stat calls when stat data is already known. - * @param {Boolean} [data.store=ZipOptions.store] Sets the compression method to STORE. - * @param {Function} callback - * @return void - */ -Zip.prototype.append = function(source, data, callback) { - this.engine.entry(source, data, callback); -}; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); -/** - * @return void - */ -Zip.prototype.finalize = function() { - this.engine.finalize(); -}; - -/** - * @return this.engine - */ -Zip.prototype.on = function() { - return this.engine.on.apply(this.engine, arguments); -}; + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; -/** - * @return this.engine - */ -Zip.prototype.pipe = function() { - return this.engine.pipe.apply(this.engine, arguments); -}; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } -/** - * @return this.engine - */ -Zip.prototype.unpipe = function() { - return this.engine.unpipe.apply(this.engine, arguments); -}; + if (entry === null) state.lastBufferedRequest = null; + } -module.exports = Zip; + state.bufferedRequest = entry; + state.bufferProcessing = false; +} -/** - * @typedef {Object} ZipOptions - * @global - * @property {String} [comment] Sets the zip archive comment. - * @property {Boolean} [forceLocalTime=false] Forces the archive to contain local file times instead of UTC. - * @property {Boolean} [forceZip64=false] Forces the archive to contain ZIP64 headers. - * @prpperty {Boolean} [namePrependSlash=false] Prepends a forward slash to archive file paths. - * @property {Boolean} [store=false] Sets the compression method to STORE. - * @property {Object} [zlib] Passed to [zlib]{@link https://nodejs.org/api/zlib.html#zlib_class_options} - * to control compression. - * @property {*} [*] See [zip-stream]{@link https://archiverjs.com/zip-stream/ZipStream.html} documentation for current list of properties. - */ +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('_write() is not implemented')); +}; -/** - * @typedef {Object} ZipEntryData - * @global - * @property {String} name Sets the entry name including internal path. - * @property {(String|Date)} [date=NOW()] Sets the entry date. - * @property {Number} [mode=D:0755/F:0644] Sets the entry permissions. - * @property {Boolean} [namePrependSlash=ZipOptions.namePrependSlash] Prepends a forward slash to archive file paths. - * @property {String} [prefix] Sets a path prefix for the entry name. Useful - * when working with methods like `directory` or `glob`. - * @property {fs.Stats} [stats] Sets the fs stat data for this entry allowing - * for reduction of fs stat calls when stat data is already known. - * @property {Boolean} [store=ZipOptions.store] Sets the compression method to STORE. - */ +Writable.prototype._writev = null; -/** - * ZipStream Module - * @external ZipStream - * @see {@link https://www.archiverjs.com/zip-stream/ZipStream.html} - */ +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } -/***/ }), + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); -/***/ 81073: -/***/ (function(__unused_webpack_module, exports) { + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } -(function (global, factory) { - true ? factory(exports) : - 0; -}(this, (function (exports) { 'use strict'; + // ignore unnecessary end() calls. + if (!state.ending) endWritable(this, state, cb); +}; - /** - * Creates a continuation function with some arguments already applied. - * - * Useful as a shorthand when combined with other control flow functions. Any - * arguments passed to the returned function are added to the arguments - * originally passed to apply. - * - * @name apply - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {Function} fn - The function you want to eventually apply all - * arguments to. Invokes with (arguments...). - * @param {...*} arguments... - Any number of arguments to automatically apply - * when the continuation is called. - * @returns {Function} the partially-applied function - * @example - * - * // using apply - * async.parallel([ - * async.apply(fs.writeFile, 'testfile1', 'test1'), - * async.apply(fs.writeFile, 'testfile2', 'test2') - * ]); - * - * - * // the same process without using apply - * async.parallel([ - * function(callback) { - * fs.writeFile('testfile1', 'test1', callback); - * }, - * function(callback) { - * fs.writeFile('testfile2', 'test2', callback); - * } - * ]); - * - * // It's possible to pass any number of additional arguments when calling the - * // continuation: - * - * node> var fn = async.apply(sys.puts, 'one'); - * node> fn('two', 'three'); - * one - * two - * three - */ - function apply(fn, ...args) { - return (...callArgs) => fn(...args,...callArgs); +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + stream.emit('error', err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function') { + state.pendingcb++; + state.finalCalled = true; + pna.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); } + } +} - function initialParams (fn) { - return function (...args/*, callback*/) { - var callback = args.pop(); - return fn.call(this, args, callback); - }; +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); } + } + return need; +} - /* istanbul ignore file */ +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} - var hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask; - var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; - var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } - function fallback(fn) { - setTimeout(fn, 0); - } + // reuse the free corkReq. + state.corkedRequestsFree.next = corkReq; +} - function wrap(defer) { - return (fn, ...args) => defer(() => fn(...args)); +Object.defineProperty(Writable.prototype, 'destroyed', { + get: function () { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; } - var _defer; + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); - if (hasQueueMicrotask) { - _defer = queueMicrotask; - } else if (hasSetImmediate) { - _defer = setImmediate; - } else if (hasNextTick) { - _defer = process.nextTick; - } else { - _defer = fallback; - } +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + this.end(); + cb(err); +}; - var setImmediate$1 = wrap(_defer); +/***/ }), - /** - * Take a sync function and make it async, passing its return value to a - * callback. This is useful for plugging sync functions into a waterfall, - * series, or other async functions. Any arguments passed to the generated - * function will be passed to the wrapped function (except for the final - * callback argument). Errors thrown will be passed to the callback. - * - * If the function passed to `asyncify` returns a Promise, that promises's - * resolved/rejected state will be used to call the callback, rather than simply - * the synchronous return value. - * - * This also means you can asyncify ES2017 `async` functions. - * - * @name asyncify - * @static - * @memberOf module:Utils - * @method - * @alias wrapSync - * @category Util - * @param {Function} func - The synchronous function, or Promise-returning - * function to convert to an {@link AsyncFunction}. - * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be - * invoked with `(args..., callback)`. - * @example - * - * // passing a regular synchronous function - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(JSON.parse), - * function (data, next) { - * // data is the result of parsing the text. - * // If there was a parsing error, it would have been caught. - * } - * ], callback); - * - * // passing a function returning a promise - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(function (contents) { - * return db.model.create(contents); - * }), - * function (model, next) { - * // `model` is the instantiated model object. - * // If there was an error, this function would be skipped. - * } - * ], callback); - * - * // es2017 example, though `asyncify` is not needed if your JS environment - * // supports async functions out of the box - * var q = async.queue(async.asyncify(async function(file) { - * var intermediateStep = await processFile(file); - * return await somePromise(intermediateStep) - * })); - * - * q.push(files); - */ - function asyncify(func) { - if (isAsync(func)) { - return function (...args/*, callback*/) { - const callback = args.pop(); - const promise = func.apply(this, args); - return handlePromise(promise, callback) - } - } +/***/ 37898: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return initialParams(function (args, callback) { - var result; - try { - result = func.apply(this, args); - } catch (e) { - return callback(e); - } - // if result is Promise object - if (result && typeof result.then === 'function') { - return handlePromise(result, callback) - } else { - callback(null, result); - } - }); - } +"use strict"; - function handlePromise(promise, callback) { - return promise.then(value => { - invokeCallback(callback, null, value); - }, err => { - invokeCallback(callback, err && err.message ? err : new Error(err)); - }); - } - function invokeCallback(callback, error, value) { - try { - callback(error, value); - } catch (err) { - setImmediate$1(e => { throw e }, err); - } - } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - function isAsync(fn) { - return fn[Symbol.toStringTag] === 'AsyncFunction'; - } +var Buffer = (__nccwpck_require__(36476).Buffer); +var util = __nccwpck_require__(73837); - function isAsyncGenerator(fn) { - return fn[Symbol.toStringTag] === 'AsyncGenerator'; - } +function copyBuffer(src, target, offset) { + src.copy(target, offset); +} - function isAsyncIterable(obj) { - return typeof obj[Symbol.asyncIterator] === 'function'; - } +module.exports = function () { + function BufferList() { + _classCallCheck(this, BufferList); - function wrapAsync(asyncFn) { - if (typeof asyncFn !== 'function') throw new Error('expected a function') - return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; - } + this.head = null; + this.tail = null; + this.length = 0; + } - // conditionally promisify a function. - // only return a promise if a callback is omitted - function awaitify (asyncFn, arity = asyncFn.length) { - if (!arity) throw new Error('arity is undefined') - function awaitable (...args) { - if (typeof args[arity - 1] === 'function') { - return asyncFn.apply(this, args) - } + BufferList.prototype.push = function push(v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; - return new Promise((resolve, reject) => { - args[arity - 1] = (err, ...cbArgs) => { - if (err) return reject(err) - resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]); - }; - asyncFn.apply(this, args); - }) - } + BufferList.prototype.unshift = function unshift(v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; - return awaitable - } + BufferList.prototype.shift = function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; - function applyEach (eachfn) { - return function applyEach(fns, ...callArgs) { - const go = awaitify(function (callback) { - var that = this; - return eachfn(fns, (fn, cb) => { - wrapAsync(fn).apply(that, callArgs.concat(cb)); - }, callback); - }); - return go; - }; - } + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; - function _asyncMap(eachfn, arr, iteratee, callback) { - arr = arr || []; - var results = []; - var counter = 0; - var _iteratee = wrapAsync(iteratee); + BufferList.prototype.join = function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; - return eachfn(arr, (value, _, iterCb) => { - var index = counter++; - _iteratee(value, (err, v) => { - results[index] = v; - iterCb(err); - }); - }, err => { - callback(err, results); - }); + BufferList.prototype.concat = function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; } + return ret; + }; - function isArrayLike(value) { - return value && - typeof value.length === 'number' && - value.length >= 0 && - value.length % 1 === 0; - } + return BufferList; +}(); - // A temporary value used to identify if the loop should be broken. - // See #1064, #1293 - const breakLoop = {}; +if (util && util.inspect && util.inspect.custom) { + module.exports.prototype[util.inspect.custom] = function () { + var obj = util.inspect({ length: this.length }); + return this.constructor.name + ' ' + obj; + }; +} - function once(fn) { - function wrapper (...args) { - if (fn === null) return; - var callFn = fn; - fn = null; - callFn.apply(this, args); - } - Object.assign(wrapper, fn); - return wrapper - } +/***/ }), - function getIterator (coll) { - return coll[Symbol.iterator] && coll[Symbol.iterator](); - } +/***/ 71890: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function createArrayIterator(coll) { - var i = -1; - var len = coll.length; - return function next() { - return ++i < len ? {value: coll[i], key: i} : null; - } - } +"use strict"; - function createES2015Iterator(iterator) { - var i = -1; - return function next() { - var item = iterator.next(); - if (item.done) - return null; - i++; - return {value: item.value, key: i}; - } - } - function createObjectIterator(obj) { - var okeys = obj ? Object.keys(obj) : []; - var i = -1; - var len = okeys.length; - return function next() { - var key = okeys[++i]; - if (key === '__proto__') { - return next(); - } - return i < len ? {value: obj[key], key} : null; - }; - } +/**/ - function createIterator(coll) { - if (isArrayLike(coll)) { - return createArrayIterator(coll); - } +var pna = __nccwpck_require__(47810); +/**/ - var iterator = getIterator(coll); - return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + pna.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + pna.nextTick(emitErrorNT, this, err); + } } - function onlyOnce(fn) { - return function (...args) { - if (fn === null) throw new Error("Callback was already called."); - var callFn = fn; - fn = null; - callFn.apply(this, args); - }; + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + pna.nextTick(emitErrorNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + pna.nextTick(emitErrorNT, _this, err); + } + } else if (cb) { + cb(err); } + }); - // for async generators - function asyncEachOfLimit(generator, limit, iteratee, callback) { - let done = false; - let canceled = false; - let awaiting = false; - let running = 0; - let idx = 0; + return this; +} - function replenish() { - //console.log('replenish') - if (running >= limit || awaiting || done) return - //console.log('replenish awaiting') - awaiting = true; - generator.next().then(({value, done: iterDone}) => { - //console.log('got value', value) - if (canceled || done) return - awaiting = false; - if (iterDone) { - done = true; - if (running <= 0) { - //console.log('done nextCb') - callback(null); - } - return; - } - running++; - iteratee(value, idx, iterateeCallback); - idx++; - replenish(); - }).catch(handleError); - } +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } - function iterateeCallback(err, result) { - //console.log('iterateeCallback') - running -= 1; - if (canceled) return - if (err) return handleError(err) + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} - if (err === false) { - done = true; - canceled = true; - return - } +function emitErrorNT(self, err) { + self.emit('error', err); +} - if (result === breakLoop || (done && running <= 0)) { - done = true; - //console.log('done iterCb') - return callback(null); - } - replenish(); - } +module.exports = { + destroy: destroy, + undestroy: undestroy +}; - function handleError(err) { - if (canceled) return - awaiting = false; - done = true; - callback(err); - } +/***/ }), - replenish(); - } +/***/ 41715: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var eachOfLimit = (limit) => { - return (obj, iteratee, callback) => { - callback = once(callback); - if (limit <= 0) { - throw new RangeError('concurrency limit cannot be less than 1') - } - if (!obj) { - return callback(null); - } - if (isAsyncGenerator(obj)) { - return asyncEachOfLimit(obj, limit, iteratee, callback) - } - if (isAsyncIterable(obj)) { - return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback) - } - var nextElem = createIterator(obj); - var done = false; - var canceled = false; - var running = 0; - var looping = false; +module.exports = __nccwpck_require__(12781); - function iterateeCallback(err, value) { - if (canceled) return - running -= 1; - if (err) { - done = true; - callback(err); - } - else if (err === false) { - done = true; - canceled = true; - } - else if (value === breakLoop || (done && running <= 0)) { - done = true; - return callback(null); - } - else if (!looping) { - replenish(); - } - } - function replenish () { - looping = true; - while (running < limit && !done) { - var elem = nextElem(); - if (elem === null) { - done = true; - if (running <= 0) { - callback(null); - } - return; - } - running += 1; - iteratee(elem.value, elem.key, onlyOnce(iterateeCallback)); - } - looping = false; - } +/***/ }), - replenish(); - }; - }; +/***/ 44785: +/***/ ((module, exports, __nccwpck_require__) => { - /** - * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a - * time. - * - * @name eachOfLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.eachOf]{@link module:Collections.eachOf} - * @alias forEachOfLimit - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. The `key` is the item's key, or index in the case of an - * array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @returns {Promise} a promise, if a callback is omitted - */ - function eachOfLimit$1(coll, limit, iteratee, callback) { - return eachOfLimit(limit)(coll, wrapAsync(iteratee), callback); - } +var Stream = __nccwpck_require__(12781); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream; + exports = module.exports = Stream.Readable; + exports.Readable = Stream.Readable; + exports.Writable = Stream.Writable; + exports.Duplex = Stream.Duplex; + exports.Transform = Stream.Transform; + exports.PassThrough = Stream.PassThrough; + exports.Stream = Stream; +} else { + exports = module.exports = __nccwpck_require__(19647); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = __nccwpck_require__(33369); + exports.Duplex = __nccwpck_require__(5364); + exports.Transform = __nccwpck_require__(95401); + exports.PassThrough = __nccwpck_require__(47905); +} - var eachOfLimit$2 = awaitify(eachOfLimit$1, 4); - // eachOf implementation optimized for array-likes - function eachOfArrayLike(coll, iteratee, callback) { - callback = once(callback); - var index = 0, - completed = 0, - {length} = coll, - canceled = false; - if (length === 0) { - callback(null); - } +/***/ }), - function iteratorCallback(err, value) { - if (err === false) { - canceled = true; - } - if (canceled === true) return - if (err) { - callback(err); - } else if ((++completed === length) || value === breakLoop) { - callback(null); - } - } +/***/ 36476: +/***/ ((module, exports, __nccwpck_require__) => { - for (; index < length; index++) { - iteratee(coll[index], index, onlyOnce(iteratorCallback)); - } - } +/* eslint-disable node/no-deprecated-api */ +var buffer = __nccwpck_require__(14300) +var Buffer = buffer.Buffer - // a generic version of eachOf which can handle array, object, and iterator cases. - function eachOfGeneric (coll, iteratee, callback) { - return eachOfLimit$2(coll, Infinity, iteratee, callback); - } +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} - /** - * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument - * to the iteratee. - * - * @name eachOf - * @static - * @memberOf module:Collections - * @method - * @alias forEachOf - * @category Collection - * @see [async.each]{@link module:Collections.each} - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each - * item in `coll`. - * The `key` is the item's key, or index in the case of an array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @returns {Promise} a promise, if a callback is omitted - * @example - * - * // dev.json is a file containing a valid json object config for dev environment - * // dev.json is a file containing a valid json object config for test environment - * // prod.json is a file containing a valid json object config for prod environment - * // invalid.json is a file with a malformed json object - * - * let configs = {}; //global variable - * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'}; - * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'}; - * - * // asynchronous function that reads a json file and parses the contents as json object - * function parseFile(file, key, callback) { - * fs.readFile(file, "utf8", function(err, data) { - * if (err) return calback(err); - * try { - * configs[key] = JSON.parse(data); - * } catch (e) { - * return callback(e); - * } - * callback(); - * }); - * } - * - * // Using callbacks - * async.forEachOf(validConfigFileMap, parseFile, function (err) { - * if (err) { - * console.error(err); - * } else { - * console.log(configs); - * // configs is now a map of JSON data, e.g. - * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} - * } - * }); - * - * //Error handing - * async.forEachOf(invalidConfigFileMap, parseFile, function (err) { - * if (err) { - * console.error(err); - * // JSON parse error exception - * } else { - * console.log(configs); - * } - * }); - * - * // Using Promises - * async.forEachOf(validConfigFileMap, parseFile) - * .then( () => { - * console.log(configs); - * // configs is now a map of JSON data, e.g. - * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} - * }).catch( err => { - * console.error(err); - * }); - * - * //Error handing - * async.forEachOf(invalidConfigFileMap, parseFile) - * .then( () => { - * console.log(configs); - * }).catch( err => { - * console.error(err); - * // JSON parse error exception - * }); - * - * // Using async/await - * async () => { - * try { - * let result = await async.forEachOf(validConfigFileMap, parseFile); - * console.log(configs); - * // configs is now a map of JSON data, e.g. - * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} - * } - * catch (err) { - * console.log(err); - * } - * } - * - * //Error handing - * async () => { - * try { - * let result = await async.forEachOf(invalidConfigFileMap, parseFile); - * console.log(configs); - * } - * catch (err) { - * console.log(err); - * // JSON parse error exception - * } - * } - * - */ - function eachOf(coll, iteratee, callback) { - var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; - return eachOfImplementation(coll, wrapAsync(iteratee), callback); +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) } + } else { + buf.fill(0) + } + return buf +} - var eachOf$1 = awaitify(eachOf, 3); +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} - /** - * Produces a new collection of values by mapping each value in `coll` through - * the `iteratee` function. The `iteratee` is called with an item from `coll` - * and a callback for when it has finished processing. Each of these callbacks - * takes 2 arguments: an `error`, and the transformed item from `coll`. If - * `iteratee` passes an error to its callback, the main `callback` (for the - * `map` function) is immediately called with the error. - * - * Note, that since this function applies the `iteratee` to each item in - * parallel, there is no guarantee that the `iteratee` functions will complete - * in order. However, the results array will be in the same order as the - * original `coll`. - * - * If `map` is passed an Object, the results will be an Array. The results - * will roughly be in the order of the original Objects' keys (but this can - * vary across JavaScript engines). - * - * @name map - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an Array of the - * transformed items from the `coll`. Invoked with (err, results). - * @returns {Promise} a promise, if no callback is passed - * @example - * - * // file1.txt is a file that is 1000 bytes in size - * // file2.txt is a file that is 2000 bytes in size - * // file3.txt is a file that is 3000 bytes in size - * // file4.txt does not exist - * - * const fileList = ['file1.txt','file2.txt','file3.txt']; - * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; - * - * // asynchronous function that returns the file size in bytes - * function getFileSizeInBytes(file, callback) { - * fs.stat(file, function(err, stat) { - * if (err) { - * return callback(err); - * } - * callback(null, stat.size); - * }); - * } - * - * // Using callbacks - * async.map(fileList, getFileSizeInBytes, function(err, results) { - * if (err) { - * console.log(err); - * } else { - * console.log(results); - * // results is now an array of the file size in bytes for each file, e.g. - * // [ 1000, 2000, 3000] - * } - * }); - * - * // Error Handling - * async.map(withMissingFileList, getFileSizeInBytes, function(err, results) { - * if (err) { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * } else { - * console.log(results); - * } - * }); - * - * // Using Promises - * async.map(fileList, getFileSizeInBytes) - * .then( results => { - * console.log(results); - * // results is now an array of the file size in bytes for each file, e.g. - * // [ 1000, 2000, 3000] - * }).catch( err => { - * console.log(err); - * }); - * - * // Error Handling - * async.map(withMissingFileList, getFileSizeInBytes) - * .then( results => { - * console.log(results); - * }).catch( err => { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * }); - * - * // Using async/await - * async () => { - * try { - * let results = await async.map(fileList, getFileSizeInBytes); - * console.log(results); - * // results is now an array of the file size in bytes for each file, e.g. - * // [ 1000, 2000, 3000] - * } - * catch (err) { - * console.log(err); - * } - * } - * - * // Error Handling - * async () => { - * try { - * let results = await async.map(withMissingFileList, getFileSizeInBytes); - * console.log(results); - * } - * catch (err) { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * } - * } - * - */ - function map (coll, iteratee, callback) { - return _asyncMap(eachOf$1, coll, iteratee, callback) - } - var map$1 = awaitify(map, 3); +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} - /** - * Applies the provided arguments to each function in the array, calling - * `callback` after all functions have completed. If you only provide the first - * argument, `fns`, then it will return a function which lets you pass in the - * arguments as if it were a single function call. If more arguments are - * provided, `callback` is required while `args` is still optional. The results - * for each of the applied async functions are passed to the final callback - * as an array. - * - * @name applyEach - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s - * to all call with the same arguments - * @param {...*} [args] - any number of separate arguments to pass to the - * function. - * @param {Function} [callback] - the final argument should be the callback, - * called when all functions have completed processing. - * @returns {AsyncFunction} - Returns a function that takes no args other than - * an optional callback, that is the result of applying the `args` to each - * of the functions. - * @example - * - * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket') - * - * appliedFn((err, results) => { - * // results[0] is the results for `enableSearch` - * // results[1] is the results for `updateSchema` - * }); - * - * // partial application example: - * async.each( - * buckets, - * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(), - * callback - * ); - */ - var applyEach$1 = applyEach(map$1); - /** - * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. - * - * @name eachOfSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.eachOf]{@link module:Collections.eachOf} - * @alias forEachOfSeries - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Invoked with (err). - * @returns {Promise} a promise, if a callback is omitted - */ - function eachOfSeries(coll, iteratee, callback) { - return eachOfLimit$2(coll, 1, iteratee, callback) - } - var eachOfSeries$1 = awaitify(eachOfSeries, 3); +/***/ }), - /** - * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. - * - * @name mapSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.map]{@link module:Collections.map} - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an array of the - * transformed items from the `coll`. Invoked with (err, results). - * @returns {Promise} a promise, if no callback is passed - */ - function mapSeries (coll, iteratee, callback) { - return _asyncMap(eachOfSeries$1, coll, iteratee, callback) - } - var mapSeries$1 = awaitify(mapSeries, 3); +/***/ 99708: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. - * - * @name applyEachSeries - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.applyEach]{@link module:ControlFlow.applyEach} - * @category Control Flow - * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all - * call with the same arguments - * @param {...*} [args] - any number of separate arguments to pass to the - * function. - * @param {Function} [callback] - the final argument should be the callback, - * called when all functions have completed processing. - * @returns {AsyncFunction} - A function, that when called, is the result of - * appling the `args` to the list of functions. It takes no args, other than - * a callback. - */ - var applyEachSeries = applyEach(mapSeries$1); +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - const PROMISE_SYMBOL = Symbol('promiseCallback'); - function promiseCallback () { - let resolve, reject; - function callback (err, ...args) { - if (err) return reject(err) - resolve(args.length > 1 ? args : args[0]); - } - callback[PROMISE_SYMBOL] = new Promise((res, rej) => { - resolve = res, - reject = rej; - }); +/**/ - return callback - } +var Buffer = (__nccwpck_require__(36476).Buffer); +/**/ - /** - * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on - * their requirements. Each function can optionally depend on other functions - * being completed first, and each function is run as soon as its requirements - * are satisfied. - * - * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence - * will stop. Further tasks will not execute (so any other functions depending - * on it will not run), and the main `callback` is immediately called with the - * error. - * - * {@link AsyncFunction}s also receive an object containing the results of functions which - * have completed so far as the first argument, if they have dependencies. If a - * task function has no dependencies, it will only be passed a callback. - * - * @name auto - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Object} tasks - An object. Each of its properties is either a - * function or an array of requirements, with the {@link AsyncFunction} itself the last item - * in the array. The object's key of a property serves as the name of the task - * defined by that property, i.e. can be used when specifying requirements for - * other tasks. The function receives one or two arguments: - * * a `results` object, containing the results of the previously executed - * functions, only passed if the task has any dependencies, - * * a `callback(err, result)` function, which must be called when finished, - * passing an `error` (which can be `null`) and the result of the function's - * execution. - * @param {number} [concurrency=Infinity] - An optional `integer` for - * determining the maximum number of tasks that can be run in parallel. By - * default, as many as possible. - * @param {Function} [callback] - An optional callback which is called when all - * the tasks have been completed. It receives the `err` argument if any `tasks` - * pass an error to their callback. Results are always returned; however, if an - * error occurs, no further `tasks` will be performed, and the results object - * will only contain partial results. Invoked with (err, results). - * @returns {Promise} a promise, if a callback is not passed - * @example - * - * //Using Callbacks - * async.auto({ - * get_data: function(callback) { - * // async code to get some data - * callback(null, 'data', 'converted to array'); - * }, - * make_folder: function(callback) { - * // async code to create a directory to store a file in - * // this is run at the same time as getting the data - * callback(null, 'folder'); - * }, - * write_file: ['get_data', 'make_folder', function(results, callback) { - * // once there is some data and the directory exists, - * // write the data to a file in the directory - * callback(null, 'filename'); - * }], - * email_link: ['write_file', function(results, callback) { - * // once the file is written let's email a link to it... - * callback(null, {'file':results.write_file, 'email':'user@example.com'}); - * }] - * }, function(err, results) { - * if (err) { - * console.log('err = ', err); - * } - * console.log('results = ', results); - * // results = { - * // get_data: ['data', 'converted to array'] - * // make_folder; 'folder', - * // write_file: 'filename' - * // email_link: { file: 'filename', email: 'user@example.com' } - * // } - * }); - * - * //Using Promises - * async.auto({ - * get_data: function(callback) { - * console.log('in get_data'); - * // async code to get some data - * callback(null, 'data', 'converted to array'); - * }, - * make_folder: function(callback) { - * console.log('in make_folder'); - * // async code to create a directory to store a file in - * // this is run at the same time as getting the data - * callback(null, 'folder'); - * }, - * write_file: ['get_data', 'make_folder', function(results, callback) { - * // once there is some data and the directory exists, - * // write the data to a file in the directory - * callback(null, 'filename'); - * }], - * email_link: ['write_file', function(results, callback) { - * // once the file is written let's email a link to it... - * callback(null, {'file':results.write_file, 'email':'user@example.com'}); - * }] - * }).then(results => { - * console.log('results = ', results); - * // results = { - * // get_data: ['data', 'converted to array'] - * // make_folder; 'folder', - * // write_file: 'filename' - * // email_link: { file: 'filename', email: 'user@example.com' } - * // } - * }).catch(err => { - * console.log('err = ', err); - * }); - * - * //Using async/await - * async () => { - * try { - * let results = await async.auto({ - * get_data: function(callback) { - * // async code to get some data - * callback(null, 'data', 'converted to array'); - * }, - * make_folder: function(callback) { - * // async code to create a directory to store a file in - * // this is run at the same time as getting the data - * callback(null, 'folder'); - * }, - * write_file: ['get_data', 'make_folder', function(results, callback) { - * // once there is some data and the directory exists, - * // write the data to a file in the directory - * callback(null, 'filename'); - * }], - * email_link: ['write_file', function(results, callback) { - * // once the file is written let's email a link to it... - * callback(null, {'file':results.write_file, 'email':'user@example.com'}); - * }] - * }); - * console.log('results = ', results); - * // results = { - * // get_data: ['data', 'converted to array'] - * // make_folder; 'folder', - * // write_file: 'filename' - * // email_link: { file: 'filename', email: 'user@example.com' } - * // } - * } - * catch (err) { - * console.log(err); - * } - * } - * - */ - function auto(tasks, concurrency, callback) { - if (typeof concurrency !== 'number') { - // concurrency is optional, shift the args. - callback = concurrency; - concurrency = null; - } - callback = once(callback || promiseCallback()); - var numTasks = Object.keys(tasks).length; - if (!numTasks) { - return callback(null); - } - if (!concurrency) { - concurrency = numTasks; - } +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } +}; - var results = {}; - var runningTasks = 0; - var canceled = false; - var hasError = false; +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; - var listeners = Object.create(null); +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} - var readyTasks = []; +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.s = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} - // for cycle detection: - var readyToCheck = []; // tasks that have been identified as reachable - // without the possibility of returning to an ancestor task - var uncheckedDependencies = {}; +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; - Object.keys(tasks).forEach(key => { - var task = tasks[key]; - if (!Array.isArray(task)) { - // no dependencies - enqueueTask(key, [task]); - readyToCheck.push(key); - return; - } +StringDecoder.prototype.end = utf8End; - var dependencies = task.slice(0, task.length - 1); - var remainingDependencies = dependencies.length; - if (remainingDependencies === 0) { - enqueueTask(key, task); - readyToCheck.push(key); - return; - } - uncheckedDependencies[key] = remainingDependencies; +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; - dependencies.forEach(dependencyName => { - if (!tasks[dependencyName]) { - throw new Error('async.auto task `' + key + - '` has a non-existent dependency `' + - dependencyName + '` in ' + - dependencies.join(', ')); - } - addListener(dependencyName, () => { - remainingDependencies--; - if (remainingDependencies === 0) { - enqueueTask(key, task); - } - }); - }); - }); +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; - checkForDeadlocks(); - processQueue(); +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} - function enqueueTask(key, task) { - readyTasks.push(() => runTask(key, task)); - } +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} - function processQueue() { - if (canceled) return - if (readyTasks.length === 0 && runningTasks === 0) { - return callback(null, results); - } - while(readyTasks.length && runningTasks < concurrency) { - var run = readyTasks.shift(); - run(); - } +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} - } +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} - function addListener(taskName, fn) { - var taskListeners = listeners[taskName]; - if (!taskListeners) { - taskListeners = listeners[taskName] = []; - } +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} - taskListeners.push(fn); - } +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} - function taskComplete(taskName) { - var taskListeners = listeners[taskName] || []; - taskListeners.forEach(fn => fn()); - processQueue(); - } +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} - function runTask(key, task) { - if (hasError) return; +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} - var taskCallback = onlyOnce((err, ...result) => { - runningTasks--; - if (err === false) { - canceled = true; - return - } - if (result.length < 2) { - [result] = result; - } - if (err) { - var safeResults = {}; - Object.keys(results).forEach(rkey => { - safeResults[rkey] = results[rkey]; - }); - safeResults[key] = result; - hasError = true; - listeners = Object.create(null); - if (canceled) return - callback(err, safeResults); - } else { - results[key] = result; - taskComplete(key); - } - }); +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} - runningTasks++; - var taskFn = wrapAsync(task[task.length - 1]); - if (task.length > 1) { - taskFn(results, taskCallback); - } else { - taskFn(taskCallback); - } - } +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} - function checkForDeadlocks() { - // Kahn's algorithm - // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm - // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html - var currentTask; - var counter = 0; - while (readyToCheck.length) { - currentTask = readyToCheck.pop(); - counter++; - getDependents(currentTask).forEach(dependent => { - if (--uncheckedDependencies[dependent] === 0) { - readyToCheck.push(dependent); - } - }); - } +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} - if (counter !== numTasks) { - throw new Error( - 'async.auto cannot execute tasks due to a recursive dependency' - ); - } - } +/***/ }), - function getDependents(taskName) { - var result = []; - Object.keys(tasks).forEach(key => { - const task = tasks[key]; - if (Array.isArray(task) && task.indexOf(taskName) >= 0) { - result.push(key); - } - }); - return result; - } +/***/ 43084: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return callback[PROMISE_SYMBOL] - } +/** + * Archiver Vending + * + * @ignore + * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} + * @copyright (c) 2012-2014 Chris Talkington, contributors. + */ +var Archiver = __nccwpck_require__(35010); - var FN_ARGS = /^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/; - var ARROW_FN_ARGS = /^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/; - var FN_ARG_SPLIT = /,/; - var FN_ARG = /(=.+)?(\s*)$/; +var formats = {}; - function stripComments(string) { - let stripped = ''; - let index = 0; - let endBlockComment = string.indexOf('*/'); - while (index < string.length) { - if (string[index] === '/' && string[index+1] === '/') { - // inline comment - let endIndex = string.indexOf('\n', index); - index = (endIndex === -1) ? string.length : endIndex; - } else if ((endBlockComment !== -1) && (string[index] === '/') && (string[index+1] === '*')) { - // block comment - let endIndex = string.indexOf('*/', index); - if (endIndex !== -1) { - index = endIndex + 2; - endBlockComment = string.indexOf('*/', index); - } else { - stripped += string[index]; - index++; - } - } else { - stripped += string[index]; - index++; - } - } - return stripped; - } +/** + * Dispenses a new Archiver instance. + * + * @constructor + * @param {String} format The archive format to use. + * @param {Object} options See [Archiver]{@link Archiver} + * @return {Archiver} + */ +var vending = function(format, options) { + return vending.create(format, options); +}; - function parseParams(func) { - const src = stripComments(func.toString()); - let match = src.match(FN_ARGS); - if (!match) { - match = src.match(ARROW_FN_ARGS); - } - if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src) - let [, args] = match; - return args - .replace(/\s/g, '') - .split(FN_ARG_SPLIT) - .map((arg) => arg.replace(FN_ARG, '').trim()); - } +/** + * Creates a new Archiver instance. + * + * @param {String} format The archive format to use. + * @param {Object} options See [Archiver]{@link Archiver} + * @return {Archiver} + */ +vending.create = function(format, options) { + if (formats[format]) { + var instance = new Archiver(format, options); + instance.setFormat(format); + instance.setModule(new formats[format](options)); - /** - * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent - * tasks are specified as parameters to the function, after the usual callback - * parameter, with the parameter names matching the names of the tasks it - * depends on. This can provide even more readable task graphs which can be - * easier to maintain. - * - * If a final callback is specified, the task results are similarly injected, - * specified as named parameters after the initial error parameter. - * - * The autoInject function is purely syntactic sugar and its semantics are - * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. - * - * @name autoInject - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.auto]{@link module:ControlFlow.auto} - * @category Control Flow - * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of - * the form 'func([dependencies...], callback). The object's key of a property - * serves as the name of the task defined by that property, i.e. can be used - * when specifying requirements for other tasks. - * * The `callback` parameter is a `callback(err, result)` which must be called - * when finished, passing an `error` (which can be `null`) and the result of - * the function's execution. The remaining parameters name other tasks on - * which the task is dependent, and the results from those tasks are the - * arguments of those parameters. - * @param {Function} [callback] - An optional callback which is called when all - * the tasks have been completed. It receives the `err` argument if any `tasks` - * pass an error to their callback, and a `results` object with any completed - * task results, similar to `auto`. - * @returns {Promise} a promise, if no callback is passed - * @example - * - * // The example from `auto` can be rewritten as follows: - * async.autoInject({ - * get_data: function(callback) { - * // async code to get some data - * callback(null, 'data', 'converted to array'); - * }, - * make_folder: function(callback) { - * // async code to create a directory to store a file in - * // this is run at the same time as getting the data - * callback(null, 'folder'); - * }, - * write_file: function(get_data, make_folder, callback) { - * // once there is some data and the directory exists, - * // write the data to a file in the directory - * callback(null, 'filename'); - * }, - * email_link: function(write_file, callback) { - * // once the file is written let's email a link to it... - * // write_file contains the filename returned by write_file. - * callback(null, {'file':write_file, 'email':'user@example.com'}); - * } - * }, function(err, results) { - * console.log('err = ', err); - * console.log('email_link = ', results.email_link); - * }); - * - * // If you are using a JS minifier that mangles parameter names, `autoInject` - * // will not work with plain functions, since the parameter names will be - * // collapsed to a single letter identifier. To work around this, you can - * // explicitly specify the names of the parameters your task function needs - * // in an array, similar to Angular.js dependency injection. - * - * // This still has an advantage over plain `auto`, since the results a task - * // depends on are still spread into arguments. - * async.autoInject({ - * //... - * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { - * callback(null, 'filename'); - * }], - * email_link: ['write_file', function(write_file, callback) { - * callback(null, {'file':write_file, 'email':'user@example.com'}); - * }] - * //... - * }, function(err, results) { - * console.log('err = ', err); - * console.log('email_link = ', results.email_link); - * }); - */ - function autoInject(tasks, callback) { - var newTasks = {}; + return instance; + } else { + throw new Error('create(' + format + '): format not registered'); + } +}; - Object.keys(tasks).forEach(key => { - var taskFn = tasks[key]; - var params; - var fnIsAsync = isAsync(taskFn); - var hasNoDeps = - (!fnIsAsync && taskFn.length === 1) || - (fnIsAsync && taskFn.length === 0); +/** + * Registers a format for use with archiver. + * + * @param {String} format The name of the format. + * @param {Function} module The function for archiver to interact with. + * @return void + */ +vending.registerFormat = function(format, module) { + if (formats[format]) { + throw new Error('register(' + format + '): format already registered'); + } - if (Array.isArray(taskFn)) { - params = [...taskFn]; - taskFn = params.pop(); + if (typeof module !== 'function') { + throw new Error('register(' + format + '): format module invalid'); + } - newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); - } else if (hasNoDeps) { - // no dependencies, use the function as-is - newTasks[key] = taskFn; - } else { - params = parseParams(taskFn); - if ((taskFn.length === 0 && !fnIsAsync) && params.length === 0) { - throw new Error("autoInject task functions require explicit parameters."); - } + if (typeof module.prototype.append !== 'function' || typeof module.prototype.finalize !== 'function') { + throw new Error('register(' + format + '): format module missing methods'); + } - // remove callback param - if (!fnIsAsync) params.pop(); + formats[format] = module; +}; - newTasks[key] = params.concat(newTask); - } +/** + * Check if the format is already registered. + * + * @param {String} format the name of the format. + * @return boolean + */ +vending.isRegisteredFormat = function (format) { + if (formats[format]) { + return true; + } + + return false; +}; - function newTask(results, taskCb) { - var newArgs = params.map(name => results[name]); - newArgs.push(taskCb); - wrapAsync(taskFn)(...newArgs); - } - }); +vending.registerFormat('zip', __nccwpck_require__(8987)); +vending.registerFormat('tar', __nccwpck_require__(33614)); +vending.registerFormat('json', __nccwpck_require__(99827)); - return auto(newTasks, callback); - } +module.exports = vending; - // Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation - // used for queues. This implementation assumes that the node provided by the user can be modified - // to adjust the next and last properties. We implement only the minimal functionality - // for queue support. - class DLL { - constructor() { - this.head = this.tail = null; - this.length = 0; - } +/***/ }), - removeLink(node) { - if (node.prev) node.prev.next = node.next; - else this.head = node.next; - if (node.next) node.next.prev = node.prev; - else this.tail = node.prev; +/***/ 35010: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - node.prev = node.next = null; - this.length -= 1; - return node; - } +/** + * Archiver Core + * + * @ignore + * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} + * @copyright (c) 2012-2014 Chris Talkington, contributors. + */ +var fs = __nccwpck_require__(57147); +var glob = __nccwpck_require__(44967); +var async = __nccwpck_require__(57888); +var path = __nccwpck_require__(71017); +var util = __nccwpck_require__(82072); - empty () { - while(this.head) this.shift(); - return this; - } +var inherits = (__nccwpck_require__(73837).inherits); +var ArchiverError = __nccwpck_require__(13143); +var Transform = (__nccwpck_require__(51642).Transform); - insertAfter(node, newNode) { - newNode.prev = node; - newNode.next = node.next; - if (node.next) node.next.prev = newNode; - else this.tail = newNode; - node.next = newNode; - this.length += 1; - } +var win32 = process.platform === 'win32'; - insertBefore(node, newNode) { - newNode.prev = node.prev; - newNode.next = node; - if (node.prev) node.prev.next = newNode; - else this.head = newNode; - node.prev = newNode; - this.length += 1; - } - - unshift(node) { - if (this.head) this.insertBefore(this.head, node); - else setInitial(this, node); - } - - push(node) { - if (this.tail) this.insertAfter(this.tail, node); - else setInitial(this, node); - } - - shift() { - return this.head && this.removeLink(this.head); - } - - pop() { - return this.tail && this.removeLink(this.tail); - } - - toArray() { - return [...this] - } - - *[Symbol.iterator] () { - var cur = this.head; - while (cur) { - yield cur.data; - cur = cur.next; - } - } +/** + * @constructor + * @param {String} format The archive format to use. + * @param {(CoreOptions|TransformOptions)} options See also {@link ZipOptions} and {@link TarOptions}. + */ +var Archiver = function(format, options) { + if (!(this instanceof Archiver)) { + return new Archiver(format, options); + } - remove (testFn) { - var curr = this.head; - while(curr) { - var {next} = curr; - if (testFn(curr)) { - this.removeLink(curr); - } - curr = next; - } - return this; - } - } + if (typeof format !== 'string') { + options = format; + format = 'zip'; + } - function setInitial(dll, node) { - dll.length = 1; - dll.head = dll.tail = node; - } + options = this.options = util.defaults(options, { + highWaterMark: 1024 * 1024, + statConcurrency: 4 + }); - function queue(worker, concurrency, payload) { - if (concurrency == null) { - concurrency = 1; - } - else if(concurrency === 0) { - throw new RangeError('Concurrency must not be zero'); - } + Transform.call(this, options); - var _worker = wrapAsync(worker); - var numRunning = 0; - var workersList = []; - const events = { - error: [], - drain: [], - saturated: [], - unsaturated: [], - empty: [] - }; + this._format = false; + this._module = false; + this._pending = 0; + this._pointer = 0; - function on (event, handler) { - events[event].push(handler); - } + this._entriesCount = 0; + this._entriesProcessedCount = 0; + this._fsEntriesTotalBytes = 0; + this._fsEntriesProcessedBytes = 0; - function once (event, handler) { - const handleAndRemove = (...args) => { - off(event, handleAndRemove); - handler(...args); - }; - events[event].push(handleAndRemove); - } + this._queue = async.queue(this._onQueueTask.bind(this), 1); + this._queue.drain(this._onQueueDrain.bind(this)); - function off (event, handler) { - if (!event) return Object.keys(events).forEach(ev => events[ev] = []) - if (!handler) return events[event] = [] - events[event] = events[event].filter(ev => ev !== handler); - } + this._statQueue = async.queue(this._onStatQueueTask.bind(this), options.statConcurrency); + this._statQueue.drain(this._onQueueDrain.bind(this)); - function trigger (event, ...args) { - events[event].forEach(handler => handler(...args)); - } + this._state = { + aborted: false, + finalize: false, + finalizing: false, + finalized: false, + modulePiped: false + }; - var processingScheduled = false; - function _insert(data, insertAtFront, rejectOnError, callback) { - if (callback != null && typeof callback !== 'function') { - throw new Error('task callback must be a function'); - } - q.started = true; + this._streams = []; +}; - var res, rej; - function promiseCallback (err, ...args) { - // we don't care about the error, let the global error handler - // deal with it - if (err) return rejectOnError ? rej(err) : res() - if (args.length <= 1) return res(args[0]) - res(args); - } +inherits(Archiver, Transform); - var item = q._createTaskItem( - data, - rejectOnError ? promiseCallback : - (callback || promiseCallback) - ); +/** + * Internal logic for `abort`. + * + * @private + * @return void + */ +Archiver.prototype._abort = function() { + this._state.aborted = true; + this._queue.kill(); + this._statQueue.kill(); - if (insertAtFront) { - q._tasks.unshift(item); - } else { - q._tasks.push(item); - } + if (this._queue.idle()) { + this._shutdown(); + } +}; - if (!processingScheduled) { - processingScheduled = true; - setImmediate$1(() => { - processingScheduled = false; - q.process(); - }); - } +/** + * Internal helper for appending files. + * + * @private + * @param {String} filepath The source filepath. + * @param {EntryData} data The entry data. + * @return void + */ +Archiver.prototype._append = function(filepath, data) { + data = data || {}; - if (rejectOnError || !callback) { - return new Promise((resolve, reject) => { - res = resolve; - rej = reject; - }) - } - } + var task = { + source: null, + filepath: filepath + }; - function _createCB(tasks) { - return function (err, ...args) { - numRunning -= 1; + if (!data.name) { + data.name = filepath; + } - for (var i = 0, l = tasks.length; i < l; i++) { - var task = tasks[i]; + data.sourcePath = filepath; + task.data = data; + this._entriesCount++; - var index = workersList.indexOf(task); - if (index === 0) { - workersList.shift(); - } else if (index > 0) { - workersList.splice(index, 1); - } + if (data.stats && data.stats instanceof fs.Stats) { + task = this._updateQueueTaskWithStats(task, data.stats); + if (task) { + if (data.stats.size) { + this._fsEntriesTotalBytes += data.stats.size; + } - task.callback(err, ...args); + this._queue.push(task); + } + } else { + this._statQueue.push(task); + } +}; - if (err != null) { - trigger('error', err, task.data); - } - } +/** + * Internal logic for `finalize`. + * + * @private + * @return void + */ +Archiver.prototype._finalize = function() { + if (this._state.finalizing || this._state.finalized || this._state.aborted) { + return; + } - if (numRunning <= (q.concurrency - q.buffer) ) { - trigger('unsaturated'); - } + this._state.finalizing = true; - if (q.idle()) { - trigger('drain'); - } - q.process(); - }; - } + this._moduleFinalize(); - function _maybeDrain(data) { - if (data.length === 0 && q.idle()) { - // call drain immediately if there are no tasks - setImmediate$1(() => trigger('drain')); - return true - } - return false - } + this._state.finalizing = false; + this._state.finalized = true; +}; - const eventMethod = (name) => (handler) => { - if (!handler) { - return new Promise((resolve, reject) => { - once(name, (err, data) => { - if (err) return reject(err) - resolve(data); - }); - }) - } - off(name); - on(name, handler); +/** + * Checks the various state variables to determine if we can `finalize`. + * + * @private + * @return {Boolean} + */ +Archiver.prototype._maybeFinalize = function() { + if (this._state.finalizing || this._state.finalized || this._state.aborted) { + return false; + } - }; + if (this._state.finalize && this._pending === 0 && this._queue.idle() && this._statQueue.idle()) { + this._finalize(); + return true; + } - var isProcessing = false; - var q = { - _tasks: new DLL(), - _createTaskItem (data, callback) { - return { - data, - callback - }; - }, - *[Symbol.iterator] () { - yield* q._tasks[Symbol.iterator](); - }, - concurrency, - payload, - buffer: concurrency / 4, - started: false, - paused: false, - push (data, callback) { - if (Array.isArray(data)) { - if (_maybeDrain(data)) return - return data.map(datum => _insert(datum, false, false, callback)) - } - return _insert(data, false, false, callback); - }, - pushAsync (data, callback) { - if (Array.isArray(data)) { - if (_maybeDrain(data)) return - return data.map(datum => _insert(datum, false, true, callback)) - } - return _insert(data, false, true, callback); - }, - kill () { - off(); - q._tasks.empty(); - }, - unshift (data, callback) { - if (Array.isArray(data)) { - if (_maybeDrain(data)) return - return data.map(datum => _insert(datum, true, false, callback)) - } - return _insert(data, true, false, callback); - }, - unshiftAsync (data, callback) { - if (Array.isArray(data)) { - if (_maybeDrain(data)) return - return data.map(datum => _insert(datum, true, true, callback)) - } - return _insert(data, true, true, callback); - }, - remove (testFn) { - q._tasks.remove(testFn); - }, - process () { - // Avoid trying to start too many processing operations. This can occur - // when callbacks resolve synchronously (#1267). - if (isProcessing) { - return; - } - isProcessing = true; - while(!q.paused && numRunning < q.concurrency && q._tasks.length){ - var tasks = [], data = []; - var l = q._tasks.length; - if (q.payload) l = Math.min(l, q.payload); - for (var i = 0; i < l; i++) { - var node = q._tasks.shift(); - tasks.push(node); - workersList.push(node); - data.push(node.data); - } + return false; +}; - numRunning += 1; +/** + * Appends an entry to the module. + * + * @private + * @fires Archiver#entry + * @param {(Buffer|Stream)} source + * @param {EntryData} data + * @param {Function} callback + * @return void + */ +Archiver.prototype._moduleAppend = function(source, data, callback) { + if (this._state.aborted) { + callback(); + return; + } - if (q._tasks.length === 0) { - trigger('empty'); - } + this._module.append(source, data, function(err) { + this._task = null; - if (numRunning === q.concurrency) { - trigger('saturated'); - } + if (this._state.aborted) { + this._shutdown(); + return; + } - var cb = onlyOnce(_createCB(tasks)); - _worker(data, cb); - } - isProcessing = false; - }, - length () { - return q._tasks.length; - }, - running () { - return numRunning; - }, - workersList () { - return workersList; - }, - idle() { - return q._tasks.length + numRunning === 0; - }, - pause () { - q.paused = true; - }, - resume () { - if (q.paused === false) { return; } - q.paused = false; - setImmediate$1(q.process); - } - }; - // define these as fixed properties, so people get useful errors when updating - Object.defineProperties(q, { - saturated: { - writable: false, - value: eventMethod('saturated') - }, - unsaturated: { - writable: false, - value: eventMethod('unsaturated') - }, - empty: { - writable: false, - value: eventMethod('empty') - }, - drain: { - writable: false, - value: eventMethod('drain') - }, - error: { - writable: false, - value: eventMethod('error') - }, - }); - return q; + if (err) { + this.emit('error', err); + setImmediate(callback); + return; } /** - * Creates a `cargo` object with the specified payload. Tasks added to the - * cargo will be processed altogether (up to the `payload` limit). If the - * `worker` is in progress, the task is queued until it becomes available. Once - * the `worker` has completed some tasks, each callback of those tasks is - * called. Check out [these](https://github.com/camo/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://github.com/camo/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) - * for how `cargo` and `queue` work. - * - * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers - * at a time, cargo passes an array of tasks to a single worker, repeating - * when the worker is finished. - * - * @name cargo - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.queue]{@link module:ControlFlow.queue} - * @category Control Flow - * @param {AsyncFunction} worker - An asynchronous function for processing an array - * of queued tasks. Invoked with `(tasks, callback)`. - * @param {number} [payload=Infinity] - An optional `integer` for determining - * how many tasks should be processed per round; if omitted, the default is - * unlimited. - * @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can - * attached as certain properties to listen for specific events during the - * lifecycle of the cargo and inner queue. - * @example - * - * // create a cargo object with payload 2 - * var cargo = async.cargo(function(tasks, callback) { - * for (var i=0; i { - * console.log(result); - * // 6000 - * // which is the sum of the file sizes of the three files - * }).catch( err => { - * console.log(err); - * }); - * - * // Error Handling - * async.reduce(withMissingFileList, 0, getFileSizeInBytes) - * .then( result => { - * console.log(result); - * }).catch( err => { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * }); - * - * // Using async/await - * async () => { - * try { - * let result = await async.reduce(fileList, 0, getFileSizeInBytes); - * console.log(result); - * // 6000 - * // which is the sum of the file sizes of the three files - * } - * catch (err) { - * console.log(err); - * } - * } - * - * // Error Handling - * async () => { - * try { - * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); - * console.log(result); - * } - * catch (err) { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * } - * } - * - */ - function reduce(coll, memo, iteratee, callback) { - callback = once(callback); - var _iteratee = wrapAsync(iteratee); - return eachOfSeries$1(coll, (x, i, iterCb) => { - _iteratee(memo, x, (err, v) => { - memo = v; - iterCb(err); - }); - }, err => callback(err, memo)); - } - var reduce$1 = awaitify(reduce, 4); + setImmediate(callback); + }.bind(this)); +}; - /** - * Version of the compose function that is more natural to read. Each function - * consumes the return value of the previous function. It is the equivalent of - * [compose]{@link module:ControlFlow.compose} with the arguments reversed. - * - * Each function is executed with the `this` binding of the composed function. - * - * @name seq - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.compose]{@link module:ControlFlow.compose} - * @category Control Flow - * @param {...AsyncFunction} functions - the asynchronous functions to compose - * @returns {Function} a function that composes the `functions` in order - * @example - * - * // Requires lodash (or underscore), express3 and dresende's orm2. - * // Part of an app, that fetches cats of the logged user. - * // This example uses `seq` function to avoid overnesting and error - * // handling clutter. - * app.get('/cats', function(request, response) { - * var User = request.models.User; - * async.seq( - * User.get.bind(User), // 'User.get' has signature (id, callback(err, data)) - * function(user, fn) { - * user.getCats(fn); // 'getCats' has signature (callback(err, data)) - * } - * )(req.session.user_id, function (err, cats) { - * if (err) { - * console.error(err); - * response.json({ status: 'error', message: err.message }); - * } else { - * response.json({ status: 'ok', message: 'Cats found', data: cats }); - * } - * }); - * }); - */ - function seq(...functions) { - var _functions = functions.map(wrapAsync); - return function (...args) { - var that = this; +/** + * Finalizes the module. + * + * @private + * @return void + */ +Archiver.prototype._moduleFinalize = function() { + if (typeof this._module.finalize === 'function') { + this._module.finalize(); + } else if (typeof this._module.end === 'function') { + this._module.end(); + } else { + this.emit('error', new ArchiverError('NOENDMETHOD')); + } +}; - var cb = args[args.length - 1]; - if (typeof cb == 'function') { - args.pop(); - } else { - cb = promiseCallback(); - } +/** + * Pipes the module to our internal stream with error bubbling. + * + * @private + * @return void + */ +Archiver.prototype._modulePipe = function() { + this._module.on('error', this._onModuleError.bind(this)); + this._module.pipe(this); + this._state.modulePiped = true; +}; - reduce$1(_functions, args, (newargs, fn, iterCb) => { - fn.apply(that, newargs.concat((err, ...nextargs) => { - iterCb(err, nextargs); - })); - }, - (err, results) => cb(err, ...results)); +/** + * Determines if the current module supports a defined feature. + * + * @private + * @param {String} key + * @return {Boolean} + */ +Archiver.prototype._moduleSupports = function(key) { + if (!this._module.supports || !this._module.supports[key]) { + return false; + } - return cb[PROMISE_SYMBOL] - }; + return this._module.supports[key]; +}; + +/** + * Unpipes the module from our internal stream. + * + * @private + * @return void + */ +Archiver.prototype._moduleUnpipe = function() { + this._module.unpipe(this); + this._state.modulePiped = false; +}; + +/** + * Normalizes entry data with fallbacks for key properties. + * + * @private + * @param {Object} data + * @param {fs.Stats} stats + * @return {Object} + */ +Archiver.prototype._normalizeEntryData = function(data, stats) { + data = util.defaults(data, { + type: 'file', + name: null, + date: null, + mode: null, + prefix: null, + sourcePath: null, + stats: false + }); + + if (stats && data.stats === false) { + data.stats = stats; + } + + var isDir = data.type === 'directory'; + + if (data.name) { + if (typeof data.prefix === 'string' && '' !== data.prefix) { + data.name = data.prefix + '/' + data.name; + data.prefix = null; } - /** - * Creates a function which is a composition of the passed asynchronous - * functions. Each function consumes the return value of the function that - * follows. Composing functions `f()`, `g()`, and `h()` would produce the result - * of `f(g(h()))`, only this version uses callbacks to obtain the return values. - * - * If the last argument to the composed function is not a function, a promise - * is returned when you call it. - * - * Each function is executed with the `this` binding of the composed function. - * - * @name compose - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {...AsyncFunction} functions - the asynchronous functions to compose - * @returns {Function} an asynchronous function that is the composed - * asynchronous `functions` - * @example - * - * function add1(n, callback) { - * setTimeout(function () { - * callback(null, n + 1); - * }, 10); - * } - * - * function mul3(n, callback) { - * setTimeout(function () { - * callback(null, n * 3); - * }, 10); - * } - * - * var add1mul3 = async.compose(mul3, add1); - * add1mul3(4, function (err, result) { - * // result now equals 15 - * }); - */ - function compose(...args) { - return seq(...args.reverse()); + data.name = util.sanitizePath(data.name); + + if (data.type !== 'symlink' && data.name.slice(-1) === '/') { + isDir = true; + data.type = 'directory'; + } else if (isDir) { + data.name += '/'; } + } - /** - * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. - * - * @name mapLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.map]{@link module:Collections.map} - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an array of the - * transformed items from the `coll`. Invoked with (err, results). - * @returns {Promise} a promise, if no callback is passed - */ - function mapLimit (coll, limit, iteratee, callback) { - return _asyncMap(eachOfLimit(limit), coll, iteratee, callback) + // 511 === 0777; 493 === 0755; 438 === 0666; 420 === 0644 + if (typeof data.mode === 'number') { + if (win32) { + data.mode &= 511; + } else { + data.mode &= 4095 + } + } else if (data.stats && data.mode === null) { + if (win32) { + data.mode = data.stats.mode & 511; + } else { + data.mode = data.stats.mode & 4095; } - var mapLimit$1 = awaitify(mapLimit, 4); - /** - * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. - * - * @name concatLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.concat]{@link module:Collections.concat} - * @category Collection - * @alias flatMapLimit - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, - * which should use an array as its result. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is an array - * containing the concatenated results of the `iteratee` function. Invoked with - * (err, results). - * @returns A Promise, if no callback is passed - */ - function concatLimit(coll, limit, iteratee, callback) { - var _iteratee = wrapAsync(iteratee); - return mapLimit$1(coll, limit, (val, iterCb) => { - _iteratee(val, (err, ...args) => { - if (err) return iterCb(err); - return iterCb(err, args); - }); - }, (err, mapResults) => { - var result = []; - for (var i = 0; i < mapResults.length; i++) { - if (mapResults[i]) { - result = result.concat(...mapResults[i]); - } - } + // stat isn't reliable on windows; force 0755 for dir + if (win32 && isDir) { + data.mode = 493; + } + } else if (data.mode === null) { + data.mode = isDir ? 493 : 420; + } - return callback(err, result); - }); + if (data.stats && data.date === null) { + data.date = data.stats.mtime; + } else { + data.date = util.dateify(data.date); + } + + return data; +}; + +/** + * Error listener that re-emits error on to our internal stream. + * + * @private + * @param {Error} err + * @return void + */ +Archiver.prototype._onModuleError = function(err) { + /** + * @event Archiver#error + * @type {ErrorData} + */ + this.emit('error', err); +}; + +/** + * Checks the various state variables after queue has drained to determine if + * we need to `finalize`. + * + * @private + * @return void + */ +Archiver.prototype._onQueueDrain = function() { + if (this._state.finalizing || this._state.finalized || this._state.aborted) { + return; + } + + if (this._state.finalize && this._pending === 0 && this._queue.idle() && this._statQueue.idle()) { + this._finalize(); + } +}; + +/** + * Appends each queue task to the module. + * + * @private + * @param {Object} task + * @param {Function} callback + * @return void + */ +Archiver.prototype._onQueueTask = function(task, callback) { + var fullCallback = () => { + if(task.data.callback) { + task.data.callback(); } - var concatLimit$1 = awaitify(concatLimit, 4); + callback(); + } - /** - * Applies `iteratee` to each item in `coll`, concatenating the results. Returns - * the concatenated list. The `iteratee`s are called in parallel, and the - * results are concatenated as they return. The results array will be returned in - * the original order of `coll` passed to the `iteratee` function. - * - * @name concat - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @alias flatMap - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, - * which should use an array as its result. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is an array - * containing the concatenated results of the `iteratee` function. Invoked with - * (err, results). - * @returns A Promise, if no callback is passed - * @example - * - * // dir1 is a directory that contains file1.txt, file2.txt - * // dir2 is a directory that contains file3.txt, file4.txt - * // dir3 is a directory that contains file5.txt - * // dir4 does not exist - * - * let directoryList = ['dir1','dir2','dir3']; - * let withMissingDirectoryList = ['dir1','dir2','dir3', 'dir4']; - * - * // Using callbacks - * async.concat(directoryList, fs.readdir, function(err, results) { - * if (err) { - * console.log(err); - * } else { - * console.log(results); - * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] - * } - * }); - * - * // Error Handling - * async.concat(withMissingDirectoryList, fs.readdir, function(err, results) { - * if (err) { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * // since dir4 does not exist - * } else { - * console.log(results); - * } - * }); - * - * // Using Promises - * async.concat(directoryList, fs.readdir) - * .then(results => { - * console.log(results); - * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] - * }).catch(err => { - * console.log(err); - * }); - * - * // Error Handling - * async.concat(withMissingDirectoryList, fs.readdir) - * .then(results => { - * console.log(results); - * }).catch(err => { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * // since dir4 does not exist - * }); - * - * // Using async/await - * async () => { - * try { - * let results = await async.concat(directoryList, fs.readdir); - * console.log(results); - * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] - * } catch (err) { - * console.log(err); - * } - * } - * - * // Error Handling - * async () => { - * try { - * let results = await async.concat(withMissingDirectoryList, fs.readdir); - * console.log(results); - * } catch (err) { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * // since dir4 does not exist - * } - * } - * - */ - function concat(coll, iteratee, callback) { - return concatLimit$1(coll, Infinity, iteratee, callback) - } - var concat$1 = awaitify(concat, 3); - - /** - * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. - * - * @name concatSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.concat]{@link module:Collections.concat} - * @category Collection - * @alias flatMapSeries - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. - * The iteratee should complete with an array an array of results. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is an array - * containing the concatenated results of the `iteratee` function. Invoked with - * (err, results). - * @returns A Promise, if no callback is passed - */ - function concatSeries(coll, iteratee, callback) { - return concatLimit$1(coll, 1, iteratee, callback) - } - var concatSeries$1 = awaitify(concatSeries, 3); + if (this._state.finalizing || this._state.finalized || this._state.aborted) { + fullCallback(); + return; + } - /** - * Returns a function that when called, calls-back with the values provided. - * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to - * [`auto`]{@link module:ControlFlow.auto}. - * - * @name constant - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {...*} arguments... - Any number of arguments to automatically invoke - * callback with. - * @returns {AsyncFunction} Returns a function that when invoked, automatically - * invokes the callback with the previous given arguments. - * @example - * - * async.waterfall([ - * async.constant(42), - * function (value, next) { - * // value === 42 - * }, - * //... - * ], callback); - * - * async.waterfall([ - * async.constant(filename, "utf8"), - * fs.readFile, - * function (fileData, next) { - * //... - * } - * //... - * ], callback); - * - * async.auto({ - * hostname: async.constant("https://server.net/"), - * port: findFreePort, - * launchServer: ["hostname", "port", function (options, cb) { - * startServer(options, cb); - * }], - * //... - * }, callback); - */ - function constant(...args) { - return function (...ignoredArgs/*, callback*/) { - var callback = ignoredArgs.pop(); - return callback(null, ...args); - }; - } + this._task = task; + this._moduleAppend(task.source, task.data, fullCallback); +}; - function _createTester(check, getResult) { - return (eachfn, arr, _iteratee, cb) => { - var testPassed = false; - var testResult; - const iteratee = wrapAsync(_iteratee); - eachfn(arr, (value, _, callback) => { - iteratee(value, (err, result) => { - if (err || err === false) return callback(err); +/** + * Performs a file stat and reinjects the task back into the queue. + * + * @private + * @param {Object} task + * @param {Function} callback + * @return void + */ +Archiver.prototype._onStatQueueTask = function(task, callback) { + if (this._state.finalizing || this._state.finalized || this._state.aborted) { + callback(); + return; + } - if (check(result) && !testResult) { - testPassed = true; - testResult = getResult(true, value); - return callback(null, breakLoop); - } - callback(); - }); - }, err => { - if (err) return cb(err); - cb(null, testPassed ? testResult : getResult(false)); - }); - }; + fs.lstat(task.filepath, function(err, stats) { + if (this._state.aborted) { + setImmediate(callback); + return; } - /** - * Returns the first value in `coll` that passes an async truth test. The - * `iteratee` is applied in parallel, meaning the first iteratee to return - * `true` will fire the detect `callback` with that result. That means the - * result might not be the first item in the original `coll` (in terms of order) - * that passes the test. - - * If order within the original `coll` is important, then look at - * [`detectSeries`]{@link module:Collections.detectSeries}. - * - * @name detect - * @static - * @memberOf module:Collections - * @method - * @alias find - * @category Collections - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - * @returns {Promise} a promise, if a callback is omitted - * @example - * - * // dir1 is a directory that contains file1.txt, file2.txt - * // dir2 is a directory that contains file3.txt, file4.txt - * // dir3 is a directory that contains file5.txt - * - * // asynchronous function that checks if a file exists - * function fileExists(file, callback) { - * fs.access(file, fs.constants.F_OK, (err) => { - * callback(null, !err); - * }); - * } - * - * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists, - * function(err, result) { - * console.log(result); - * // dir1/file1.txt - * // result now equals the first file in the list that exists - * } - *); - * - * // Using Promises - * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists) - * .then(result => { - * console.log(result); - * // dir1/file1.txt - * // result now equals the first file in the list that exists - * }).catch(err => { - * console.log(err); - * }); - * - * // Using async/await - * async () => { - * try { - * let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists); - * console.log(result); - * // dir1/file1.txt - * // result now equals the file in the list that exists - * } - * catch (err) { - * console.log(err); - * } - * } - * - */ - function detect(coll, iteratee, callback) { - return _createTester(bool => bool, (res, item) => item)(eachOf$1, coll, iteratee, callback) - } - var detect$1 = awaitify(detect, 3); + if (err) { + this._entriesCount--; - /** - * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a - * time. - * - * @name detectLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.detect]{@link module:Collections.detect} - * @alias findLimit - * @category Collections - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - * @returns {Promise} a promise, if a callback is omitted - */ - function detectLimit(coll, limit, iteratee, callback) { - return _createTester(bool => bool, (res, item) => item)(eachOfLimit(limit), coll, iteratee, callback) + /** + * @event Archiver#warning + * @type {ErrorData} + */ + this.emit('warning', err); + setImmediate(callback); + return; } - var detectLimit$1 = awaitify(detectLimit, 4); - /** - * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. - * - * @name detectSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.detect]{@link module:Collections.detect} - * @alias findSeries - * @category Collections - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - * @returns {Promise} a promise, if a callback is omitted - */ - function detectSeries(coll, iteratee, callback) { - return _createTester(bool => bool, (res, item) => item)(eachOfLimit(1), coll, iteratee, callback) - } + task = this._updateQueueTaskWithStats(task, stats); - var detectSeries$1 = awaitify(detectSeries, 3); + if (task) { + if (stats.size) { + this._fsEntriesTotalBytes += stats.size; + } - function consoleFunc(name) { - return (fn, ...args) => wrapAsync(fn)(...args, (err, ...resultArgs) => { - /* istanbul ignore else */ - if (typeof console === 'object') { - /* istanbul ignore else */ - if (err) { - /* istanbul ignore else */ - if (console.error) { - console.error(err); - } - } else if (console[name]) { /* istanbul ignore else */ - resultArgs.forEach(x => console[name](x)); - } - } - }) + this._queue.push(task); } - /** - * Logs the result of an [`async` function]{@link AsyncFunction} to the - * `console` using `console.dir` to display the properties of the resulting object. - * Only works in Node.js or in browsers that support `console.dir` and - * `console.error` (such as FF and Chrome). - * If multiple arguments are returned from the async function, - * `console.dir` is called on each argument in order. - * - * @name dir - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} function - The function you want to eventually apply - * all arguments to. - * @param {...*} arguments... - Any number of arguments to apply to the function. - * @example - * - * // in a module - * var hello = function(name, callback) { - * setTimeout(function() { - * callback(null, {hello: name}); - * }, 1000); - * }; - * - * // in the node repl - * node> async.dir(hello, 'world'); - * {hello: 'world'} - */ - var dir = consoleFunc('dir'); + setImmediate(callback); + }.bind(this)); +}; - /** - * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in - * the order of operations, the arguments `test` and `iteratee` are switched. - * - * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. - * - * @name doWhilst - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {AsyncFunction} iteratee - A function which is called each time `test` - * passes. Invoked with (callback). - * @param {AsyncFunction} test - asynchronous truth test to perform after each - * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the - * non-error args from the previous callback of `iteratee`. - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `iteratee` has stopped. - * `callback` will be passed an error and any arguments passed to the final - * `iteratee`'s callback. Invoked with (err, [results]); - * @returns {Promise} a promise, if no callback is passed - */ - function doWhilst(iteratee, test, callback) { - callback = onlyOnce(callback); - var _fn = wrapAsync(iteratee); - var _test = wrapAsync(test); - var results; +/** + * Unpipes the module and ends our internal stream. + * + * @private + * @return void + */ +Archiver.prototype._shutdown = function() { + this._moduleUnpipe(); + this.end(); +}; - function next(err, ...args) { - if (err) return callback(err); - if (err === false) return; - results = args; - _test(...args, check); - } +/** + * Tracks the bytes emitted by our internal stream. + * + * @private + * @param {Buffer} chunk + * @param {String} encoding + * @param {Function} callback + * @return void + */ +Archiver.prototype._transform = function(chunk, encoding, callback) { + if (chunk) { + this._pointer += chunk.length; + } - function check(err, truth) { - if (err) return callback(err); - if (err === false) return; - if (!truth) return callback(null, ...results); - _fn(next); - } + callback(null, chunk); +}; - return check(null, true); +/** + * Updates and normalizes a queue task using stats data. + * + * @private + * @param {Object} task + * @param {fs.Stats} stats + * @return {Object} + */ +Archiver.prototype._updateQueueTaskWithStats = function(task, stats) { + if (stats.isFile()) { + task.data.type = 'file'; + task.data.sourceType = 'stream'; + task.source = util.lazyReadStream(task.filepath); + } else if (stats.isDirectory() && this._moduleSupports('directory')) { + task.data.name = util.trailingSlashIt(task.data.name); + task.data.type = 'directory'; + task.data.sourcePath = util.trailingSlashIt(task.filepath); + task.data.sourceType = 'buffer'; + task.source = Buffer.concat([]); + } else if (stats.isSymbolicLink() && this._moduleSupports('symlink')) { + var linkPath = fs.readlinkSync(task.filepath); + var dirName = path.dirname(task.filepath); + task.data.type = 'symlink'; + task.data.linkname = path.relative(dirName, path.resolve(dirName, linkPath)); + task.data.sourceType = 'buffer'; + task.source = Buffer.concat([]); + } else { + if (stats.isDirectory()) { + this.emit('warning', new ArchiverError('DIRECTORYNOTSUPPORTED', task.data)); + } else if (stats.isSymbolicLink()) { + this.emit('warning', new ArchiverError('SYMLINKNOTSUPPORTED', task.data)); + } else { + this.emit('warning', new ArchiverError('ENTRYNOTSUPPORTED', task.data)); } - var doWhilst$1 = awaitify(doWhilst, 3); + return null; + } - /** - * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the - * argument ordering differs from `until`. - * - * @name doUntil - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} - * @category Control Flow - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` fails. Invoked with (callback). - * @param {AsyncFunction} test - asynchronous truth test to perform after each - * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the - * non-error args from the previous callback of `iteratee` - * @param {Function} [callback] - A callback which is called after the test - * function has passed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - * @returns {Promise} a promise, if no callback is passed - */ - function doUntil(iteratee, test, callback) { - const _test = wrapAsync(test); - return doWhilst$1(iteratee, (...args) => { - const cb = args.pop(); - _test(...args, (err, truth) => cb (err, !truth)); - }, callback); - } + task.data = this._normalizeEntryData(task.data, stats); - function _withoutIndex(iteratee) { - return (value, index, callback) => iteratee(value, callback); - } + return task; +}; - /** - * Applies the function `iteratee` to each item in `coll`, in parallel. - * The `iteratee` is called with an item from the list, and a callback for when - * it has finished. If the `iteratee` passes an error to its `callback`, the - * main `callback` (for the `each` function) is immediately called with the - * error. - * - * Note, that since this function applies `iteratee` to each item in parallel, - * there is no guarantee that the iteratee functions will complete in order. - * - * @name each - * @static - * @memberOf module:Collections - * @method - * @alias forEach - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to - * each item in `coll`. Invoked with (item, callback). - * The array index is not passed to the iteratee. - * If you need the index, use `eachOf`. - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @returns {Promise} a promise, if a callback is omitted - * @example - * - * // dir1 is a directory that contains file1.txt, file2.txt - * // dir2 is a directory that contains file3.txt, file4.txt - * // dir3 is a directory that contains file5.txt - * // dir4 does not exist - * - * const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt']; - * const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt']; - * - * // asynchronous function that deletes a file - * const deleteFile = function(file, callback) { - * fs.unlink(file, callback); - * }; - * - * // Using callbacks - * async.each(fileList, deleteFile, function(err) { - * if( err ) { - * console.log(err); - * } else { - * console.log('All files have been deleted successfully'); - * } - * }); - * - * // Error Handling - * async.each(withMissingFileList, deleteFile, function(err){ - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * // since dir4/file2.txt does not exist - * // dir1/file1.txt could have been deleted - * }); - * - * // Using Promises - * async.each(fileList, deleteFile) - * .then( () => { - * console.log('All files have been deleted successfully'); - * }).catch( err => { - * console.log(err); - * }); - * - * // Error Handling - * async.each(fileList, deleteFile) - * .then( () => { - * console.log('All files have been deleted successfully'); - * }).catch( err => { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * // since dir4/file2.txt does not exist - * // dir1/file1.txt could have been deleted - * }); - * - * // Using async/await - * async () => { - * try { - * await async.each(files, deleteFile); - * } - * catch (err) { - * console.log(err); - * } - * } - * - * // Error Handling - * async () => { - * try { - * await async.each(withMissingFileList, deleteFile); - * } - * catch (err) { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * // since dir4/file2.txt does not exist - * // dir1/file1.txt could have been deleted - * } - * } - * - */ - function eachLimit(coll, iteratee, callback) { - return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback); - } +/** + * Aborts the archiving process, taking a best-effort approach, by: + * + * - removing any pending queue tasks + * - allowing any active queue workers to finish + * - detaching internal module pipes + * - ending both sides of the Transform stream + * + * It will NOT drain any remaining sources. + * + * @return {this} + */ +Archiver.prototype.abort = function() { + if (this._state.aborted || this._state.finalized) { + return this; + } - var each = awaitify(eachLimit, 3); + this._abort(); - /** - * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. - * - * @name eachLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachLimit - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfLimit`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @returns {Promise} a promise, if a callback is omitted - */ - function eachLimit$1(coll, limit, iteratee, callback) { - return eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); - } - var eachLimit$2 = awaitify(eachLimit$1, 4); + return this; +}; - /** - * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. - * - * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item - * in series and therefore the iteratee functions will complete in order. +/** + * Appends an input source (text string, buffer, or stream) to the instance. + * + * When the instance has received, processed, and emitted the input, the `entry` + * event is fired. + * + * @fires Archiver#entry + * @param {(Buffer|Stream|String)} source The input source. + * @param {EntryData} data See also {@link ZipEntryData} and {@link TarEntryData}. + * @return {this} + */ +Archiver.prototype.append = function(source, data) { + if (this._state.finalize || this._state.aborted) { + this.emit('error', new ArchiverError('QUEUECLOSED')); + return this; + } - * @name eachSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachSeries - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfSeries`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @returns {Promise} a promise, if a callback is omitted - */ - function eachSeries(coll, iteratee, callback) { - return eachLimit$2(coll, 1, iteratee, callback) - } - var eachSeries$1 = awaitify(eachSeries, 3); + data = this._normalizeEntryData(data); - /** - * Wrap an async function and ensure it calls its callback on a later tick of - * the event loop. If the function already calls its callback on a next tick, - * no extra deferral is added. This is useful for preventing stack overflows - * (`RangeError: Maximum call stack size exceeded`) and generally keeping - * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) - * contained. ES2017 `async` functions are returned as-is -- they are immune - * to Zalgo's corrupting influences, as they always resolve on a later tick. - * - * @name ensureAsync - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - an async function, one that expects a node-style - * callback as its last argument. - * @returns {AsyncFunction} Returns a wrapped function with the exact same call - * signature as the function passed in. - * @example - * - * function sometimesAsync(arg, callback) { - * if (cache[arg]) { - * return callback(null, cache[arg]); // this would be synchronous!! - * } else { - * doSomeIO(arg, callback); // this IO would be asynchronous - * } - * } - * - * // this has a risk of stack overflows if many results are cached in a row - * async.mapSeries(args, sometimesAsync, done); - * - * // this will defer sometimesAsync's callback if necessary, - * // preventing stack overflows - * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); - */ - function ensureAsync(fn) { - if (isAsync(fn)) return fn; - return function (...args/*, callback*/) { - var callback = args.pop(); - var sync = true; - args.push((...innerArgs) => { - if (sync) { - setImmediate$1(() => callback(...innerArgs)); - } else { - callback(...innerArgs); - } - }); - fn.apply(this, args); - sync = false; - }; - } + if (typeof data.name !== 'string' || data.name.length === 0) { + this.emit('error', new ArchiverError('ENTRYNAMEREQUIRED')); + return this; + } - /** - * Returns `true` if every element in `coll` satisfies an async test. If any - * iteratee call returns `false`, the main `callback` is immediately called. - * - * @name every - * @static - * @memberOf module:Collections - * @method - * @alias all - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in parallel. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - * @returns {Promise} a promise, if no callback provided - * @example - * - * // dir1 is a directory that contains file1.txt, file2.txt - * // dir2 is a directory that contains file3.txt, file4.txt - * // dir3 is a directory that contains file5.txt - * // dir4 does not exist - * - * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt']; - * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; - * - * // asynchronous function that checks if a file exists - * function fileExists(file, callback) { - * fs.access(file, fs.constants.F_OK, (err) => { - * callback(null, !err); - * }); - * } - * - * // Using callbacks - * async.every(fileList, fileExists, function(err, result) { - * console.log(result); - * // true - * // result is true since every file exists - * }); - * - * async.every(withMissingFileList, fileExists, function(err, result) { - * console.log(result); - * // false - * // result is false since NOT every file exists - * }); - * - * // Using Promises - * async.every(fileList, fileExists) - * .then( result => { - * console.log(result); - * // true - * // result is true since every file exists - * }).catch( err => { - * console.log(err); - * }); - * - * async.every(withMissingFileList, fileExists) - * .then( result => { - * console.log(result); - * // false - * // result is false since NOT every file exists - * }).catch( err => { - * console.log(err); - * }); - * - * // Using async/await - * async () => { - * try { - * let result = await async.every(fileList, fileExists); - * console.log(result); - * // true - * // result is true since every file exists - * } - * catch (err) { - * console.log(err); - * } - * } - * - * async () => { - * try { - * let result = await async.every(withMissingFileList, fileExists); - * console.log(result); - * // false - * // result is false since NOT every file exists - * } - * catch (err) { - * console.log(err); - * } - * } - * - */ - function every(coll, iteratee, callback) { - return _createTester(bool => !bool, res => !res)(eachOf$1, coll, iteratee, callback) - } - var every$1 = awaitify(every, 3); + if (data.type === 'directory' && !this._moduleSupports('directory')) { + this.emit('error', new ArchiverError('DIRECTORYNOTSUPPORTED', { name: data.name })); + return this; + } - /** - * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. - * - * @name everyLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.every]{@link module:Collections.every} - * @alias allLimit - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in parallel. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - * @returns {Promise} a promise, if no callback provided - */ - function everyLimit(coll, limit, iteratee, callback) { - return _createTester(bool => !bool, res => !res)(eachOfLimit(limit), coll, iteratee, callback) - } - var everyLimit$1 = awaitify(everyLimit, 4); + source = util.normalizeInputSource(source); - /** - * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. - * - * @name everySeries - * @static - * @memberOf module:Collections - * @method - * @see [async.every]{@link module:Collections.every} - * @alias allSeries - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in series. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - * @returns {Promise} a promise, if no callback provided - */ - function everySeries(coll, iteratee, callback) { - return _createTester(bool => !bool, res => !res)(eachOfSeries$1, coll, iteratee, callback) - } - var everySeries$1 = awaitify(everySeries, 3); + if (Buffer.isBuffer(source)) { + data.sourceType = 'buffer'; + } else if (util.isStream(source)) { + data.sourceType = 'stream'; + } else { + this.emit('error', new ArchiverError('INPUTSTEAMBUFFERREQUIRED', { name: data.name })); + return this; + } - function filterArray(eachfn, arr, iteratee, callback) { - var truthValues = new Array(arr.length); - eachfn(arr, (x, index, iterCb) => { - iteratee(x, (err, v) => { - truthValues[index] = !!v; - iterCb(err); - }); - }, err => { - if (err) return callback(err); - var results = []; - for (var i = 0; i < arr.length; i++) { - if (truthValues[i]) results.push(arr[i]); - } - callback(null, results); - }); - } + this._entriesCount++; + this._queue.push({ + data: data, + source: source + }); - function filterGeneric(eachfn, coll, iteratee, callback) { - var results = []; - eachfn(coll, (x, index, iterCb) => { - iteratee(x, (err, v) => { - if (err) return iterCb(err); - if (v) { - results.push({index, value: x}); - } - iterCb(err); - }); - }, err => { - if (err) return callback(err); - callback(null, results - .sort((a, b) => a.index - b.index) - .map(v => v.value)); - }); - } + return this; +}; - function _filter(eachfn, coll, iteratee, callback) { - var filter = isArrayLike(coll) ? filterArray : filterGeneric; - return filter(eachfn, coll, wrapAsync(iteratee), callback); +/** + * Appends a directory and its files, recursively, given its dirpath. + * + * @param {String} dirpath The source directory path. + * @param {String} destpath The destination path within the archive. + * @param {(EntryData|Function)} data See also [ZipEntryData]{@link ZipEntryData} and + * [TarEntryData]{@link TarEntryData}. + * @return {this} + */ +Archiver.prototype.directory = function(dirpath, destpath, data) { + if (this._state.finalize || this._state.aborted) { + this.emit('error', new ArchiverError('QUEUECLOSED')); + return this; + } + + if (typeof dirpath !== 'string' || dirpath.length === 0) { + this.emit('error', new ArchiverError('DIRECTORYDIRPATHREQUIRED')); + return this; + } + + this._pending++; + + if (destpath === false) { + destpath = ''; + } else if (typeof destpath !== 'string'){ + destpath = dirpath; + } + + var dataFunction = false; + if (typeof data === 'function') { + dataFunction = data; + data = {}; + } else if (typeof data !== 'object') { + data = {}; + } + + var globOptions = { + stat: true, + dot: true + }; + + function onGlobEnd() { + this._pending--; + this._maybeFinalize(); + } + + function onGlobError(err) { + this.emit('error', err); + } + + function onGlobMatch(match){ + globber.pause(); + + var ignoreMatch = false; + var entryData = Object.assign({}, data); + entryData.name = match.relative; + entryData.prefix = destpath; + entryData.stats = match.stat; + entryData.callback = globber.resume.bind(globber); + + try { + if (dataFunction) { + entryData = dataFunction(entryData); + + if (entryData === false) { + ignoreMatch = true; + } else if (typeof entryData !== 'object') { + throw new ArchiverError('DIRECTORYFUNCTIONINVALIDDATA', { dirpath: dirpath }); + } + } + } catch(e) { + this.emit('error', e); + return; } - /** - * Returns a new array of all the values in `coll` which pass an async truth - * test. This operation is performed in parallel, but the results array will be - * in the same order as the original. - * - * @name filter - * @static - * @memberOf module:Collections - * @method - * @alias select - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @returns {Promise} a promise, if no callback provided - * @example - * - * // dir1 is a directory that contains file1.txt, file2.txt - * // dir2 is a directory that contains file3.txt, file4.txt - * // dir3 is a directory that contains file5.txt - * - * const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; - * - * // asynchronous function that checks if a file exists - * function fileExists(file, callback) { - * fs.access(file, fs.constants.F_OK, (err) => { - * callback(null, !err); - * }); - * } - * - * // Using callbacks - * async.filter(files, fileExists, function(err, results) { - * if(err) { - * console.log(err); - * } else { - * console.log(results); - * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] - * // results is now an array of the existing files - * } - * }); - * - * // Using Promises - * async.filter(files, fileExists) - * .then(results => { - * console.log(results); - * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] - * // results is now an array of the existing files - * }).catch(err => { - * console.log(err); - * }); - * - * // Using async/await - * async () => { - * try { - * let results = await async.filter(files, fileExists); - * console.log(results); - * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] - * // results is now an array of the existing files - * } - * catch (err) { - * console.log(err); - * } - * } - * - */ - function filter (coll, iteratee, callback) { - return _filter(eachOf$1, coll, iteratee, callback) + if (ignoreMatch) { + globber.resume(); + return; } - var filter$1 = awaitify(filter, 3); - /** - * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a - * time. - * - * @name filterLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @alias selectLimit - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @returns {Promise} a promise, if no callback provided - */ - function filterLimit (coll, limit, iteratee, callback) { - return _filter(eachOfLimit(limit), coll, iteratee, callback) - } - var filterLimit$1 = awaitify(filterLimit, 4); + this._append(match.absolute, entryData); + } - /** - * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. - * - * @name filterSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @alias selectSeries - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results) - * @returns {Promise} a promise, if no callback provided - */ - function filterSeries (coll, iteratee, callback) { - return _filter(eachOfSeries$1, coll, iteratee, callback) - } - var filterSeries$1 = awaitify(filterSeries, 3); + var globber = glob(dirpath, globOptions); + globber.on('error', onGlobError.bind(this)); + globber.on('match', onGlobMatch.bind(this)); + globber.on('end', onGlobEnd.bind(this)); - /** - * Calls the asynchronous function `fn` with a callback parameter that allows it - * to call itself again, in series, indefinitely. + return this; +}; - * If an error is passed to the callback then `errback` is called with the - * error, and execution stops, otherwise it will never be called. - * - * @name forever - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {AsyncFunction} fn - an async function to call repeatedly. - * Invoked with (next). - * @param {Function} [errback] - when `fn` passes an error to it's callback, - * this function will be called, and execution stops. Invoked with (err). - * @returns {Promise} a promise that rejects if an error occurs and an errback - * is not passed - * @example - * - * async.forever( - * function(next) { - * // next is suitable for passing to things that need a callback(err [, whatever]); - * // it will result in this function being called again. - * }, - * function(err) { - * // if next is called with a value in its first parameter, it will appear - * // in here as 'err', and execution will stop. - * } - * ); - */ - function forever(fn, errback) { - var done = onlyOnce(errback); - var task = wrapAsync(ensureAsync(fn)); +/** + * Appends a file given its filepath using a + * [lazystream]{@link https://github.com/jpommerening/node-lazystream} wrapper to + * prevent issues with open file limits. + * + * When the instance has received, processed, and emitted the file, the `entry` + * event is fired. + * + * @param {String} filepath The source filepath. + * @param {EntryData} data See also [ZipEntryData]{@link ZipEntryData} and + * [TarEntryData]{@link TarEntryData}. + * @return {this} + */ +Archiver.prototype.file = function(filepath, data) { + if (this._state.finalize || this._state.aborted) { + this.emit('error', new ArchiverError('QUEUECLOSED')); + return this; + } - function next(err) { - if (err) return done(err); - if (err === false) return; - task(next); - } - return next(); - } - var forever$1 = awaitify(forever, 2); + if (typeof filepath !== 'string' || filepath.length === 0) { + this.emit('error', new ArchiverError('FILEFILEPATHREQUIRED')); + return this; + } - /** - * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. - * - * @name groupByLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.groupBy]{@link module:Collections.groupBy} - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - * @returns {Promise} a promise, if no callback is passed - */ - function groupByLimit(coll, limit, iteratee, callback) { - var _iteratee = wrapAsync(iteratee); - return mapLimit$1(coll, limit, (val, iterCb) => { - _iteratee(val, (err, key) => { - if (err) return iterCb(err); - return iterCb(err, {key, val}); - }); - }, (err, mapResults) => { - var result = {}; - // from MDN, handle object having an `hasOwnProperty` prop - var {hasOwnProperty} = Object.prototype; + this._append(filepath, data); - for (var i = 0; i < mapResults.length; i++) { - if (mapResults[i]) { - var {key} = mapResults[i]; - var {val} = mapResults[i]; + return this; +}; - if (hasOwnProperty.call(result, key)) { - result[key].push(val); - } else { - result[key] = [val]; - } - } - } +/** + * Appends multiple files that match a glob pattern. + * + * @param {String} pattern The [glob pattern]{@link https://github.com/isaacs/minimatch} to match. + * @param {Object} options See [node-readdir-glob]{@link https://github.com/yqnn/node-readdir-glob#options}. + * @param {EntryData} data See also [ZipEntryData]{@link ZipEntryData} and + * [TarEntryData]{@link TarEntryData}. + * @return {this} + */ +Archiver.prototype.glob = function(pattern, options, data) { + this._pending++; - return callback(err, result); - }); - } + options = util.defaults(options, { + stat: true, + pattern: pattern + }); - var groupByLimit$1 = awaitify(groupByLimit, 4); + function onGlobEnd() { + this._pending--; + this._maybeFinalize(); + } - /** - * Returns a new object, where each value corresponds to an array of items, from - * `coll`, that returned the corresponding key. That is, the keys of the object - * correspond to the values passed to the `iteratee` callback. - * - * Note: Since this function applies the `iteratee` to each item in parallel, - * there is no guarantee that the `iteratee` functions will complete in order. - * However, the values for each key in the `result` will be in the same order as - * the original `coll`. For Objects, the values will roughly be in the order of - * the original Objects' keys (but this can vary across JavaScript engines). - * - * @name groupBy - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - * @returns {Promise} a promise, if no callback is passed - * @example - * - * // dir1 is a directory that contains file1.txt, file2.txt - * // dir2 is a directory that contains file3.txt, file4.txt - * // dir3 is a directory that contains file5.txt - * // dir4 does not exist - * - * const files = ['dir1/file1.txt','dir2','dir4'] - * - * // asynchronous function that detects file type as none, file, or directory - * function detectFile(file, callback) { - * fs.stat(file, function(err, stat) { - * if (err) { - * return callback(null, 'none'); - * } - * callback(null, stat.isDirectory() ? 'directory' : 'file'); - * }); - * } - * - * //Using callbacks - * async.groupBy(files, detectFile, function(err, result) { - * if(err) { - * console.log(err); - * } else { - * console.log(result); - * // { - * // file: [ 'dir1/file1.txt' ], - * // none: [ 'dir4' ], - * // directory: [ 'dir2'] - * // } - * // result is object containing the files grouped by type - * } - * }); - * - * // Using Promises - * async.groupBy(files, detectFile) - * .then( result => { - * console.log(result); - * // { - * // file: [ 'dir1/file1.txt' ], - * // none: [ 'dir4' ], - * // directory: [ 'dir2'] - * // } - * // result is object containing the files grouped by type - * }).catch( err => { - * console.log(err); - * }); - * - * // Using async/await - * async () => { - * try { - * let result = await async.groupBy(files, detectFile); - * console.log(result); - * // { - * // file: [ 'dir1/file1.txt' ], - * // none: [ 'dir4' ], - * // directory: [ 'dir2'] - * // } - * // result is object containing the files grouped by type - * } - * catch (err) { - * console.log(err); - * } - * } - * - */ - function groupBy (coll, iteratee, callback) { - return groupByLimit$1(coll, Infinity, iteratee, callback) - } + function onGlobError(err) { + this.emit('error', err); + } - /** - * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. - * - * @name groupBySeries - * @static - * @memberOf module:Collections - * @method - * @see [async.groupBy]{@link module:Collections.groupBy} - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whose - * properties are arrays of values which returned the corresponding key. - * @returns {Promise} a promise, if no callback is passed - */ - function groupBySeries (coll, iteratee, callback) { - return groupByLimit$1(coll, 1, iteratee, callback) - } + function onGlobMatch(match){ + globber.pause(); + var entryData = Object.assign({}, data); + entryData.callback = globber.resume.bind(globber); + entryData.stats = match.stat; + entryData.name = match.relative; - /** - * Logs the result of an `async` function to the `console`. Only works in - * Node.js or in browsers that support `console.log` and `console.error` (such - * as FF and Chrome). If multiple arguments are returned from the async - * function, `console.log` is called on each argument in order. - * - * @name log - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} function - The function you want to eventually apply - * all arguments to. - * @param {...*} arguments... - Any number of arguments to apply to the function. - * @example - * - * // in a module - * var hello = function(name, callback) { - * setTimeout(function() { - * callback(null, 'hello ' + name); - * }, 1000); - * }; - * - * // in the node repl - * node> async.log(hello, 'world'); - * 'hello world' - */ - var log = consoleFunc('log'); + this._append(match.absolute, entryData); + } - /** - * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a - * time. - * - * @name mapValuesLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.mapValues]{@link module:Collections.mapValues} - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - * @returns {Promise} a promise, if no callback is passed - */ - function mapValuesLimit(obj, limit, iteratee, callback) { - callback = once(callback); - var newObj = {}; - var _iteratee = wrapAsync(iteratee); - return eachOfLimit(limit)(obj, (val, key, next) => { - _iteratee(val, key, (err, result) => { - if (err) return next(err); - newObj[key] = result; - next(err); - }); - }, err => callback(err, newObj)); - } + var globber = glob(options.cwd || '.', options); + globber.on('error', onGlobError.bind(this)); + globber.on('match', onGlobMatch.bind(this)); + globber.on('end', onGlobEnd.bind(this)); - var mapValuesLimit$1 = awaitify(mapValuesLimit, 4); + return this; +}; - /** - * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. - * - * Produces a new Object by mapping each value of `obj` through the `iteratee` - * function. The `iteratee` is called each `value` and `key` from `obj` and a - * callback for when it has finished processing. Each of these callbacks takes - * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` - * passes an error to its callback, the main `callback` (for the `mapValues` - * function) is immediately called with the error. - * - * Note, the order of the keys in the result is not guaranteed. The keys will - * be roughly in the order they complete, (but this is very engine-specific) - * - * @name mapValues - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - * @returns {Promise} a promise, if no callback is passed - * @example - * - * // file1.txt is a file that is 1000 bytes in size - * // file2.txt is a file that is 2000 bytes in size - * // file3.txt is a file that is 3000 bytes in size - * // file4.txt does not exist - * - * const fileMap = { - * f1: 'file1.txt', - * f2: 'file2.txt', - * f3: 'file3.txt' - * }; - * - * const withMissingFileMap = { - * f1: 'file1.txt', - * f2: 'file2.txt', - * f3: 'file4.txt' - * }; - * - * // asynchronous function that returns the file size in bytes - * function getFileSizeInBytes(file, key, callback) { - * fs.stat(file, function(err, stat) { - * if (err) { - * return callback(err); - * } - * callback(null, stat.size); - * }); - * } - * - * // Using callbacks - * async.mapValues(fileMap, getFileSizeInBytes, function(err, result) { - * if (err) { - * console.log(err); - * } else { - * console.log(result); - * // result is now a map of file size in bytes for each file, e.g. - * // { - * // f1: 1000, - * // f2: 2000, - * // f3: 3000 - * // } - * } - * }); - * - * // Error handling - * async.mapValues(withMissingFileMap, getFileSizeInBytes, function(err, result) { - * if (err) { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * } else { - * console.log(result); - * } - * }); - * - * // Using Promises - * async.mapValues(fileMap, getFileSizeInBytes) - * .then( result => { - * console.log(result); - * // result is now a map of file size in bytes for each file, e.g. - * // { - * // f1: 1000, - * // f2: 2000, - * // f3: 3000 - * // } - * }).catch (err => { - * console.log(err); - * }); - * - * // Error Handling - * async.mapValues(withMissingFileMap, getFileSizeInBytes) - * .then( result => { - * console.log(result); - * }).catch (err => { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * }); - * - * // Using async/await - * async () => { - * try { - * let result = await async.mapValues(fileMap, getFileSizeInBytes); - * console.log(result); - * // result is now a map of file size in bytes for each file, e.g. - * // { - * // f1: 1000, - * // f2: 2000, - * // f3: 3000 - * // } - * } - * catch (err) { - * console.log(err); - * } - * } - * - * // Error Handling - * async () => { - * try { - * let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes); - * console.log(result); - * } - * catch (err) { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * } - * } - * - */ - function mapValues(obj, iteratee, callback) { - return mapValuesLimit$1(obj, Infinity, iteratee, callback) - } +/** + * Finalizes the instance and prevents further appending to the archive + * structure (queue will continue til drained). + * + * The `end`, `close` or `finish` events on the destination stream may fire + * right after calling this method so you should set listeners beforehand to + * properly detect stream completion. + * + * @return {Promise} + */ +Archiver.prototype.finalize = function() { + if (this._state.aborted) { + var abortedError = new ArchiverError('ABORTED'); + this.emit('error', abortedError); + return Promise.reject(abortedError); + } - /** - * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. - * - * @name mapValuesSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.mapValues]{@link module:Collections.mapValues} - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - * @returns {Promise} a promise, if no callback is passed - */ - function mapValuesSeries(obj, iteratee, callback) { - return mapValuesLimit$1(obj, 1, iteratee, callback) - } + if (this._state.finalize) { + var finalizingError = new ArchiverError('FINALIZING'); + this.emit('error', finalizingError); + return Promise.reject(finalizingError); + } - /** - * Caches the results of an async function. When creating a hash to store - * function results against, the callback is omitted from the hash and an - * optional hash function can be used. - * - * **Note: if the async function errs, the result will not be cached and - * subsequent calls will call the wrapped function.** - * - * If no hash function is specified, the first argument is used as a hash key, - * which may work reasonably if it is a string or a data type that converts to a - * distinct string. Note that objects and arrays will not behave reasonably. - * Neither will cases where the other arguments are significant. In such cases, - * specify your own hash function. - * - * The cache of results is exposed as the `memo` property of the function - * returned by `memoize`. - * - * @name memoize - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - The async function to proxy and cache results from. - * @param {Function} hasher - An optional function for generating a custom hash - * for storing results. It has all the arguments applied to it apart from the - * callback, and must be synchronous. - * @returns {AsyncFunction} a memoized version of `fn` - * @example - * - * var slow_fn = function(name, callback) { - * // do something - * callback(null, result); - * }; - * var fn = async.memoize(slow_fn); - * - * // fn can now be used as if it were slow_fn - * fn('some name', function() { - * // callback - * }); - */ - function memoize(fn, hasher = v => v) { - var memo = Object.create(null); - var queues = Object.create(null); - var _fn = wrapAsync(fn); - var memoized = initialParams((args, callback) => { - var key = hasher(...args); - if (key in memo) { - setImmediate$1(() => callback(null, ...memo[key])); - } else if (key in queues) { - queues[key].push(callback); - } else { - queues[key] = [callback]; - _fn(...args, (err, ...resultArgs) => { - // #1465 don't memoize if an error occurred - if (!err) { - memo[key] = resultArgs; - } - var q = queues[key]; - delete queues[key]; - for (var i = 0, l = q.length; i < l; i++) { - q[i](err, ...resultArgs); - } - }); - } - }); - memoized.memo = memo; - memoized.unmemoized = fn; - return memoized; - } + this._state.finalize = true; - /* istanbul ignore file */ + if (this._pending === 0 && this._queue.idle() && this._statQueue.idle()) { + this._finalize(); + } - /** - * Calls `callback` on a later loop around the event loop. In Node.js this just - * calls `process.nextTick`. In the browser it will use `setImmediate` if - * available, otherwise `setTimeout(callback, 0)`, which means other higher - * priority events may precede the execution of `callback`. - * - * This is used internally for browser-compatibility purposes. - * - * @name nextTick - * @static - * @memberOf module:Utils - * @method - * @see [async.setImmediate]{@link module:Utils.setImmediate} - * @category Util - * @param {Function} callback - The function to call on a later loop around - * the event loop. Invoked with (args...). - * @param {...*} args... - any number of additional arguments to pass to the - * callback on the next tick. - * @example - * - * var call_order = []; - * async.nextTick(function() { - * call_order.push('two'); - * // call_order now equals ['one','two'] - * }); - * call_order.push('one'); - * - * async.setImmediate(function (a, b, c) { - * // a, b, and c equal 1, 2, and 3 - * }, 1, 2, 3); - */ - var _defer$1; + var self = this; - if (hasNextTick) { - _defer$1 = process.nextTick; - } else if (hasSetImmediate) { - _defer$1 = setImmediate; - } else { - _defer$1 = fallback; - } + return new Promise(function(resolve, reject) { + var errored; - var nextTick = wrap(_defer$1); + self._module.on('end', function() { + if (!errored) { + resolve(); + } + }) - var parallel = awaitify((eachfn, tasks, callback) => { - var results = isArrayLike(tasks) ? [] : {}; + self._module.on('error', function(err) { + errored = true; + reject(err); + }) + }) +}; - eachfn(tasks, (task, key, taskCb) => { - wrapAsync(task)((err, ...result) => { - if (result.length < 2) { - [result] = result; - } - results[key] = result; - taskCb(err); - }); - }, err => callback(err, results)); - }, 3); +/** + * Sets the module format name used for archiving. + * + * @param {String} format The name of the format. + * @return {this} + */ +Archiver.prototype.setFormat = function(format) { + if (this._format) { + this.emit('error', new ArchiverError('FORMATSET')); + return this; + } - /** - * Run the `tasks` collection of functions in parallel, without waiting until - * the previous function has completed. If any of the functions pass an error to - * its callback, the main `callback` is immediately called with the value of the - * error. Once the `tasks` have completed, the results are passed to the final - * `callback` as an array. - * - * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about - * parallel execution of code. If your tasks do not use any timers or perform - * any I/O, they will actually be executed in series. Any synchronous setup - * sections for each task will happen one after the other. JavaScript remains - * single-threaded. - * - * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the - * execution of other tasks when a task fails. - * - * It is also possible to use an object instead of an array. Each property will - * be run as a function and the results will be passed to the final `callback` - * as an object instead of an array. This can be a more readable way of handling - * results from {@link async.parallel}. - * - * @name parallel - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of - * [async functions]{@link AsyncFunction} to run. - * Each async function can complete with any number of optional `result` values. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed successfully. This function gets a results array - * (or object) containing all the result arguments passed to the task callbacks. - * Invoked with (err, results). - * @returns {Promise} a promise, if a callback is not passed - * - * @example - * - * //Using Callbacks - * async.parallel([ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ], function(err, results) { - * console.log(results); - * // results is equal to ['one','two'] even though - * // the second function had a shorter timeout. - * }); - * - * // an example using an object instead of an array - * async.parallel({ - * one: function(callback) { - * setTimeout(function() { - * callback(null, 1); - * }, 200); - * }, - * two: function(callback) { - * setTimeout(function() { - * callback(null, 2); - * }, 100); - * } - * }, function(err, results) { - * console.log(results); - * // results is equal to: { one: 1, two: 2 } - * }); - * - * //Using Promises - * async.parallel([ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ]).then(results => { - * console.log(results); - * // results is equal to ['one','two'] even though - * // the second function had a shorter timeout. - * }).catch(err => { - * console.log(err); - * }); - * - * // an example using an object instead of an array - * async.parallel({ - * one: function(callback) { - * setTimeout(function() { - * callback(null, 1); - * }, 200); - * }, - * two: function(callback) { - * setTimeout(function() { - * callback(null, 2); - * }, 100); - * } - * }).then(results => { - * console.log(results); - * // results is equal to: { one: 1, two: 2 } - * }).catch(err => { - * console.log(err); - * }); - * - * //Using async/await - * async () => { - * try { - * let results = await async.parallel([ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ]); - * console.log(results); - * // results is equal to ['one','two'] even though - * // the second function had a shorter timeout. - * } - * catch (err) { - * console.log(err); - * } - * } - * - * // an example using an object instead of an array - * async () => { - * try { - * let results = await async.parallel({ - * one: function(callback) { - * setTimeout(function() { - * callback(null, 1); - * }, 200); - * }, - * two: function(callback) { - * setTimeout(function() { - * callback(null, 2); - * }, 100); - * } - * }); - * console.log(results); - * // results is equal to: { one: 1, two: 2 } - * } - * catch (err) { - * console.log(err); - * } - * } - * - */ - function parallel$1(tasks, callback) { - return parallel(eachOf$1, tasks, callback); - } + this._format = format; - /** - * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a - * time. - * - * @name parallelLimit - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.parallel]{@link module:ControlFlow.parallel} - * @category Control Flow - * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of - * [async functions]{@link AsyncFunction} to run. - * Each async function can complete with any number of optional `result` values. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed successfully. This function gets a results array - * (or object) containing all the result arguments passed to the task callbacks. - * Invoked with (err, results). - * @returns {Promise} a promise, if a callback is not passed - */ - function parallelLimit(tasks, limit, callback) { - return parallel(eachOfLimit(limit), tasks, callback); - } + return this; +}; - /** - * A queue of tasks for the worker function to complete. - * @typedef {Iterable} QueueObject - * @memberOf module:ControlFlow - * @property {Function} length - a function returning the number of items - * waiting to be processed. Invoke with `queue.length()`. - * @property {boolean} started - a boolean indicating whether or not any - * items have been pushed and processed by the queue. - * @property {Function} running - a function returning the number of items - * currently being processed. Invoke with `queue.running()`. - * @property {Function} workersList - a function returning the array of items - * currently being processed. Invoke with `queue.workersList()`. - * @property {Function} idle - a function returning false if there are items - * waiting or being processed, or true if not. Invoke with `queue.idle()`. - * @property {number} concurrency - an integer for determining how many `worker` - * functions should be run in parallel. This property can be changed after a - * `queue` is created to alter the concurrency on-the-fly. - * @property {number} payload - an integer that specifies how many items are - * passed to the worker function at a time. only applies if this is a - * [cargo]{@link module:ControlFlow.cargo} object - * @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback` - * once the `worker` has finished processing the task. Instead of a single task, - * a `tasks` array can be submitted. The respective callback is used for every - * task in the list. Invoke with `queue.push(task, [callback])`, - * @property {AsyncFunction} unshift - add a new task to the front of the `queue`. - * Invoke with `queue.unshift(task, [callback])`. - * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns - * a promise that rejects if an error occurs. - * @property {AsyncFunction} unshiftAsync - the same as `q.unshift`, except this returns - * a promise that rejects if an error occurs. - * @property {Function} remove - remove items from the queue that match a test - * function. The test function will be passed an object with a `data` property, - * and a `priority` property, if this is a - * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. - * Invoked with `queue.remove(testFn)`, where `testFn` is of the form - * `function ({data, priority}) {}` and returns a Boolean. - * @property {Function} saturated - a function that sets a callback that is - * called when the number of running workers hits the `concurrency` limit, and - * further tasks will be queued. If the callback is omitted, `q.saturated()` - * returns a promise for the next occurrence. - * @property {Function} unsaturated - a function that sets a callback that is - * called when the number of running workers is less than the `concurrency` & - * `buffer` limits, and further tasks will not be queued. If the callback is - * omitted, `q.unsaturated()` returns a promise for the next occurrence. - * @property {number} buffer - A minimum threshold buffer in order to say that - * the `queue` is `unsaturated`. - * @property {Function} empty - a function that sets a callback that is called - * when the last item from the `queue` is given to a `worker`. If the callback - * is omitted, `q.empty()` returns a promise for the next occurrence. - * @property {Function} drain - a function that sets a callback that is called - * when the last item from the `queue` has returned from the `worker`. If the - * callback is omitted, `q.drain()` returns a promise for the next occurrence. - * @property {Function} error - a function that sets a callback that is called - * when a task errors. Has the signature `function(error, task)`. If the - * callback is omitted, `error()` returns a promise that rejects on the next - * error. - * @property {boolean} paused - a boolean for determining whether the queue is - * in a paused state. - * @property {Function} pause - a function that pauses the processing of tasks - * until `resume()` is called. Invoke with `queue.pause()`. - * @property {Function} resume - a function that resumes the processing of - * queued tasks when the queue is paused. Invoke with `queue.resume()`. - * @property {Function} kill - a function that removes the `drain` callback and - * empties remaining tasks from the queue forcing it to go idle. No more tasks - * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. - * - * @example - * const q = async.queue(worker, 2) - * q.push(item1) - * q.push(item2) - * q.push(item3) - * // queues are iterable, spread into an array to inspect - * const items = [...q] // [item1, item2, item3] - * // or use for of - * for (let item of q) { - * console.log(item) - * } - * - * q.drain(() => { - * console.log('all done') - * }) - * // or - * await q.drain() - */ +/** + * Sets the module used for archiving. + * + * @param {Function} module The function for archiver to interact with. + * @return {this} + */ +Archiver.prototype.setModule = function(module) { + if (this._state.aborted) { + this.emit('error', new ArchiverError('ABORTED')); + return this; + } - /** - * Creates a `queue` object with the specified `concurrency`. Tasks added to the - * `queue` are processed in parallel (up to the `concurrency` limit). If all - * `worker`s are in progress, the task is queued until one becomes available. - * Once a `worker` completes a `task`, that `task`'s callback is called. - * - * @name queue - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {AsyncFunction} worker - An async function for processing a queued task. - * If you want to handle errors from an individual task, pass a callback to - * `q.push()`. Invoked with (task, callback). - * @param {number} [concurrency=1] - An `integer` for determining how many - * `worker` functions should be run in parallel. If omitted, the concurrency - * defaults to `1`. If the concurrency is `0`, an error is thrown. - * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be - * attached as certain properties to listen for specific events during the - * lifecycle of the queue. - * @example - * - * // create a queue object with concurrency 2 - * var q = async.queue(function(task, callback) { - * console.log('hello ' + task.name); - * callback(); - * }, 2); - * - * // assign a callback - * q.drain(function() { - * console.log('all items have been processed'); - * }); - * // or await the end - * await q.drain() - * - * // assign an error callback - * q.error(function(err, task) { - * console.error('task experienced an error'); - * }); - * - * // add some items to the queue - * q.push({name: 'foo'}, function(err) { - * console.log('finished processing foo'); - * }); - * // callback is optional - * q.push({name: 'bar'}); - * - * // add some items to the queue (batch-wise) - * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { - * console.log('finished processing item'); - * }); - * - * // add some items to the front of the queue - * q.unshift({name: 'bar'}, function (err) { - * console.log('finished processing bar'); - * }); - */ - function queue$1 (worker, concurrency) { - var _worker = wrapAsync(worker); - return queue((items, cb) => { - _worker(items[0], cb); - }, concurrency, 1); - } + if (this._state.module) { + this.emit('error', new ArchiverError('MODULESET')); + return this; + } - // Binary min-heap implementation used for priority queue. - // Implementation is stable, i.e. push time is considered for equal priorities - class Heap { - constructor() { - this.heap = []; - this.pushCount = Number.MIN_SAFE_INTEGER; - } + this._module = module; + this._modulePipe(); - get length() { - return this.heap.length; - } + return this; +}; - empty () { - this.heap = []; - return this; - } +/** + * Appends a symlink to the instance. + * + * This does NOT interact with filesystem and is used for programmatically creating symlinks. + * + * @param {String} filepath The symlink path (within archive). + * @param {String} target The target path (within archive). + * @param {Number} mode Sets the entry permissions. + * @return {this} + */ +Archiver.prototype.symlink = function(filepath, target, mode) { + if (this._state.finalize || this._state.aborted) { + this.emit('error', new ArchiverError('QUEUECLOSED')); + return this; + } - percUp(index) { - let p; + if (typeof filepath !== 'string' || filepath.length === 0) { + this.emit('error', new ArchiverError('SYMLINKFILEPATHREQUIRED')); + return this; + } - while (index > 0 && smaller(this.heap[index], this.heap[p=parent(index)])) { - let t = this.heap[index]; - this.heap[index] = this.heap[p]; - this.heap[p] = t; + if (typeof target !== 'string' || target.length === 0) { + this.emit('error', new ArchiverError('SYMLINKTARGETREQUIRED', { filepath: filepath })); + return this; + } - index = p; - } - } + if (!this._moduleSupports('symlink')) { + this.emit('error', new ArchiverError('SYMLINKNOTSUPPORTED', { filepath: filepath })); + return this; + } - percDown(index) { - let l; + var data = {}; + data.type = 'symlink'; + data.name = filepath.replace(/\\/g, '/'); + data.linkname = target.replace(/\\/g, '/'); + data.sourceType = 'buffer'; - while ((l=leftChi(index)) < this.heap.length) { - if (l+1 < this.heap.length && smaller(this.heap[l+1], this.heap[l])) { - l = l+1; - } + if (typeof mode === "number") { + data.mode = mode; + } - if (smaller(this.heap[index], this.heap[l])) { - break; - } + this._entriesCount++; + this._queue.push({ + data: data, + source: Buffer.concat([]) + }); - let t = this.heap[index]; - this.heap[index] = this.heap[l]; - this.heap[l] = t; + return this; +}; - index = l; - } - } +/** + * Returns the current length (in bytes) that has been emitted. + * + * @return {Number} + */ +Archiver.prototype.pointer = function() { + return this._pointer; +}; - push(node) { - node.pushCount = ++this.pushCount; - this.heap.push(node); - this.percUp(this.heap.length-1); - } +/** + * Middleware-like helper that has yet to be fully implemented. + * + * @private + * @param {Function} plugin + * @return {this} + */ +Archiver.prototype.use = function(plugin) { + this._streams.push(plugin); + return this; +}; - unshift(node) { - return this.heap.push(node); - } +module.exports = Archiver; - shift() { - let [top] = this.heap; +/** + * @typedef {Object} CoreOptions + * @global + * @property {Number} [statConcurrency=4] Sets the number of workers used to + * process the internal fs stat queue. + */ - this.heap[0] = this.heap[this.heap.length-1]; - this.heap.pop(); - this.percDown(0); +/** + * @typedef {Object} TransformOptions + * @property {Boolean} [allowHalfOpen=true] If set to false, then the stream + * will automatically end the readable side when the writable side ends and vice + * versa. + * @property {Boolean} [readableObjectMode=false] Sets objectMode for readable + * side of the stream. Has no effect if objectMode is true. + * @property {Boolean} [writableObjectMode=false] Sets objectMode for writable + * side of the stream. Has no effect if objectMode is true. + * @property {Boolean} [decodeStrings=true] Whether or not to decode strings + * into Buffers before passing them to _write(). `Writable` + * @property {String} [encoding=NULL] If specified, then buffers will be decoded + * to strings using the specified encoding. `Readable` + * @property {Number} [highWaterMark=16kb] The maximum number of bytes to store + * in the internal buffer before ceasing to read from the underlying resource. + * `Readable` `Writable` + * @property {Boolean} [objectMode=false] Whether this stream should behave as a + * stream of objects. Meaning that stream.read(n) returns a single value instead + * of a Buffer of size n. `Readable` `Writable` + */ - return top; - } +/** + * @typedef {Object} EntryData + * @property {String} name Sets the entry name including internal path. + * @property {(String|Date)} [date=NOW()] Sets the entry date. + * @property {Number} [mode=D:0755/F:0644] Sets the entry permissions. + * @property {String} [prefix] Sets a path prefix for the entry name. Useful + * when working with methods like `directory` or `glob`. + * @property {fs.Stats} [stats] Sets the fs stat data for this entry allowing + * for reduction of fs stat calls when stat data is already known. + */ - toArray() { - return [...this]; - } +/** + * @typedef {Object} ErrorData + * @property {String} message The message of the error. + * @property {String} code The error code assigned to this error. + * @property {String} data Additional data provided for reporting or debugging (where available). + */ - *[Symbol.iterator] () { - for (let i = 0; i < this.heap.length; i++) { - yield this.heap[i].data; - } - } +/** + * @typedef {Object} ProgressData + * @property {Object} entries + * @property {Number} entries.total Number of entries that have been appended. + * @property {Number} entries.processed Number of entries that have been processed. + * @property {Object} fs + * @property {Number} fs.totalBytes Number of bytes that have been appended. Calculated asynchronously and might not be accurate: it growth while entries are added. (based on fs.Stats) + * @property {Number} fs.processedBytes Number of bytes that have been processed. (based on fs.Stats) + */ - remove (testFn) { - let j = 0; - for (let i = 0; i < this.heap.length; i++) { - if (!testFn(this.heap[i])) { - this.heap[j] = this.heap[i]; - j++; - } - } - this.heap.splice(j); +/***/ }), - for (let i = parent(this.heap.length-1); i >= 0; i--) { - this.percDown(i); - } +/***/ 13143: +/***/ ((module, exports, __nccwpck_require__) => { - return this; - } - } +/** + * Archiver Core + * + * @ignore + * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} + * @copyright (c) 2012-2014 Chris Talkington, contributors. + */ - function leftChi(i) { - return (i<<1)+1; - } +var util = __nccwpck_require__(73837); - function parent(i) { - return ((i+1)>>1)-1; - } +const ERROR_CODES = { + 'ABORTED': 'archive was aborted', + 'DIRECTORYDIRPATHREQUIRED': 'diretory dirpath argument must be a non-empty string value', + 'DIRECTORYFUNCTIONINVALIDDATA': 'invalid data returned by directory custom data function', + 'ENTRYNAMEREQUIRED': 'entry name must be a non-empty string value', + 'FILEFILEPATHREQUIRED': 'file filepath argument must be a non-empty string value', + 'FINALIZING': 'archive already finalizing', + 'QUEUECLOSED': 'queue closed', + 'NOENDMETHOD': 'no suitable finalize/end method defined by module', + 'DIRECTORYNOTSUPPORTED': 'support for directory entries not defined by module', + 'FORMATSET': 'archive format already set', + 'INPUTSTEAMBUFFERREQUIRED': 'input source must be valid Stream or Buffer instance', + 'MODULESET': 'module already set', + 'SYMLINKNOTSUPPORTED': 'support for symlink entries not defined by module', + 'SYMLINKFILEPATHREQUIRED': 'symlink filepath argument must be a non-empty string value', + 'SYMLINKTARGETREQUIRED': 'symlink target argument must be a non-empty string value', + 'ENTRYNOTSUPPORTED': 'entry not supported' +}; - function smaller(x, y) { - if (x.priority !== y.priority) { - return x.priority < y.priority; - } - else { - return x.pushCount < y.pushCount; - } - } +function ArchiverError(code, data) { + Error.captureStackTrace(this, this.constructor); + //this.name = this.constructor.name; + this.message = ERROR_CODES[code] || code; + this.code = code; + this.data = data; +} - /** - * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and - * completed in ascending priority order. - * - * @name priorityQueue - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.queue]{@link module:ControlFlow.queue} - * @category Control Flow - * @param {AsyncFunction} worker - An async function for processing a queued task. - * If you want to handle errors from an individual task, pass a callback to - * `q.push()`. - * Invoked with (task, callback). - * @param {number} concurrency - An `integer` for determining how many `worker` - * functions should be run in parallel. If omitted, the concurrency defaults to - * `1`. If the concurrency is `0`, an error is thrown. - * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are three - * differences between `queue` and `priorityQueue` objects: - * * `push(task, priority, [callback])` - `priority` should be a number. If an - * array of `tasks` is given, all tasks will be assigned the same priority. - * * `pushAsync(task, priority, [callback])` - the same as `priorityQueue.push`, - * except this returns a promise that rejects if an error occurs. - * * The `unshift` and `unshiftAsync` methods were removed. - */ - function priorityQueue(worker, concurrency) { - // Start with a normal queue - var q = queue$1(worker, concurrency); +util.inherits(ArchiverError, Error); - var { - push, - pushAsync - } = q; +exports = module.exports = ArchiverError; - q._tasks = new Heap(); - q._createTaskItem = ({data, priority}, callback) => { - return { - data, - priority, - callback - }; - }; +/***/ }), - function createDataItems(tasks, priority) { - if (!Array.isArray(tasks)) { - return {data: tasks, priority}; - } - return tasks.map(data => { return {data, priority}; }); - } +/***/ 99827: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Override push to accept second parameter representing priority - q.push = function(data, priority = 0, callback) { - return push(createDataItems(data, priority), callback); - }; +/** + * JSON Format Plugin + * + * @module plugins/json + * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} + * @copyright (c) 2012-2014 Chris Talkington, contributors. + */ +var inherits = (__nccwpck_require__(73837).inherits); +var Transform = (__nccwpck_require__(51642).Transform); - q.pushAsync = function(data, priority = 0, callback) { - return pushAsync(createDataItems(data, priority), callback); - }; +var crc32 = __nccwpck_require__(84794); +var util = __nccwpck_require__(82072); - // Remove unshift functions - delete q.unshift; - delete q.unshiftAsync; +/** + * @constructor + * @param {(JsonOptions|TransformOptions)} options + */ +var Json = function(options) { + if (!(this instanceof Json)) { + return new Json(options); + } - return q; - } + options = this.options = util.defaults(options, {}); - /** - * Runs the `tasks` array of functions in parallel, without waiting until the - * previous function has completed. Once any of the `tasks` complete or pass an - * error to its callback, the main `callback` is immediately called. It's - * equivalent to `Promise.race()`. - * - * @name race - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} - * to run. Each function can complete with an optional `result` value. - * @param {Function} callback - A callback to run once any of the functions have - * completed. This function gets an error or result from the first function that - * completed. Invoked with (err, result). - * @returns {Promise} a promise, if a callback is omitted - * @example - * - * async.race([ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ], - * // main callback - * function(err, result) { - * // the result will be equal to 'two' as it finishes earlier - * }); - */ - function race(tasks, callback) { - callback = once(callback); - if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); - if (!tasks.length) return callback(); - for (var i = 0, l = tasks.length; i < l; i++) { - wrapAsync(tasks[i])(callback); - } - } + Transform.call(this, options); - var race$1 = awaitify(race, 2); + this.supports = { + directory: true, + symlink: true + }; - /** - * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. - * - * @name reduceRight - * @static - * @memberOf module:Collections - * @method - * @see [async.reduce]{@link module:Collections.reduce} - * @alias foldr - * @category Collection - * @param {Array} array - A collection to iterate over. - * @param {*} memo - The initial state of the reduction. - * @param {AsyncFunction} iteratee - A function applied to each item in the - * array to produce the next step in the reduction. - * The `iteratee` should complete with the next state of the reduction. - * If the iteratee completes with an error, the reduction is stopped and the - * main `callback` is immediately called with the error. - * Invoked with (memo, item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the reduced value. Invoked with - * (err, result). - * @returns {Promise} a promise, if no callback is passed - */ - function reduceRight (array, memo, iteratee, callback) { - var reversed = [...array].reverse(); - return reduce$1(reversed, memo, iteratee, callback); - } + this.files = []; +}; - /** - * Wraps the async function in another function that always completes with a - * result object, even when it errors. - * - * The result object has either the property `error` or `value`. - * - * @name reflect - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - The async function you want to wrap - * @returns {Function} - A function that always passes null to it's callback as - * the error. The second argument to the callback will be an `object` with - * either an `error` or a `value` property. - * @example - * - * async.parallel([ - * async.reflect(function(callback) { - * // do some stuff ... - * callback(null, 'one'); - * }), - * async.reflect(function(callback) { - * // do some more stuff but error ... - * callback('bad stuff happened'); - * }), - * async.reflect(function(callback) { - * // do some more stuff ... - * callback(null, 'two'); - * }) - * ], - * // optional callback - * function(err, results) { - * // values - * // results[0].value = 'one' - * // results[1].error = 'bad stuff happened' - * // results[2].value = 'two' - * }); - */ - function reflect(fn) { - var _fn = wrapAsync(fn); - return initialParams(function reflectOn(args, reflectCallback) { - args.push((error, ...cbArgs) => { - let retVal = {}; - if (error) { - retVal.error = error; - } - if (cbArgs.length > 0){ - var value = cbArgs; - if (cbArgs.length <= 1) { - [value] = cbArgs; - } - retVal.value = value; - } - reflectCallback(null, retVal); - }); +inherits(Json, Transform); - return _fn.apply(this, args); - }); - } +/** + * [_transform description] + * + * @private + * @param {Buffer} chunk + * @param {String} encoding + * @param {Function} callback + * @return void + */ +Json.prototype._transform = function(chunk, encoding, callback) { + callback(null, chunk); +}; - /** - * A helper function that wraps an array or an object of functions with `reflect`. - * - * @name reflectAll - * @static - * @memberOf module:Utils - * @method - * @see [async.reflect]{@link module:Utils.reflect} - * @category Util - * @param {Array|Object|Iterable} tasks - The collection of - * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. - * @returns {Array} Returns an array of async functions, each wrapped in - * `async.reflect` - * @example - * - * let tasks = [ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * // do some more stuff but error ... - * callback(new Error('bad stuff happened')); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ]; - * - * async.parallel(async.reflectAll(tasks), - * // optional callback - * function(err, results) { - * // values - * // results[0].value = 'one' - * // results[1].error = Error('bad stuff happened') - * // results[2].value = 'two' - * }); - * - * // an example using an object instead of an array - * let tasks = { - * one: function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * two: function(callback) { - * callback('two'); - * }, - * three: function(callback) { - * setTimeout(function() { - * callback(null, 'three'); - * }, 100); - * } - * }; - * - * async.parallel(async.reflectAll(tasks), - * // optional callback - * function(err, results) { - * // values - * // results.one.value = 'one' - * // results.two.error = 'two' - * // results.three.value = 'three' - * }); - */ - function reflectAll(tasks) { - var results; - if (Array.isArray(tasks)) { - results = tasks.map(reflect); - } else { - results = {}; - Object.keys(tasks).forEach(key => { - results[key] = reflect.call(this, tasks[key]); - }); - } - return results; - } +/** + * [_writeStringified description] + * + * @private + * @return void + */ +Json.prototype._writeStringified = function() { + var fileString = JSON.stringify(this.files); + this.write(fileString); +}; - function reject(eachfn, arr, _iteratee, callback) { - const iteratee = wrapAsync(_iteratee); - return _filter(eachfn, arr, (value, cb) => { - iteratee(value, (err, v) => { - cb(err, !v); - }); - }, callback); - } +/** + * [append description] + * + * @param {(Buffer|Stream)} source + * @param {EntryData} data + * @param {Function} callback + * @return void + */ +Json.prototype.append = function(source, data, callback) { + var self = this; - /** - * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. - * - * @name reject - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @returns {Promise} a promise, if no callback is passed - * @example - * - * // dir1 is a directory that contains file1.txt, file2.txt - * // dir2 is a directory that contains file3.txt, file4.txt - * // dir3 is a directory that contains file5.txt - * - * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; - * - * // asynchronous function that checks if a file exists - * function fileExists(file, callback) { - * fs.access(file, fs.constants.F_OK, (err) => { - * callback(null, !err); - * }); - * } - * - * // Using callbacks - * async.reject(fileList, fileExists, function(err, results) { - * // [ 'dir3/file6.txt' ] - * // results now equals an array of the non-existing files - * }); - * - * // Using Promises - * async.reject(fileList, fileExists) - * .then( results => { - * console.log(results); - * // [ 'dir3/file6.txt' ] - * // results now equals an array of the non-existing files - * }).catch( err => { - * console.log(err); - * }); - * - * // Using async/await - * async () => { - * try { - * let results = await async.reject(fileList, fileExists); - * console.log(results); - * // [ 'dir3/file6.txt' ] - * // results now equals an array of the non-existing files - * } - * catch (err) { - * console.log(err); - * } - * } - * - */ - function reject$1 (coll, iteratee, callback) { - return reject(eachOf$1, coll, iteratee, callback) - } - var reject$2 = awaitify(reject$1, 3); + data.crc32 = 0; - /** - * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a - * time. - * - * @name rejectLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.reject]{@link module:Collections.reject} - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @returns {Promise} a promise, if no callback is passed - */ - function rejectLimit (coll, limit, iteratee, callback) { - return reject(eachOfLimit(limit), coll, iteratee, callback) + function onend(err, sourceBuffer) { + if (err) { + callback(err); + return; } - var rejectLimit$1 = awaitify(rejectLimit, 4); - /** - * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. - * - * @name rejectSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.reject]{@link module:Collections.reject} - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @returns {Promise} a promise, if no callback is passed - */ - function rejectSeries (coll, iteratee, callback) { - return reject(eachOfSeries$1, coll, iteratee, callback) - } - var rejectSeries$1 = awaitify(rejectSeries, 3); + data.size = sourceBuffer.length || 0; + data.crc32 = crc32.unsigned(sourceBuffer); - function constant$1(value) { - return function () { - return value; - } - } + self.files.push(data); - /** - * Attempts to get a successful response from `task` no more than `times` times - * before returning an error. If the task is successful, the `callback` will be - * passed the result of the successful task. If all attempts fail, the callback - * will be passed the error and result (if any) of the final attempt. - * - * @name retry - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @see [async.retryable]{@link module:ControlFlow.retryable} - * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an - * object with `times` and `interval` or a number. - * * `times` - The number of attempts to make before giving up. The default - * is `5`. - * * `interval` - The time to wait between retries, in milliseconds. The - * default is `0`. The interval may also be specified as a function of the - * retry count (see example). - * * `errorFilter` - An optional synchronous function that is invoked on - * erroneous result. If it returns `true` the retry attempts will continue; - * if the function returns `false` the retry flow is aborted with the current - * attempt's error and result being returned to the final callback. - * Invoked with (err). - * * If `opts` is a number, the number specifies the number of times to retry, - * with the default interval of `0`. - * @param {AsyncFunction} task - An async function to retry. - * Invoked with (callback). - * @param {Function} [callback] - An optional callback which is called when the - * task has succeeded, or after the final failed attempt. It receives the `err` - * and `result` arguments of the last attempt at completing the `task`. Invoked - * with (err, results). - * @returns {Promise} a promise if no callback provided - * - * @example - * - * // The `retry` function can be used as a stand-alone control flow by passing - * // a callback, as shown below: - * - * // try calling apiMethod 3 times - * async.retry(3, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod 3 times, waiting 200 ms between each retry - * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod 10 times with exponential backoff - * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) - * async.retry({ - * times: 10, - * interval: function(retryCount) { - * return 50 * Math.pow(2, retryCount); - * } - * }, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod the default 5 times no delay between each retry - * async.retry(apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod only when error condition satisfies, all other - * // errors will abort the retry control flow and return to final callback - * async.retry({ - * errorFilter: function(err) { - * return err.message === 'Temporary error'; // only retry on a specific error - * } - * }, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // to retry individual methods that are not as reliable within other - * // control flow functions, use the `retryable` wrapper: - * async.auto({ - * users: api.getUsers.bind(api), - * payments: async.retryable(3, api.getPayments.bind(api)) - * }, function(err, results) { - * // do something with the results - * }); - * - */ - const DEFAULT_TIMES = 5; - const DEFAULT_INTERVAL = 0; + callback(null, data); + } - function retry(opts, task, callback) { - var options = { - times: DEFAULT_TIMES, - intervalFunc: constant$1(DEFAULT_INTERVAL) - }; + if (data.sourceType === 'buffer') { + onend(null, source); + } else if (data.sourceType === 'stream') { + util.collectStream(source, onend); + } +}; - if (arguments.length < 3 && typeof opts === 'function') { - callback = task || promiseCallback(); - task = opts; - } else { - parseTimes(options, opts); - callback = callback || promiseCallback(); - } +/** + * [finalize description] + * + * @return void + */ +Json.prototype.finalize = function() { + this._writeStringified(); + this.end(); +}; - if (typeof task !== 'function') { - throw new Error("Invalid arguments for async.retry"); - } +module.exports = Json; - var _task = wrapAsync(task); +/** + * @typedef {Object} JsonOptions + * @global + */ - var attempt = 1; - function retryAttempt() { - _task((err, ...args) => { - if (err === false) return - if (err && attempt++ < options.times && - (typeof options.errorFilter != 'function' || - options.errorFilter(err))) { - setTimeout(retryAttempt, options.intervalFunc(attempt - 1)); - } else { - callback(err, ...args); - } - }); - } - retryAttempt(); - return callback[PROMISE_SYMBOL] - } +/***/ }), - function parseTimes(acc, t) { - if (typeof t === 'object') { - acc.times = +t.times || DEFAULT_TIMES; +/***/ 33614: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - acc.intervalFunc = typeof t.interval === 'function' ? - t.interval : - constant$1(+t.interval || DEFAULT_INTERVAL); +/** + * TAR Format Plugin + * + * @module plugins/tar + * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} + * @copyright (c) 2012-2014 Chris Talkington, contributors. + */ +var zlib = __nccwpck_require__(59796); - acc.errorFilter = t.errorFilter; - } else if (typeof t === 'number' || typeof t === 'string') { - acc.times = +t || DEFAULT_TIMES; - } else { - throw new Error("Invalid arguments for async.retry"); - } - } +var engine = __nccwpck_require__(2283); +var util = __nccwpck_require__(82072); - /** - * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method - * wraps a task and makes it retryable, rather than immediately calling it - * with retries. - * - * @name retryable - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.retry]{@link module:ControlFlow.retry} - * @category Control Flow - * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional - * options, exactly the same as from `retry`, except for a `opts.arity` that - * is the arity of the `task` function, defaulting to `task.length` - * @param {AsyncFunction} task - the asynchronous function to wrap. - * This function will be passed any arguments passed to the returned wrapper. - * Invoked with (...args, callback). - * @returns {AsyncFunction} The wrapped function, which when invoked, will - * retry on an error, based on the parameters specified in `opts`. - * This function will accept the same parameters as `task`. - * @example - * - * async.auto({ - * dep1: async.retryable(3, getFromFlakyService), - * process: ["dep1", async.retryable(3, function (results, cb) { - * maybeProcessData(results.dep1, cb); - * })] - * }, callback); - */ - function retryable (opts, task) { - if (!task) { - task = opts; - opts = null; - } - let arity = (opts && opts.arity) || task.length; - if (isAsync(task)) { - arity += 1; - } - var _task = wrapAsync(task); - return initialParams((args, callback) => { - if (args.length < arity - 1 || callback == null) { - args.push(callback); - callback = promiseCallback(); - } - function taskFn(cb) { - _task(...args, cb); - } +/** + * @constructor + * @param {TarOptions} options + */ +var Tar = function(options) { + if (!(this instanceof Tar)) { + return new Tar(options); + } - if (opts) retry(opts, taskFn, callback); - else retry(taskFn, callback); + options = this.options = util.defaults(options, { + gzip: false + }); - return callback[PROMISE_SYMBOL] - }); - } + if (typeof options.gzipOptions !== 'object') { + options.gzipOptions = {}; + } + + this.supports = { + directory: true, + symlink: true + }; + + this.engine = engine.pack(options); + this.compressor = false; + + if (options.gzip) { + this.compressor = zlib.createGzip(options.gzipOptions); + this.compressor.on('error', this._onCompressorError.bind(this)); + } +}; + +/** + * [_onCompressorError description] + * + * @private + * @param {Error} err + * @return void + */ +Tar.prototype._onCompressorError = function(err) { + this.engine.emit('error', err); +}; + +/** + * [append description] + * + * @param {(Buffer|Stream)} source + * @param {TarEntryData} data + * @param {Function} callback + * @return void + */ +Tar.prototype.append = function(source, data, callback) { + var self = this; + + data.mtime = data.date; + + function append(err, sourceBuffer) { + if (err) { + callback(err); + return; + } + + self.engine.entry(data, sourceBuffer, function(err) { + callback(err, data); + }); + } + + if (data.sourceType === 'buffer') { + append(null, source); + } else if (data.sourceType === 'stream' && data.stats) { + data.size = data.stats.size; + + var entry = self.engine.entry(data, function(err) { + callback(err, data); + }); + + source.pipe(entry); + } else if (data.sourceType === 'stream') { + util.collectStream(source, append); + } +}; + +/** + * [finalize description] + * + * @return void + */ +Tar.prototype.finalize = function() { + this.engine.finalize(); +}; + +/** + * [on description] + * + * @return this.engine + */ +Tar.prototype.on = function() { + return this.engine.on.apply(this.engine, arguments); +}; + +/** + * [pipe description] + * + * @param {String} destination + * @param {Object} options + * @return this.engine + */ +Tar.prototype.pipe = function(destination, options) { + if (this.compressor) { + return this.engine.pipe.apply(this.engine, [this.compressor]).pipe(destination, options); + } else { + return this.engine.pipe.apply(this.engine, arguments); + } +}; + +/** + * [unpipe description] + * + * @return this.engine + */ +Tar.prototype.unpipe = function() { + if (this.compressor) { + return this.compressor.unpipe.apply(this.compressor, arguments); + } else { + return this.engine.unpipe.apply(this.engine, arguments); + } +}; + +module.exports = Tar; + +/** + * @typedef {Object} TarOptions + * @global + * @property {Boolean} [gzip=false] Compress the tar archive using gzip. + * @property {Object} [gzipOptions] Passed to [zlib]{@link https://nodejs.org/api/zlib.html#zlib_class_options} + * to control compression. + * @property {*} [*] See [tar-stream]{@link https://github.com/mafintosh/tar-stream} documentation for additional properties. + */ + +/** + * @typedef {Object} TarEntryData + * @global + * @property {String} name Sets the entry name including internal path. + * @property {(String|Date)} [date=NOW()] Sets the entry date. + * @property {Number} [mode=D:0755/F:0644] Sets the entry permissions. + * @property {String} [prefix] Sets a path prefix for the entry name. Useful + * when working with methods like `directory` or `glob`. + * @property {fs.Stats} [stats] Sets the fs stat data for this entry allowing + * for reduction of fs stat calls when stat data is already known. + */ + +/** + * TarStream Module + * @external TarStream + * @see {@link https://github.com/mafintosh/tar-stream} + */ + + +/***/ }), + +/***/ 8987: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * ZIP Format Plugin + * + * @module plugins/zip + * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} + * @copyright (c) 2012-2014 Chris Talkington, contributors. + */ +var engine = __nccwpck_require__(86454); +var util = __nccwpck_require__(82072); + +/** + * @constructor + * @param {ZipOptions} [options] + * @param {String} [options.comment] Sets the zip archive comment. + * @param {Boolean} [options.forceLocalTime=false] Forces the archive to contain local file times instead of UTC. + * @param {Boolean} [options.forceZip64=false] Forces the archive to contain ZIP64 headers. + * @param {Boolean} [options.namePrependSlash=false] Prepends a forward slash to archive file paths. + * @param {Boolean} [options.store=false] Sets the compression method to STORE. + * @param {Object} [options.zlib] Passed to [zlib]{@link https://nodejs.org/api/zlib.html#zlib_class_options} + */ +var Zip = function(options) { + if (!(this instanceof Zip)) { + return new Zip(options); + } + + options = this.options = util.defaults(options, { + comment: '', + forceUTC: false, + namePrependSlash: false, + store: false + }); + + this.supports = { + directory: true, + symlink: true + }; + + this.engine = new engine(options); +}; + +/** + * @param {(Buffer|Stream)} source + * @param {ZipEntryData} data + * @param {String} data.name Sets the entry name including internal path. + * @param {(String|Date)} [data.date=NOW()] Sets the entry date. + * @param {Number} [data.mode=D:0755/F:0644] Sets the entry permissions. + * @param {String} [data.prefix] Sets a path prefix for the entry name. Useful + * when working with methods like `directory` or `glob`. + * @param {fs.Stats} [data.stats] Sets the fs stat data for this entry allowing + * for reduction of fs stat calls when stat data is already known. + * @param {Boolean} [data.store=ZipOptions.store] Sets the compression method to STORE. + * @param {Function} callback + * @return void + */ +Zip.prototype.append = function(source, data, callback) { + this.engine.entry(source, data, callback); +}; + +/** + * @return void + */ +Zip.prototype.finalize = function() { + this.engine.finalize(); +}; + +/** + * @return this.engine + */ +Zip.prototype.on = function() { + return this.engine.on.apply(this.engine, arguments); +}; + +/** + * @return this.engine + */ +Zip.prototype.pipe = function() { + return this.engine.pipe.apply(this.engine, arguments); +}; + +/** + * @return this.engine + */ +Zip.prototype.unpipe = function() { + return this.engine.unpipe.apply(this.engine, arguments); +}; + +module.exports = Zip; + +/** + * @typedef {Object} ZipOptions + * @global + * @property {String} [comment] Sets the zip archive comment. + * @property {Boolean} [forceLocalTime=false] Forces the archive to contain local file times instead of UTC. + * @property {Boolean} [forceZip64=false] Forces the archive to contain ZIP64 headers. + * @prpperty {Boolean} [namePrependSlash=false] Prepends a forward slash to archive file paths. + * @property {Boolean} [store=false] Sets the compression method to STORE. + * @property {Object} [zlib] Passed to [zlib]{@link https://nodejs.org/api/zlib.html#zlib_class_options} + * to control compression. + * @property {*} [*] See [zip-stream]{@link https://archiverjs.com/zip-stream/ZipStream.html} documentation for current list of properties. + */ + +/** + * @typedef {Object} ZipEntryData + * @global + * @property {String} name Sets the entry name including internal path. + * @property {(String|Date)} [date=NOW()] Sets the entry date. + * @property {Number} [mode=D:0755/F:0644] Sets the entry permissions. + * @property {Boolean} [namePrependSlash=ZipOptions.namePrependSlash] Prepends a forward slash to archive file paths. + * @property {String} [prefix] Sets a path prefix for the entry name. Useful + * when working with methods like `directory` or `glob`. + * @property {fs.Stats} [stats] Sets the fs stat data for this entry allowing + * for reduction of fs stat calls when stat data is already known. + * @property {Boolean} [store=ZipOptions.store] Sets the compression method to STORE. + */ + +/** + * ZipStream Module + * @external ZipStream + * @see {@link https://www.archiverjs.com/zip-stream/ZipStream.html} + */ + + +/***/ }), + +/***/ 57888: +/***/ (function(__unused_webpack_module, exports) { + +(function (global, factory) { + true ? factory(exports) : + 0; +})(this, (function (exports) { 'use strict'; /** - * Run the functions in the `tasks` collection in series, each one running once - * the previous function has completed. If any functions in the series pass an - * error to its callback, no more functions are run, and `callback` is - * immediately called with the value of the error. Otherwise, `callback` - * receives an array of results when `tasks` have completed. - * - * It is also possible to use an object instead of an array. Each property will - * be run as a function, and the results will be passed to the final `callback` - * as an object instead of an array. This can be a more readable way of handling - * results from {@link async.series}. - * - * **Note** that while many implementations preserve the order of object - * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) - * explicitly states that - * - * > The mechanics and order of enumerating the properties is not specified. + * Creates a continuation function with some arguments already applied. * - * So if you rely on the order in which your series of functions are executed, - * and want this to work on all platforms, consider using an array. + * Useful as a shorthand when combined with other control flow functions. Any + * arguments passed to the returned function are added to the arguments + * originally passed to apply. * - * @name series + * @name apply * @static - * @memberOf module:ControlFlow + * @memberOf module:Utils * @method - * @category Control Flow - * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing - * [async functions]{@link AsyncFunction} to run in series. - * Each function can complete with any number of optional `result` values. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed. This function gets a results array (or object) - * containing all the result arguments passed to the `task` callbacks. Invoked - * with (err, result). - * @return {Promise} a promise, if no callback is passed + * @category Util + * @param {Function} fn - The function you want to eventually apply all + * arguments to. Invokes with (arguments...). + * @param {...*} arguments... - Any number of arguments to automatically apply + * when the continuation is called. + * @returns {Function} the partially-applied function * @example * - * //Using Callbacks - * async.series([ - * function(callback) { - * setTimeout(function() { - * // do some async task - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * // then do another async task - * callback(null, 'two'); - * }, 100); - * } - * ], function(err, results) { - * console.log(results); - * // results is equal to ['one','two'] - * }); + * // using apply + * async.parallel([ + * async.apply(fs.writeFile, 'testfile1', 'test1'), + * async.apply(fs.writeFile, 'testfile2', 'test2') + * ]); * - * // an example using objects instead of arrays - * async.series({ - * one: function(callback) { - * setTimeout(function() { - * // do some async task - * callback(null, 1); - * }, 200); - * }, - * two: function(callback) { - * setTimeout(function() { - * // then do another async task - * callback(null, 2); - * }, 100); - * } - * }, function(err, results) { - * console.log(results); - * // results is equal to: { one: 1, two: 2 } - * }); * - * //Using Promises - * async.series([ + * // the same process without using apply + * async.parallel([ * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); + * fs.writeFile('testfile1', 'test1', callback); * }, * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ]).then(results => { - * console.log(results); - * // results is equal to ['one','two'] - * }).catch(err => { - * console.log(err); - * }); - * - * // an example using an object instead of an array - * async.series({ - * one: function(callback) { - * setTimeout(function() { - * // do some async task - * callback(null, 1); - * }, 200); - * }, - * two: function(callback) { - * setTimeout(function() { - * // then do another async task - * callback(null, 2); - * }, 100); - * } - * }).then(results => { - * console.log(results); - * // results is equal to: { one: 1, two: 2 } - * }).catch(err => { - * console.log(err); - * }); - * - * //Using async/await - * async () => { - * try { - * let results = await async.series([ - * function(callback) { - * setTimeout(function() { - * // do some async task - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * // then do another async task - * callback(null, 'two'); - * }, 100); - * } - * ]); - * console.log(results); - * // results is equal to ['one','two'] - * } - * catch (err) { - * console.log(err); + * fs.writeFile('testfile2', 'test2', callback); * } - * } + * ]); * - * // an example using an object instead of an array - * async () => { - * try { - * let results = await async.parallel({ - * one: function(callback) { - * setTimeout(function() { - * // do some async task - * callback(null, 1); - * }, 200); - * }, - * two: function(callback) { - * setTimeout(function() { - * // then do another async task - * callback(null, 2); - * }, 100); - * } - * }); - * console.log(results); - * // results is equal to: { one: 1, two: 2 } - * } - * catch (err) { - * console.log(err); - * } - * } + * // It's possible to pass any number of additional arguments when calling the + * // continuation: * + * node> var fn = async.apply(sys.puts, 'one'); + * node> fn('two', 'three'); + * one + * two + * three */ - function series(tasks, callback) { - return parallel(eachOfSeries$1, tasks, callback); + function apply(fn, ...args) { + return (...callArgs) => fn(...args,...callArgs); + } + + function initialParams (fn) { + return function (...args/*, callback*/) { + var callback = args.pop(); + return fn.call(this, args, callback); + }; + } + + /* istanbul ignore file */ + + var hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask; + var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; + var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; + + function fallback(fn) { + setTimeout(fn, 0); + } + + function wrap(defer) { + return (fn, ...args) => defer(() => fn(...args)); + } + + var _defer$1; + + if (hasQueueMicrotask) { + _defer$1 = queueMicrotask; + } else if (hasSetImmediate) { + _defer$1 = setImmediate; + } else if (hasNextTick) { + _defer$1 = process.nextTick; + } else { + _defer$1 = fallback; } + var setImmediate$1 = wrap(_defer$1); + /** - * Returns `true` if at least one element in the `coll` satisfies an async test. - * If any iteratee call returns `true`, the main `callback` is immediately - * called. + * Take a sync function and make it async, passing its return value to a + * callback. This is useful for plugging sync functions into a waterfall, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. * - * @name some + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify * @static - * @memberOf module:Collections + * @memberOf module:Utils * @method - * @alias any - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in parallel. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - * @returns {Promise} a promise, if no callback provided + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. * @example * - * // dir1 is a directory that contains file1.txt, file2.txt - * // dir2 is a directory that contains file3.txt, file4.txt - * // dir3 is a directory that contains file5.txt - * // dir4 does not exist - * - * // asynchronous function that checks if a file exists - * function fileExists(file, callback) { - * fs.access(file, fs.constants.F_OK, (err) => { - * callback(null, !err); - * }); - * } - * - * // Using callbacks - * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists, - * function(err, result) { - * console.log(result); - * // true - * // result is true since some file in the list exists - * } - *); - * - * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists, - * function(err, result) { - * console.log(result); - * // false - * // result is false since none of the files exists - * } - *); - * - * // Using Promises - * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists) - * .then( result => { - * console.log(result); - * // true - * // result is true since some file in the list exists - * }).catch( err => { - * console.log(err); - * }); - * - * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists) - * .then( result => { - * console.log(result); - * // false - * // result is false since none of the files exists - * }).catch( err => { - * console.log(err); - * }); - * - * // Using async/await - * async () => { - * try { - * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists); - * console.log(result); - * // true - * // result is true since some file in the list exists - * } - * catch (err) { - * console.log(err); + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. * } - * } + * ], callback); * - * async () => { - * try { - * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists); - * console.log(result); - * // false - * // result is false since none of the files exists - * } - * catch (err) { - * console.log(err); + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. * } - * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); * + * q.push(files); */ - function some(coll, iteratee, callback) { - return _createTester(Boolean, res => res)(eachOf$1, coll, iteratee, callback) + function asyncify(func) { + if (isAsync(func)) { + return function (...args/*, callback*/) { + const callback = args.pop(); + const promise = func.apply(this, args); + return handlePromise(promise, callback) + } + } + + return initialParams(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (result && typeof result.then === 'function') { + return handlePromise(result, callback) + } else { + callback(null, result); + } + }); } - var some$1 = awaitify(some, 3); + + function handlePromise(promise, callback) { + return promise.then(value => { + invokeCallback(callback, null, value); + }, err => { + invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err)); + }); + } + + function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (err) { + setImmediate$1(e => { throw e }, err); + } + } + + function isAsync(fn) { + return fn[Symbol.toStringTag] === 'AsyncFunction'; + } + + function isAsyncGenerator(fn) { + return fn[Symbol.toStringTag] === 'AsyncGenerator'; + } + + function isAsyncIterable(obj) { + return typeof obj[Symbol.asyncIterator] === 'function'; + } + + function wrapAsync(asyncFn) { + if (typeof asyncFn !== 'function') throw new Error('expected a function') + return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; + } + + // conditionally promisify a function. + // only return a promise if a callback is omitted + function awaitify (asyncFn, arity) { + if (!arity) arity = asyncFn.length; + if (!arity) throw new Error('arity is undefined') + function awaitable (...args) { + if (typeof args[arity - 1] === 'function') { + return asyncFn.apply(this, args) + } + + return new Promise((resolve, reject) => { + args[arity - 1] = (err, ...cbArgs) => { + if (err) return reject(err) + resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]); + }; + asyncFn.apply(this, args); + }) + } + + return awaitable + } + + function applyEach$1 (eachfn) { + return function applyEach(fns, ...callArgs) { + const go = awaitify(function (callback) { + var that = this; + return eachfn(fns, (fn, cb) => { + wrapAsync(fn).apply(that, callArgs.concat(cb)); + }, callback); + }); + return go; + }; + } + + function _asyncMap(eachfn, arr, iteratee, callback) { + arr = arr || []; + var results = []; + var counter = 0; + var _iteratee = wrapAsync(iteratee); + + return eachfn(arr, (value, _, iterCb) => { + var index = counter++; + _iteratee(value, (err, v) => { + results[index] = v; + iterCb(err); + }); + }, err => { + callback(err, results); + }); + } + + function isArrayLike(value) { + return value && + typeof value.length === 'number' && + value.length >= 0 && + value.length % 1 === 0; + } + + // A temporary value used to identify if the loop should be broken. + // See #1064, #1293 + const breakLoop = {}; + var breakLoop$1 = breakLoop; + + function once(fn) { + function wrapper (...args) { + if (fn === null) return; + var callFn = fn; + fn = null; + callFn.apply(this, args); + } + Object.assign(wrapper, fn); + return wrapper + } + + function getIterator (coll) { + return coll[Symbol.iterator] && coll[Symbol.iterator](); + } + + function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? {value: coll[i], key: i} : null; + } + } + + function createES2015Iterator(iterator) { + var i = -1; + return function next() { + var item = iterator.next(); + if (item.done) + return null; + i++; + return {value: item.value, key: i}; + } + } + + function createObjectIterator(obj) { + var okeys = obj ? Object.keys(obj) : []; + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + if (key === '__proto__') { + return next(); + } + return i < len ? {value: obj[key], key} : null; + }; + } + + function createIterator(coll) { + if (isArrayLike(coll)) { + return createArrayIterator(coll); + } + + var iterator = getIterator(coll); + return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); + } + + function onlyOnce(fn) { + return function (...args) { + if (fn === null) throw new Error("Callback was already called."); + var callFn = fn; + fn = null; + callFn.apply(this, args); + }; + } + + // for async generators + function asyncEachOfLimit(generator, limit, iteratee, callback) { + let done = false; + let canceled = false; + let awaiting = false; + let running = 0; + let idx = 0; + + function replenish() { + //console.log('replenish') + if (running >= limit || awaiting || done) return + //console.log('replenish awaiting') + awaiting = true; + generator.next().then(({value, done: iterDone}) => { + //console.log('got value', value) + if (canceled || done) return + awaiting = false; + if (iterDone) { + done = true; + if (running <= 0) { + //console.log('done nextCb') + callback(null); + } + return; + } + running++; + iteratee(value, idx, iterateeCallback); + idx++; + replenish(); + }).catch(handleError); + } + + function iterateeCallback(err, result) { + //console.log('iterateeCallback') + running -= 1; + if (canceled) return + if (err) return handleError(err) + + if (err === false) { + done = true; + canceled = true; + return + } + + if (result === breakLoop$1 || (done && running <= 0)) { + done = true; + //console.log('done iterCb') + return callback(null); + } + replenish(); + } + + function handleError(err) { + if (canceled) return + awaiting = false; + done = true; + callback(err); + } + + replenish(); + } + + var eachOfLimit$2 = (limit) => { + return (obj, iteratee, callback) => { + callback = once(callback); + if (limit <= 0) { + throw new RangeError('concurrency limit cannot be less than 1') + } + if (!obj) { + return callback(null); + } + if (isAsyncGenerator(obj)) { + return asyncEachOfLimit(obj, limit, iteratee, callback) + } + if (isAsyncIterable(obj)) { + return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback) + } + var nextElem = createIterator(obj); + var done = false; + var canceled = false; + var running = 0; + var looping = false; + + function iterateeCallback(err, value) { + if (canceled) return + running -= 1; + if (err) { + done = true; + callback(err); + } + else if (err === false) { + done = true; + canceled = true; + } + else if (value === breakLoop$1 || (done && running <= 0)) { + done = true; + return callback(null); + } + else if (!looping) { + replenish(); + } + } + + function replenish () { + looping = true; + while (running < limit && !done) { + var elem = nextElem(); + if (elem === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + iteratee(elem.value, elem.key, onlyOnce(iterateeCallback)); + } + looping = false; + } + + replenish(); + }; + }; /** - * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a + * time. * - * @name someLimit + * @name eachOfLimit * @static * @memberOf module:Collections * @method - * @see [async.some]{@link module:Collections.some} - * @alias anyLimit + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit * @category Collection * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in parallel. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - * @returns {Promise} a promise, if no callback provided + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted */ - function someLimit(coll, limit, iteratee, callback) { - return _createTester(Boolean, res => res)(eachOfLimit(limit), coll, iteratee, callback) + function eachOfLimit(coll, limit, iteratee, callback) { + return eachOfLimit$2(limit)(coll, wrapAsync(iteratee), callback); } - var someLimit$1 = awaitify(someLimit, 4); - /** - * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. - * - * @name someSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.some]{@link module:Collections.some} - * @alias anySeries - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in series. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - * @returns {Promise} a promise, if no callback provided - */ - function someSeries(coll, iteratee, callback) { - return _createTester(Boolean, res => res)(eachOfSeries$1, coll, iteratee, callback) + var eachOfLimit$1 = awaitify(eachOfLimit, 4); + + // eachOf implementation optimized for array-likes + function eachOfArrayLike(coll, iteratee, callback) { + callback = once(callback); + var index = 0, + completed = 0, + {length} = coll, + canceled = false; + if (length === 0) { + callback(null); + } + + function iteratorCallback(err, value) { + if (err === false) { + canceled = true; + } + if (canceled === true) return + if (err) { + callback(err); + } else if ((++completed === length) || value === breakLoop$1) { + callback(null); + } + } + + for (; index < length; index++) { + iteratee(coll[index], index, onlyOnce(iteratorCallback)); + } + } + + // a generic version of eachOf which can handle array, object, and iterator cases. + function eachOfGeneric (coll, iteratee, callback) { + return eachOfLimit$1(coll, Infinity, iteratee, callback); } - var someSeries$1 = awaitify(someSeries, 3); /** - * Sorts a list by the results of running each `coll` value through an async - * `iteratee`. + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument + * to the iteratee. * - * @name sortBy + * @name eachOf * @static * @memberOf module:Collections * @method + * @alias forEachOf * @category Collection + * @see [async.each]{@link module:Collections.each} * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a value to use as the sort criteria as - * its `result`. - * Invoked with (item, callback). - * @param {Function} callback - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is the items - * from the original `coll` sorted by the values returned by the `iteratee` - * calls. Invoked with (err, results). - * @returns {Promise} a promise, if no callback passed - * @example - * - * // bigfile.txt is a file that is 251100 bytes in size - * // mediumfile.txt is a file that is 11000 bytes in size - * // smallfile.txt is a file that is 121 bytes in size + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example * - * // asynchronous function that returns the file size in bytes - * function getFileSizeInBytes(file, callback) { - * fs.stat(file, function(err, stat) { - * if (err) { - * return callback(err); + * // dev.json is a file containing a valid json object config for dev environment + * // dev.json is a file containing a valid json object config for test environment + * // prod.json is a file containing a valid json object config for prod environment + * // invalid.json is a file with a malformed json object + * + * let configs = {}; //global variable + * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'}; + * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'}; + * + * // asynchronous function that reads a json file and parses the contents as json object + * function parseFile(file, key, callback) { + * fs.readFile(file, "utf8", function(err, data) { + * if (err) return calback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); * } - * callback(null, stat.size); + * callback(); * }); * } * * // Using callbacks - * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes, - * function(err, results) { - * if (err) { - * console.log(err); - * } else { - * console.log(results); - * // results is now the original array of files sorted by - * // file size (ascending by default), e.g. - * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] - * } + * async.forEachOf(validConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * } else { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} * } - * ); + * }); * - * // By modifying the callback parameter the - * // sorting order can be influenced: + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * // JSON parse error exception + * } else { + * console.log(configs); + * } + * }); * - * // ascending order - * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], function(file, callback) { - * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { - * if (getFileSizeErr) return callback(getFileSizeErr); - * callback(null, fileSize); - * }); - * }, function(err, results) { - * if (err) { - * console.log(err); - * } else { - * console.log(results); - * // results is now the original array of files sorted by - * // file size (ascending by default), e.g. - * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] - * } + * // Using Promises + * async.forEachOf(validConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * }).catch( err => { + * console.error(err); + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * }).catch( err => { + * console.error(err); + * // JSON parse error exception + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.forEachOf(validConfigFileMap, parseFile); + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} * } - * ); + * catch (err) { + * console.log(err); + * } + * } * - * // descending order - * async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], function(file, callback) { - * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { - * if (getFileSizeErr) { - * return callback(getFileSizeErr); - * } - * callback(null, fileSize * -1); - * }); - * }, function(err, results) { - * if (err) { - * console.log(err); - * } else { - * console.log(results); - * // results is now the original array of files sorted by - * // file size (ascending by default), e.g. - * // [ 'bigfile.txt', 'mediumfile.txt', 'smallfile.txt'] - * } + * //Error handing + * async () => { + * try { + * let result = await async.forEachOf(invalidConfigFileMap, parseFile); + * console.log(configs); * } - * ); + * catch (err) { + * console.log(err); + * // JSON parse error exception + * } + * } * - * // Error handling - * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes, - * function(err, results) { + */ + function eachOf(coll, iteratee, callback) { + var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; + return eachOfImplementation(coll, wrapAsync(iteratee), callback); + } + + var eachOf$1 = awaitify(eachOf, 3); + + /** + * Produces a new collection of values by mapping each value in `coll` through + * the `iteratee` function. The `iteratee` is called with an item from `coll` + * and a callback for when it has finished processing. Each of these callbacks + * takes 2 arguments: an `error`, and the transformed item from `coll`. If + * `iteratee` passes an error to its callback, the main `callback` (for the + * `map` function) is immediately called with the error. + * + * Note, that since this function applies the `iteratee` to each item in + * parallel, there is no guarantee that the `iteratee` functions will complete + * in order. However, the results array will be in the same order as the + * original `coll`. + * + * If `map` is passed an Object, the results will be an Array. The results + * will roughly be in the order of the original Objects' keys (but this can + * vary across JavaScript engines). + * + * @name map + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an Array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { * if (err) { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * } else { - * console.log(results); + * return callback(err); * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.map(fileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] * } - * ); + * }); + * + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * }); * * // Using Promises - * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes) + * async.map(fileList, getFileSizeInBytes) * .then( results => { * console.log(results); - * // results is now the original array of files sorted by - * // file size (ascending by default), e.g. - * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] * }).catch( err => { * console.log(err); * }); * - * // Error handling - * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes) + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes) * .then( results => { * console.log(results); * }).catch( err => { @@ -61617,23 +56854,22 @@ module.exports = Zip; * }); * * // Using async/await - * (async () => { + * async () => { * try { - * let results = await async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * let results = await async.map(fileList, getFileSizeInBytes); * console.log(results); - * // results is now the original array of files sorted by - * // file size (ascending by default), e.g. - * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] * } * catch (err) { * console.log(err); * } - * })(); + * } * - * // Error handling + * // Error Handling * async () => { * try { - * let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * let results = await async.map(withMissingFileList, getFileSizeInBytes); * console.log(results); * } * catch (err) { @@ -61643,311 +56879,275 @@ module.exports = Zip; * } * */ - function sortBy (coll, iteratee, callback) { - var _iteratee = wrapAsync(iteratee); - return map$1(coll, (x, iterCb) => { - _iteratee(x, (err, criteria) => { - if (err) return iterCb(err); - iterCb(err, {value: x, criteria}); - }); - }, (err, results) => { - if (err) return callback(err); - callback(null, results.sort(comparator).map(v => v.value)); - }); - - function comparator(left, right) { - var a = left.criteria, b = right.criteria; - return a < b ? -1 : a > b ? 1 : 0; - } + function map (coll, iteratee, callback) { + return _asyncMap(eachOf$1, coll, iteratee, callback) } - var sortBy$1 = awaitify(sortBy, 3); + var map$1 = awaitify(map, 3); /** - * Sets a time limit on an asynchronous function. If the function does not call - * its callback within the specified milliseconds, it will be called with a - * timeout error. The code property for the error object will be `'ETIMEDOUT'`. + * Applies the provided arguments to each function in the array, calling + * `callback` after all functions have completed. If you only provide the first + * argument, `fns`, then it will return a function which lets you pass in the + * arguments as if it were a single function call. If more arguments are + * provided, `callback` is required while `args` is still optional. The results + * for each of the applied async functions are passed to the final callback + * as an array. * - * @name timeout + * @name applyEach * @static - * @memberOf module:Utils + * @memberOf module:ControlFlow * @method - * @category Util - * @param {AsyncFunction} asyncFn - The async function to limit in time. - * @param {number} milliseconds - The specified time limit. - * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) - * to timeout Error for more information.. - * @returns {AsyncFunction} Returns a wrapped function that can be used with any - * of the control flow functions. - * Invoke this function with the same parameters as you would `asyncFunc`. + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s + * to all call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - Returns a function that takes no args other than + * an optional callback, that is the result of applying the `args` to each + * of the functions. * @example * - * function myFunction(foo, callback) { - * doAsyncTask(foo, function(err, data) { - * // handle errors - * if (err) return callback(err); - * - * // do some stuff ... - * - * // return processed data - * return callback(null, data); - * }); - * } - * - * var wrapped = async.timeout(myFunction, 1000); - * - * // call `wrapped` as you would `myFunction` - * wrapped({ bar: 'bar' }, function(err, data) { - * // if `myFunction` takes < 1000 ms to execute, `err` - * // and `data` will have their expected values + * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket') * - * // else `err` will be an Error with the code 'ETIMEDOUT' + * appliedFn((err, results) => { + * // results[0] is the results for `enableSearch` + * // results[1] is the results for `updateSchema` * }); + * + * // partial application example: + * async.each( + * buckets, + * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(), + * callback + * ); */ - function timeout(asyncFn, milliseconds, info) { - var fn = wrapAsync(asyncFn); - - return initialParams((args, callback) => { - var timedOut = false; - var timer; - - function timeoutCallback() { - var name = asyncFn.name || 'anonymous'; - var error = new Error('Callback function "' + name + '" timed out.'); - error.code = 'ETIMEDOUT'; - if (info) { - error.info = info; - } - timedOut = true; - callback(error); - } - - args.push((...cbArgs) => { - if (!timedOut) { - callback(...cbArgs); - clearTimeout(timer); - } - }); - - // setup timer and call original function - timer = setTimeout(timeoutCallback, milliseconds); - fn(...args); - }); - } - - function range(size) { - var result = Array(size); - while (size--) { - result[size] = size; - } - return result; - } + var applyEach = applyEach$1(map$1); /** - * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a - * time. + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. * - * @name timesLimit + * @name eachOfSeries * @static - * @memberOf module:ControlFlow + * @memberOf module:Collections * @method - * @see [async.times]{@link module:ControlFlow.times} - * @category Control Flow - * @param {number} count - The number of times to run the function. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see [async.map]{@link module:Collections.map}. - * @returns {Promise} a promise, if no callback is provided + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted */ - function timesLimit(count, limit, iteratee, callback) { - var _iteratee = wrapAsync(iteratee); - return mapLimit$1(range(count), limit, _iteratee, callback); + function eachOfSeries(coll, iteratee, callback) { + return eachOfLimit$1(coll, 1, iteratee, callback) } + var eachOfSeries$1 = awaitify(eachOfSeries, 3); /** - * Calls the `iteratee` function `n` times, and accumulates results in the same - * manner you would use with [map]{@link module:Collections.map}. + * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. * - * @name times + * @name mapSeries * @static - * @memberOf module:ControlFlow + * @memberOf module:Collections * @method * @see [async.map]{@link module:Collections.map} - * @category Control Flow - * @param {number} n - The number of times to run the function. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see {@link module:Collections.map}. - * @returns {Promise} a promise, if no callback is provided - * @example - * - * // Pretend this is some complicated async factory - * var createUser = function(id, callback) { - * callback(null, { - * id: 'user' + id - * }); - * }; - * - * // generate 5 users - * async.times(5, function(n, next) { - * createUser(n, function(err, user) { - * next(err, user); - * }); - * }, function(err, users) { - * // we should now have 5 users - * }); + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed */ - function times (n, iteratee, callback) { - return timesLimit(n, Infinity, iteratee, callback) + function mapSeries (coll, iteratee, callback) { + return _asyncMap(eachOfSeries$1, coll, iteratee, callback) } + var mapSeries$1 = awaitify(mapSeries, 3); /** - * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. + * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. * - * @name timesSeries + * @name applyEachSeries * @static * @memberOf module:ControlFlow * @method - * @see [async.times]{@link module:ControlFlow.times} + * @see [async.applyEach]{@link module:ControlFlow.applyEach} * @category Control Flow - * @param {number} n - The number of times to run the function. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see {@link module:Collections.map}. - * @returns {Promise} a promise, if no callback is provided + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all + * call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - A function, that when called, is the result of + * appling the `args` to the list of functions. It takes no args, other than + * a callback. */ - function timesSeries (n, iteratee, callback) { - return timesLimit(n, 1, iteratee, callback) + var applyEachSeries = applyEach$1(mapSeries$1); + + const PROMISE_SYMBOL = Symbol('promiseCallback'); + + function promiseCallback () { + let resolve, reject; + function callback (err, ...args) { + if (err) return reject(err) + resolve(args.length > 1 ? args : args[0]); + } + + callback[PROMISE_SYMBOL] = new Promise((res, rej) => { + resolve = res, + reject = rej; + }); + + return callback } /** - * A relative of `reduce`. Takes an Object or Array, and iterates over each - * element in parallel, each step potentially mutating an `accumulator` value. - * The type of the accumulator defaults to the type of collection passed in. + * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on + * their requirements. Each function can optionally depend on other functions + * being completed first, and each function is run as soon as its requirements + * are satisfied. * - * @name transform + * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence + * will stop. Further tasks will not execute (so any other functions depending + * on it will not run), and the main `callback` is immediately called with the + * error. + * + * {@link AsyncFunction}s also receive an object containing the results of functions which + * have completed so far as the first argument, if they have dependencies. If a + * task function has no dependencies, it will only be passed a callback. + * + * @name auto * @static - * @memberOf module:Collections + * @memberOf module:ControlFlow * @method - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {*} [accumulator] - The initial state of the transform. If omitted, - * it will default to an empty Object or Array, depending on the type of `coll` - * @param {AsyncFunction} iteratee - A function applied to each item in the - * collection that potentially modifies the accumulator. - * Invoked with (accumulator, item, key, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the transformed accumulator. - * Invoked with (err, result). - * @returns {Promise} a promise, if no callback provided - * @example - * - * // file1.txt is a file that is 1000 bytes in size - * // file2.txt is a file that is 2000 bytes in size - * // file3.txt is a file that is 3000 bytes in size - * - * // helper function that returns human-readable size format from bytes - * function formatBytes(bytes, decimals = 2) { - * // implementation not included for brevity - * return humanReadbleFilesize; - * } - * - * const fileList = ['file1.txt','file2.txt','file3.txt']; - * - * // asynchronous function that returns the file size, transformed to human-readable format - * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. - * function transformFileSize(acc, value, key, callback) { - * fs.stat(value, function(err, stat) { - * if (err) { - * return callback(err); - * } - * acc[key] = formatBytes(stat.size); - * callback(null); - * }); - * } - * - * // Using callbacks - * async.transform(fileList, transformFileSize, function(err, result) { - * if(err) { - * console.log(err); - * } else { - * console.log(result); - * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] - * } - * }); - * - * // Using Promises - * async.transform(fileList, transformFileSize) - * .then(result => { - * console.log(result); - * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] - * }).catch(err => { - * console.log(err); - * }); - * - * // Using async/await - * (async () => { - * try { - * let result = await async.transform(fileList, transformFileSize); - * console.log(result); - * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] - * } - * catch (err) { - * console.log(err); - * } - * })(); - * + * @category Control Flow + * @param {Object} tasks - An object. Each of its properties is either a + * function or an array of requirements, with the {@link AsyncFunction} itself the last item + * in the array. The object's key of a property serves as the name of the task + * defined by that property, i.e. can be used when specifying requirements for + * other tasks. The function receives one or two arguments: + * * a `results` object, containing the results of the previously executed + * functions, only passed if the task has any dependencies, + * * a `callback(err, result)` function, which must be called when finished, + * passing an `error` (which can be `null`) and the result of the function's + * execution. + * @param {number} [concurrency=Infinity] - An optional `integer` for + * determining the maximum number of tasks that can be run in parallel. By + * default, as many as possible. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback. Results are always returned; however, if an + * error occurs, no further `tasks` will be performed, and the results object + * will only contain partial results. Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed * @example * - * // file1.txt is a file that is 1000 bytes in size - * // file2.txt is a file that is 2000 bytes in size - * // file3.txt is a file that is 3000 bytes in size - * - * // helper function that returns human-readable size format from bytes - * function formatBytes(bytes, decimals = 2) { - * // implementation not included for brevity - * return humanReadbleFilesize; - * } - * - * const fileMap = { f1: 'file1.txt', f2: 'file2.txt', f3: 'file3.txt' }; - * - * // asynchronous function that returns the file size, transformed to human-readable format - * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. - * function transformFileSize(acc, value, key, callback) { - * fs.stat(value, function(err, stat) { - * if (err) { - * return callback(err); - * } - * acc[key] = formatBytes(stat.size); - * callback(null); - * }); - * } - * - * // Using callbacks - * async.transform(fileMap, transformFileSize, function(err, result) { - * if(err) { - * console.log(err); - * } else { - * console.log(result); - * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * //Using Callbacks + * async.auto({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }, function(err, results) { + * if (err) { + * console.log('err = ', err); * } + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } * }); * - * // Using Promises - * async.transform(fileMap, transformFileSize) - * .then(result => { - * console.log(result); - * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * //Using Promises + * async.auto({ + * get_data: function(callback) { + * console.log('in get_data'); + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * console.log('in make_folder'); + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }).then(results => { + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } * }).catch(err => { - * console.log(err); + * console.log('err = ', err); * }); * - * // Using async/await + * //Using async/await * async () => { * try { - * let result = await async.transform(fileMap, transformFileSize); - * console.log(result); - * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * let results = await async.auto({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }); + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } * } * catch (err) { * console.log(err); @@ -61955,11990 +57155,10508 @@ module.exports = Zip; * } * */ - function transform (coll, accumulator, iteratee, callback) { - if (arguments.length <= 3 && typeof accumulator === 'function') { - callback = iteratee; - iteratee = accumulator; - accumulator = Array.isArray(coll) ? [] : {}; + function auto(tasks, concurrency, callback) { + if (typeof concurrency !== 'number') { + // concurrency is optional, shift the args. + callback = concurrency; + concurrency = null; } callback = once(callback || promiseCallback()); - var _iteratee = wrapAsync(iteratee); + var numTasks = Object.keys(tasks).length; + if (!numTasks) { + return callback(null); + } + if (!concurrency) { + concurrency = numTasks; + } - eachOf$1(coll, (v, k, cb) => { - _iteratee(accumulator, v, k, cb); - }, err => callback(err, accumulator)); - return callback[PROMISE_SYMBOL] - } + var results = {}; + var runningTasks = 0; + var canceled = false; + var hasError = false; - /** - * It runs each task in series but stops whenever any of the functions were - * successful. If one of the tasks were successful, the `callback` will be - * passed the result of the successful task. If all tasks fail, the callback - * will be passed the error and result (if any) of the final attempt. - * - * @name tryEach - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to - * run, each function is passed a `callback(err, result)` it must call on - * completion with an error `err` (which can be `null`) and an optional `result` - * value. - * @param {Function} [callback] - An optional callback which is called when one - * of the tasks has succeeded, or all have failed. It receives the `err` and - * `result` arguments of the last attempt at completing the `task`. Invoked with - * (err, results). - * @returns {Promise} a promise, if no callback is passed - * @example - * async.tryEach([ - * function getDataFromFirstWebsite(callback) { - * // Try getting the data from the first website - * callback(err, data); - * }, - * function getDataFromSecondWebsite(callback) { - * // First website failed, - * // Try getting the data from the backup website - * callback(err, data); - * } - * ], - * // optional callback - * function(err, results) { - * Now do something with the data. - * }); - * - */ - function tryEach(tasks, callback) { - var error = null; - var result; - return eachSeries$1(tasks, (task, taskCb) => { - wrapAsync(task)((err, ...args) => { - if (err === false) return taskCb(err); + var listeners = Object.create(null); - if (args.length < 2) { - [result] = args; + var readyTasks = []; + + // for cycle detection: + var readyToCheck = []; // tasks that have been identified as reachable + // without the possibility of returning to an ancestor task + var uncheckedDependencies = {}; + + Object.keys(tasks).forEach(key => { + var task = tasks[key]; + if (!Array.isArray(task)) { + // no dependencies + enqueueTask(key, [task]); + readyToCheck.push(key); + return; + } + + var dependencies = task.slice(0, task.length - 1); + var remainingDependencies = dependencies.length; + if (remainingDependencies === 0) { + enqueueTask(key, task); + readyToCheck.push(key); + return; + } + uncheckedDependencies[key] = remainingDependencies; + + dependencies.forEach(dependencyName => { + if (!tasks[dependencyName]) { + throw new Error('async.auto task `' + key + + '` has a non-existent dependency `' + + dependencyName + '` in ' + + dependencies.join(', ')); + } + addListener(dependencyName, () => { + remainingDependencies--; + if (remainingDependencies === 0) { + enqueueTask(key, task); + } + }); + }); + }); + + checkForDeadlocks(); + processQueue(); + + function enqueueTask(key, task) { + readyTasks.push(() => runTask(key, task)); + } + + function processQueue() { + if (canceled) return + if (readyTasks.length === 0 && runningTasks === 0) { + return callback(null, results); + } + while(readyTasks.length && runningTasks < concurrency) { + var run = readyTasks.shift(); + run(); + } + + } + + function addListener(taskName, fn) { + var taskListeners = listeners[taskName]; + if (!taskListeners) { + taskListeners = listeners[taskName] = []; + } + + taskListeners.push(fn); + } + + function taskComplete(taskName) { + var taskListeners = listeners[taskName] || []; + taskListeners.forEach(fn => fn()); + processQueue(); + } + + + function runTask(key, task) { + if (hasError) return; + + var taskCallback = onlyOnce((err, ...result) => { + runningTasks--; + if (err === false) { + canceled = true; + return + } + if (result.length < 2) { + [result] = result; + } + if (err) { + var safeResults = {}; + Object.keys(results).forEach(rkey => { + safeResults[rkey] = results[rkey]; + }); + safeResults[key] = result; + hasError = true; + listeners = Object.create(null); + if (canceled) return + callback(err, safeResults); } else { - result = args; + results[key] = result; + taskComplete(key); } - error = err; - taskCb(err ? null : {}); }); - }, () => callback(error, result)); + + runningTasks++; + var taskFn = wrapAsync(task[task.length - 1]); + if (task.length > 1) { + taskFn(results, taskCallback); + } else { + taskFn(taskCallback); + } + } + + function checkForDeadlocks() { + // Kahn's algorithm + // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm + // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html + var currentTask; + var counter = 0; + while (readyToCheck.length) { + currentTask = readyToCheck.pop(); + counter++; + getDependents(currentTask).forEach(dependent => { + if (--uncheckedDependencies[dependent] === 0) { + readyToCheck.push(dependent); + } + }); + } + + if (counter !== numTasks) { + throw new Error( + 'async.auto cannot execute tasks due to a recursive dependency' + ); + } + } + + function getDependents(taskName) { + var result = []; + Object.keys(tasks).forEach(key => { + const task = tasks[key]; + if (Array.isArray(task) && task.indexOf(taskName) >= 0) { + result.push(key); + } + }); + return result; + } + + return callback[PROMISE_SYMBOL] } - var tryEach$1 = awaitify(tryEach); + var FN_ARGS = /^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/; + var ARROW_FN_ARGS = /^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/; + var FN_ARG_SPLIT = /,/; + var FN_ARG = /(=.+)?(\s*)$/; - /** - * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, - * unmemoized form. Handy for testing. - * - * @name unmemoize - * @static - * @memberOf module:Utils - * @method - * @see [async.memoize]{@link module:Utils.memoize} - * @category Util - * @param {AsyncFunction} fn - the memoized function - * @returns {AsyncFunction} a function that calls the original unmemoized function - */ - function unmemoize(fn) { - return (...args) => { - return (fn.unmemoized || fn)(...args); - }; + function stripComments(string) { + let stripped = ''; + let index = 0; + let endBlockComment = string.indexOf('*/'); + while (index < string.length) { + if (string[index] === '/' && string[index+1] === '/') { + // inline comment + let endIndex = string.indexOf('\n', index); + index = (endIndex === -1) ? string.length : endIndex; + } else if ((endBlockComment !== -1) && (string[index] === '/') && (string[index+1] === '*')) { + // block comment + let endIndex = string.indexOf('*/', index); + if (endIndex !== -1) { + index = endIndex + 2; + endBlockComment = string.indexOf('*/', index); + } else { + stripped += string[index]; + index++; + } + } else { + stripped += string[index]; + index++; + } + } + return stripped; + } + + function parseParams(func) { + const src = stripComments(func.toString()); + let match = src.match(FN_ARGS); + if (!match) { + match = src.match(ARROW_FN_ARGS); + } + if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src) + let [, args] = match; + return args + .replace(/\s/g, '') + .split(FN_ARG_SPLIT) + .map((arg) => arg.replace(FN_ARG, '').trim()); } /** - * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when - * stopped, or an error occurs. + * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent + * tasks are specified as parameters to the function, after the usual callback + * parameter, with the parameter names matching the names of the tasks it + * depends on. This can provide even more readable task graphs which can be + * easier to maintain. * - * @name whilst + * If a final callback is specified, the task results are similarly injected, + * specified as named parameters after the initial error parameter. + * + * The autoInject function is purely syntactic sugar and its semantics are + * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. + * + * @name autoInject * @static * @memberOf module:ControlFlow * @method + * @see [async.auto]{@link module:ControlFlow.auto} * @category Control Flow - * @param {AsyncFunction} test - asynchronous truth test to perform before each - * execution of `iteratee`. Invoked with (). - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); + * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of + * the form 'func([dependencies...], callback). The object's key of a property + * serves as the name of the task defined by that property, i.e. can be used + * when specifying requirements for other tasks. + * * The `callback` parameter is a `callback(err, result)` which must be called + * when finished, passing an `error` (which can be `null`) and the result of + * the function's execution. The remaining parameters name other tasks on + * which the task is dependent, and the results from those tasks are the + * arguments of those parameters. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback, and a `results` object with any completed + * task results, similar to `auto`. * @returns {Promise} a promise, if no callback is passed * @example * - * var count = 0; - * async.whilst( - * function test(cb) { cb(null, count < 5); }, - * function iter(callback) { - * count++; - * setTimeout(function() { - * callback(null, count); - * }, 1000); + * // The example from `auto` can be rewritten as follows: + * async.autoInject({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); * }, - * function (err, n) { - * // 5 seconds have passed, n = 5 - * } - * ); - */ - function whilst(test, iteratee, callback) { - callback = onlyOnce(callback); - var _fn = wrapAsync(iteratee); - var _test = wrapAsync(test); - var results = []; - - function next(err, ...rest) { - if (err) return callback(err); - results = rest; - if (err === false) return; - _test(check); - } - - function check(err, truth) { - if (err) return callback(err); - if (err === false) return; - if (!truth) return callback(null, ...results); - _fn(next); - } - - return _test(check); - } - var whilst$1 = awaitify(whilst, 3); - - /** - * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when - * stopped, or an error occurs. `callback` will be passed an error and any - * arguments passed to the final `iteratee`'s callback. - * - * The inverse of [whilst]{@link module:ControlFlow.whilst}. - * - * @name until - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {AsyncFunction} test - asynchronous truth test to perform before each - * execution of `iteratee`. Invoked with (callback). - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` fails. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has passed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - * @returns {Promise} a promise, if a callback is not passed - * - * @example - * const results = [] - * let finished = false - * async.until(function test(cb) { - * cb(null, finished) - * }, function iter(next) { - * fetchPage(url, (err, body) => { - * if (err) return next(err) - * results = results.concat(body.objects) - * finished = !!body.next - * next(err) - * }) - * }, function done (err) { - * // all pages have been fetched - * }) - */ - function until(test, iteratee, callback) { - const _test = wrapAsync(test); - return whilst$1((cb) => _test((err, truth) => cb (err, !truth)), iteratee, callback); - } - - /** - * Runs the `tasks` array of functions in series, each passing their results to - * the next in the array. However, if any of the `tasks` pass an error to their - * own callback, the next function is not executed, and the main `callback` is - * immediately called with the error. - * - * @name waterfall - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} - * to run. - * Each function should complete with any number of `result` values. - * The `result` values will be passed as arguments, in order, to the next task. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed. This will be passed the results of the last task's - * callback. Invoked with (err, [results]). - * @returns {Promise} a promise, if a callback is omitted - * @example - * - * async.waterfall([ - * function(callback) { - * callback(null, 'one', 'two'); + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); * }, - * function(arg1, arg2, callback) { - * // arg1 now equals 'one' and arg2 now equals 'two' - * callback(null, 'three'); + * write_file: function(get_data, make_folder, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); * }, - * function(arg1, callback) { - * // arg1 now equals 'three' - * callback(null, 'done'); + * email_link: function(write_file, callback) { + * // once the file is written let's email a link to it... + * // write_file contains the filename returned by write_file. + * callback(null, {'file':write_file, 'email':'user@example.com'}); * } - * ], function (err, result) { - * // result now equals 'done' + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); * }); * - * // Or, with named functions: - * async.waterfall([ - * myFirstFunction, - * mySecondFunction, - * myLastFunction, - * ], function (err, result) { - * // result now equals 'done' + * // If you are using a JS minifier that mangles parameter names, `autoInject` + * // will not work with plain functions, since the parameter names will be + * // collapsed to a single letter identifier. To work around this, you can + * // explicitly specify the names of the parameters your task function needs + * // in an array, similar to Angular.js dependency injection. + * + * // This still has an advantage over plain `auto`, since the results a task + * // depends on are still spread into arguments. + * async.autoInject({ + * //... + * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(write_file, callback) { + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * }] + * //... + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); * }); - * function myFirstFunction(callback) { - * callback(null, 'one', 'two'); - * } - * function mySecondFunction(arg1, arg2, callback) { - * // arg1 now equals 'one' and arg2 now equals 'two' - * callback(null, 'three'); - * } - * function myLastFunction(arg1, callback) { - * // arg1 now equals 'three' - * callback(null, 'done'); - * } */ - function waterfall (tasks, callback) { - callback = once(callback); - if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); - if (!tasks.length) return callback(); - var taskIndex = 0; - - function nextTask(args) { - var task = wrapAsync(tasks[taskIndex++]); - task(...args, onlyOnce(next)); - } - - function next(err, ...args) { - if (err === false) return - if (err || taskIndex === tasks.length) { - return callback(err, ...args); - } - nextTask(args); - } + function autoInject(tasks, callback) { + var newTasks = {}; - nextTask([]); - } + Object.keys(tasks).forEach(key => { + var taskFn = tasks[key]; + var params; + var fnIsAsync = isAsync(taskFn); + var hasNoDeps = + (!fnIsAsync && taskFn.length === 1) || + (fnIsAsync && taskFn.length === 0); - var waterfall$1 = awaitify(waterfall); + if (Array.isArray(taskFn)) { + params = [...taskFn]; + taskFn = params.pop(); - /** - * An "async function" in the context of Async is an asynchronous function with - * a variable number of parameters, with the final parameter being a callback. - * (`function (arg1, arg2, ..., callback) {}`) - * The final callback is of the form `callback(err, results...)`, which must be - * called once the function is completed. The callback should be called with a - * Error as its first argument to signal that an error occurred. - * Otherwise, if no error occurred, it should be called with `null` as the first - * argument, and any additional `result` arguments that may apply, to signal - * successful completion. - * The callback must be called exactly once, ideally on a later tick of the - * JavaScript event loop. - * - * This type of function is also referred to as a "Node-style async function", - * or a "continuation passing-style function" (CPS). Most of the methods of this - * library are themselves CPS/Node-style async functions, or functions that - * return CPS/Node-style async functions. - * - * Wherever we accept a Node-style async function, we also directly accept an - * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. - * In this case, the `async` function will not be passed a final callback - * argument, and any thrown error will be used as the `err` argument of the - * implicit callback, and the return value will be used as the `result` value. - * (i.e. a `rejected` of the returned Promise becomes the `err` callback - * argument, and a `resolved` value becomes the `result`.) - * - * Note, due to JavaScript limitations, we can only detect native `async` - * functions and not transpilied implementations. - * Your environment must have `async`/`await` support for this to work. - * (e.g. Node > v7.6, or a recent version of a modern browser). - * If you are using `async` functions through a transpiler (e.g. Babel), you - * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, - * because the `async function` will be compiled to an ordinary function that - * returns a promise. - * - * @typedef {Function} AsyncFunction - * @static - */ + newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); + } else if (hasNoDeps) { + // no dependencies, use the function as-is + newTasks[key] = taskFn; + } else { + params = parseParams(taskFn); + if ((taskFn.length === 0 && !fnIsAsync) && params.length === 0) { + throw new Error("autoInject task functions require explicit parameters."); + } - var index = { - apply, - applyEach: applyEach$1, - applyEachSeries, - asyncify, - auto, - autoInject, - cargo, - cargoQueue: cargo$1, - compose, - concat: concat$1, - concatLimit: concatLimit$1, - concatSeries: concatSeries$1, - constant, - detect: detect$1, - detectLimit: detectLimit$1, - detectSeries: detectSeries$1, - dir, - doUntil, - doWhilst: doWhilst$1, - each, - eachLimit: eachLimit$2, - eachOf: eachOf$1, - eachOfLimit: eachOfLimit$2, - eachOfSeries: eachOfSeries$1, - eachSeries: eachSeries$1, - ensureAsync, - every: every$1, - everyLimit: everyLimit$1, - everySeries: everySeries$1, - filter: filter$1, - filterLimit: filterLimit$1, - filterSeries: filterSeries$1, - forever: forever$1, - groupBy, - groupByLimit: groupByLimit$1, - groupBySeries, - log, - map: map$1, - mapLimit: mapLimit$1, - mapSeries: mapSeries$1, - mapValues, - mapValuesLimit: mapValuesLimit$1, - mapValuesSeries, - memoize, - nextTick, - parallel: parallel$1, - parallelLimit, - priorityQueue, - queue: queue$1, - race: race$1, - reduce: reduce$1, - reduceRight, - reflect, - reflectAll, - reject: reject$2, - rejectLimit: rejectLimit$1, - rejectSeries: rejectSeries$1, - retry, - retryable, - seq, - series, - setImmediate: setImmediate$1, - some: some$1, - someLimit: someLimit$1, - someSeries: someSeries$1, - sortBy: sortBy$1, - timeout, - times, - timesLimit, - timesSeries, - transform, - tryEach: tryEach$1, - unmemoize, - until, - waterfall: waterfall$1, - whilst: whilst$1, + // remove callback param + if (!fnIsAsync) params.pop(); - // aliases - all: every$1, - allLimit: everyLimit$1, - allSeries: everySeries$1, - any: some$1, - anyLimit: someLimit$1, - anySeries: someSeries$1, - find: detect$1, - findLimit: detectLimit$1, - findSeries: detectSeries$1, - flatMap: concat$1, - flatMapLimit: concatLimit$1, - flatMapSeries: concatSeries$1, - forEach: each, - forEachSeries: eachSeries$1, - forEachLimit: eachLimit$2, - forEachOf: eachOf$1, - forEachOfSeries: eachOfSeries$1, - forEachOfLimit: eachOfLimit$2, - inject: reduce$1, - foldl: reduce$1, - foldr: reduceRight, - select: filter$1, - selectLimit: filterLimit$1, - selectSeries: filterSeries$1, - wrapSync: asyncify, - during: whilst$1, - doDuring: doWhilst$1 - }; + newTasks[key] = params.concat(newTask); + } - exports.default = index; - exports.apply = apply; - exports.applyEach = applyEach$1; - exports.applyEachSeries = applyEachSeries; - exports.asyncify = asyncify; - exports.auto = auto; - exports.autoInject = autoInject; - exports.cargo = cargo; - exports.cargoQueue = cargo$1; - exports.compose = compose; - exports.concat = concat$1; - exports.concatLimit = concatLimit$1; - exports.concatSeries = concatSeries$1; - exports.constant = constant; - exports.detect = detect$1; - exports.detectLimit = detectLimit$1; - exports.detectSeries = detectSeries$1; - exports.dir = dir; - exports.doUntil = doUntil; - exports.doWhilst = doWhilst$1; - exports.each = each; - exports.eachLimit = eachLimit$2; - exports.eachOf = eachOf$1; - exports.eachOfLimit = eachOfLimit$2; - exports.eachOfSeries = eachOfSeries$1; - exports.eachSeries = eachSeries$1; - exports.ensureAsync = ensureAsync; - exports.every = every$1; - exports.everyLimit = everyLimit$1; - exports.everySeries = everySeries$1; - exports.filter = filter$1; - exports.filterLimit = filterLimit$1; - exports.filterSeries = filterSeries$1; - exports.forever = forever$1; - exports.groupBy = groupBy; - exports.groupByLimit = groupByLimit$1; - exports.groupBySeries = groupBySeries; - exports.log = log; - exports.map = map$1; - exports.mapLimit = mapLimit$1; - exports.mapSeries = mapSeries$1; - exports.mapValues = mapValues; - exports.mapValuesLimit = mapValuesLimit$1; - exports.mapValuesSeries = mapValuesSeries; - exports.memoize = memoize; - exports.nextTick = nextTick; - exports.parallel = parallel$1; - exports.parallelLimit = parallelLimit; - exports.priorityQueue = priorityQueue; - exports.queue = queue$1; - exports.race = race$1; - exports.reduce = reduce$1; - exports.reduceRight = reduceRight; - exports.reflect = reflect; - exports.reflectAll = reflectAll; - exports.reject = reject$2; - exports.rejectLimit = rejectLimit$1; - exports.rejectSeries = rejectSeries$1; - exports.retry = retry; - exports.retryable = retryable; - exports.seq = seq; - exports.series = series; - exports.setImmediate = setImmediate$1; - exports.some = some$1; - exports.someLimit = someLimit$1; - exports.someSeries = someSeries$1; - exports.sortBy = sortBy$1; - exports.timeout = timeout; - exports.times = times; - exports.timesLimit = timesLimit; - exports.timesSeries = timesSeries; - exports.transform = transform; - exports.tryEach = tryEach$1; - exports.unmemoize = unmemoize; - exports.until = until; - exports.waterfall = waterfall$1; - exports.whilst = whilst$1; - exports.all = every$1; - exports.allLimit = everyLimit$1; - exports.allSeries = everySeries$1; - exports.any = some$1; - exports.anyLimit = someLimit$1; - exports.anySeries = someSeries$1; - exports.find = detect$1; - exports.findLimit = detectLimit$1; - exports.findSeries = detectSeries$1; - exports.flatMap = concat$1; - exports.flatMapLimit = concatLimit$1; - exports.flatMapSeries = concatSeries$1; - exports.forEach = each; - exports.forEachSeries = eachSeries$1; - exports.forEachLimit = eachLimit$2; - exports.forEachOf = eachOf$1; - exports.forEachOfSeries = eachOfSeries$1; - exports.forEachOfLimit = eachOfLimit$2; - exports.inject = reduce$1; - exports.foldl = reduce$1; - exports.foldr = reduceRight; - exports.select = filter$1; - exports.selectLimit = filterLimit$1; - exports.selectSeries = filterSeries$1; - exports.wrapSync = asyncify; - exports.during = whilst$1; - exports.doDuring = doWhilst$1; + function newTask(results, taskCb) { + var newArgs = params.map(name => results[name]); + newArgs.push(taskCb); + wrapAsync(taskFn)(...newArgs); + } + }); - Object.defineProperty(exports, '__esModule', { value: true }); + return auto(newTasks, callback); + } -}))); + // Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation + // used for queues. This implementation assumes that the node provided by the user can be modified + // to adjust the next and last properties. We implement only the minimal functionality + // for queue support. + class DLL { + constructor() { + this.head = this.tail = null; + this.length = 0; + } + removeLink(node) { + if (node.prev) node.prev.next = node.next; + else this.head = node.next; + if (node.next) node.next.prev = node.prev; + else this.tail = node.prev; -/***/ }), + node.prev = node.next = null; + this.length -= 1; + return node; + } -/***/ 32944: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + empty () { + while(this.head) this.shift(); + return this; + } -module.exports = -{ - parallel : __nccwpck_require__(79347), - serial : __nccwpck_require__(99784), - serialOrdered : __nccwpck_require__(98758) -}; + insertAfter(node, newNode) { + newNode.prev = node; + newNode.next = node.next; + if (node.next) node.next.prev = newNode; + else this.tail = newNode; + node.next = newNode; + this.length += 1; + } + insertBefore(node, newNode) { + newNode.prev = node.prev; + newNode.next = node; + if (node.prev) node.prev.next = newNode; + else this.head = newNode; + node.prev = newNode; + this.length += 1; + } -/***/ }), - -/***/ 56163: -/***/ ((module) => { - -// API -module.exports = abort; + unshift(node) { + if (this.head) this.insertBefore(this.head, node); + else setInitial(this, node); + } -/** - * Aborts leftover active jobs - * - * @param {object} state - current state object - */ -function abort(state) -{ - Object.keys(state.jobs).forEach(clean.bind(state)); + push(node) { + if (this.tail) this.insertAfter(this.tail, node); + else setInitial(this, node); + } - // reset leftover jobs - state.jobs = {}; -} + shift() { + return this.head && this.removeLink(this.head); + } -/** - * Cleans up leftover job by invoking abort function for the provided job id - * - * @this state - * @param {string|number} key - job id to abort - */ -function clean(key) -{ - if (typeof this.jobs[key] == 'function') - { - this.jobs[key](); - } -} + pop() { + return this.tail && this.removeLink(this.tail); + } + toArray() { + return [...this] + } -/***/ }), + *[Symbol.iterator] () { + var cur = this.head; + while (cur) { + yield cur.data; + cur = cur.next; + } + } -/***/ 61741: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + remove (testFn) { + var curr = this.head; + while(curr) { + var {next} = curr; + if (testFn(curr)) { + this.removeLink(curr); + } + curr = next; + } + return this; + } + } -var defer = __nccwpck_require__(91288); + function setInitial(dll, node) { + dll.length = 1; + dll.head = dll.tail = node; + } -// API -module.exports = async; + function queue$1(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } + else if(concurrency === 0) { + throw new RangeError('Concurrency must not be zero'); + } -/** - * Runs provided callback asynchronously - * even if callback itself is not - * - * @param {function} callback - callback to invoke - * @returns {function} - augmented callback - */ -function async(callback) -{ - var isAsync = false; + var _worker = wrapAsync(worker); + var numRunning = 0; + var workersList = []; + const events = { + error: [], + drain: [], + saturated: [], + unsaturated: [], + empty: [] + }; - // check if async happened - defer(function() { isAsync = true; }); + function on (event, handler) { + events[event].push(handler); + } - return function async_callback(err, result) - { - if (isAsync) - { - callback(err, result); - } - else - { - defer(function nextTick_callback() - { - callback(err, result); - }); - } - }; -} + function once (event, handler) { + const handleAndRemove = (...args) => { + off(event, handleAndRemove); + handler(...args); + }; + events[event].push(handleAndRemove); + } + function off (event, handler) { + if (!event) return Object.keys(events).forEach(ev => events[ev] = []) + if (!handler) return events[event] = [] + events[event] = events[event].filter(ev => ev !== handler); + } -/***/ }), + function trigger (event, ...args) { + events[event].forEach(handler => handler(...args)); + } -/***/ 91288: -/***/ ((module) => { + var processingScheduled = false; + function _insert(data, insertAtFront, rejectOnError, callback) { + if (callback != null && typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; -module.exports = defer; + var res, rej; + function promiseCallback (err, ...args) { + // we don't care about the error, let the global error handler + // deal with it + if (err) return rejectOnError ? rej(err) : res() + if (args.length <= 1) return res(args[0]) + res(args); + } -/** - * Runs provided function on next iteration of the event loop - * - * @param {function} fn - function to run - */ -function defer(fn) -{ - var nextTick = typeof setImmediate == 'function' - ? setImmediate - : ( - typeof process == 'object' && typeof process.nextTick == 'function' - ? process.nextTick - : null - ); + var item = q._createTaskItem( + data, + rejectOnError ? promiseCallback : + (callback || promiseCallback) + ); - if (nextTick) - { - nextTick(fn); - } - else - { - setTimeout(fn, 0); - } -} + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + if (!processingScheduled) { + processingScheduled = true; + setImmediate$1(() => { + processingScheduled = false; + q.process(); + }); + } -/***/ }), + if (rejectOnError || !callback) { + return new Promise((resolve, reject) => { + res = resolve; + rej = reject; + }) + } + } -/***/ 20966: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + function _createCB(tasks) { + return function (err, ...args) { + numRunning -= 1; -var async = __nccwpck_require__(61741) - , abort = __nccwpck_require__(56163) - ; + for (var i = 0, l = tasks.length; i < l; i++) { + var task = tasks[i]; -// API -module.exports = iterate; + var index = workersList.indexOf(task); + if (index === 0) { + workersList.shift(); + } else if (index > 0) { + workersList.splice(index, 1); + } -/** - * Iterates over each job object - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {object} state - current job status - * @param {function} callback - invoked when all elements processed - */ -function iterate(list, iterator, state, callback) -{ - // store current index - var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; + task.callback(err, ...args); - state.jobs[key] = runJob(iterator, key, list[key], function(error, output) - { - // don't repeat yourself - // skip secondary callbacks - if (!(key in state.jobs)) - { - return; - } + if (err != null) { + trigger('error', err, task.data); + } + } - // clean up jobs - delete state.jobs[key]; + if (numRunning <= (q.concurrency - q.buffer) ) { + trigger('unsaturated'); + } - if (error) - { - // don't process rest of the results - // stop still active jobs - // and reset the list - abort(state); - } - else - { - state.results[key] = output; - } + if (q.idle()) { + trigger('drain'); + } + q.process(); + }; + } - // return salvaged results - callback(error, state.results); - }); -} + function _maybeDrain(data) { + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + setImmediate$1(() => trigger('drain')); + return true + } + return false + } -/** - * Runs iterator over provided job element - * - * @param {function} iterator - iterator to invoke - * @param {string|number} key - key/index of the element in the list of jobs - * @param {mixed} item - job description - * @param {function} callback - invoked after iterator is done with the job - * @returns {function|mixed} - job abort function or something else - */ -function runJob(iterator, key, item, callback) -{ - var aborter; + const eventMethod = (name) => (handler) => { + if (!handler) { + return new Promise((resolve, reject) => { + once(name, (err, data) => { + if (err) return reject(err) + resolve(data); + }); + }) + } + off(name); + on(name, handler); - // allow shortcut if iterator expects only two arguments - if (iterator.length == 2) - { - aborter = iterator(item, async(callback)); - } - // otherwise go with full three arguments - else - { - aborter = iterator(item, key, async(callback)); - } + }; - return aborter; -} + var isProcessing = false; + var q = { + _tasks: new DLL(), + _createTaskItem (data, callback) { + return { + data, + callback + }; + }, + *[Symbol.iterator] () { + yield* q._tasks[Symbol.iterator](); + }, + concurrency, + payload, + buffer: concurrency / 4, + started: false, + paused: false, + push (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, false, callback)) + } + return _insert(data, false, false, callback); + }, + pushAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, true, callback)) + } + return _insert(data, false, true, callback); + }, + kill () { + off(); + q._tasks.empty(); + }, + unshift (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, false, callback)) + } + return _insert(data, true, false, callback); + }, + unshiftAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, true, callback)) + } + return _insert(data, true, true, callback); + }, + remove (testFn) { + q._tasks.remove(testFn); + }, + process () { + // Avoid trying to start too many processing operations. This can occur + // when callbacks resolve synchronously (#1267). + if (isProcessing) { + return; + } + isProcessing = true; + while(!q.paused && numRunning < q.concurrency && q._tasks.length){ + var tasks = [], data = []; + var l = q._tasks.length; + if (q.payload) l = Math.min(l, q.payload); + for (var i = 0; i < l; i++) { + var node = q._tasks.shift(); + tasks.push(node); + workersList.push(node); + data.push(node.data); + } + numRunning += 1; -/***/ }), + if (q._tasks.length === 0) { + trigger('empty'); + } -/***/ 24725: -/***/ ((module) => { + if (numRunning === q.concurrency) { + trigger('saturated'); + } -// API -module.exports = state; + var cb = onlyOnce(_createCB(tasks)); + _worker(data, cb); + } + isProcessing = false; + }, + length () { + return q._tasks.length; + }, + running () { + return numRunning; + }, + workersList () { + return workersList; + }, + idle() { + return q._tasks.length + numRunning === 0; + }, + pause () { + q.paused = true; + }, + resume () { + if (q.paused === false) { return; } + q.paused = false; + setImmediate$1(q.process); + } + }; + // define these as fixed properties, so people get useful errors when updating + Object.defineProperties(q, { + saturated: { + writable: false, + value: eventMethod('saturated') + }, + unsaturated: { + writable: false, + value: eventMethod('unsaturated') + }, + empty: { + writable: false, + value: eventMethod('empty') + }, + drain: { + writable: false, + value: eventMethod('drain') + }, + error: { + writable: false, + value: eventMethod('error') + }, + }); + return q; + } -/** - * Creates initial state object - * for iteration over list - * - * @param {array|object} list - list to iterate over - * @param {function|null} sortMethod - function to use for keys sort, - * or `null` to keep them as is - * @returns {object} - initial state object - */ -function state(list, sortMethod) -{ - var isNamedList = !Array.isArray(list) - , initState = - { - index : 0, - keyedList: isNamedList || sortMethod ? Object.keys(list) : null, - jobs : {}, - results : isNamedList ? {} : [], - size : isNamedList ? Object.keys(list).length : list.length + /** + * Creates a `cargo` object with the specified payload. Tasks added to the + * cargo will be processed altogether (up to the `payload` limit). If the + * `worker` is in progress, the task is queued until it becomes available. Once + * the `worker` has completed some tasks, each callback of those tasks is + * called. Check out [these](https://github.com/camo/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://github.com/camo/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) + * for how `cargo` and `queue` work. + * + * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers + * at a time, cargo passes an array of tasks to a single worker, repeating + * when the worker is finished. + * + * @name cargo + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An asynchronous function for processing an array + * of queued tasks. Invoked with `(tasks, callback)`. + * @param {number} [payload=Infinity] - An optional `integer` for determining + * how many tasks should be processed per round; if omitted, the default is + * unlimited. + * @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the cargo and inner queue. + * @example + * + * // create a cargo object with payload 2 + * var cargo = async.cargo(function(tasks, callback) { + * for (var i=0; i { - -var abort = __nccwpck_require__(56163) - , async = __nccwpck_require__(61741) - ; - -// API -module.exports = terminator; - -/** - * Terminates jobs in the attached state context - * - * @this AsyncKitState# - * @param {function} callback - final callback to invoke after termination - */ -function terminator(callback) -{ - if (!Object.keys(this.jobs).length) - { - return; - } - - // fast forward iteration index - this.index = this.size; - - // abort jobs - abort(this); - - // send back results we have so far - async(callback)(null, this.results); -} - - -/***/ }), - -/***/ 79347: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var iterate = __nccwpck_require__(20966) - , initState = __nccwpck_require__(24725) - , terminator = __nccwpck_require__(82067) - ; - -// Public API -module.exports = parallel; - -/** - * Runs iterator over provided array elements in parallel - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {function} callback - invoked when all elements processed - * @returns {function} - jobs terminator - */ -function parallel(list, iterator, callback) -{ - var state = initState(list); - - while (state.index < (state['keyedList'] || list).length) - { - iterate(list, iterator, state, function(error, result) - { - if (error) - { - callback(error, result); - return; - } - - // looks like it's the last one - if (Object.keys(state.jobs).length === 0) - { - callback(null, state.results); - return; - } - }); - - state.index++; - } - - return terminator.bind(state, callback); -} - - -/***/ }), - -/***/ 99784: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var serialOrdered = __nccwpck_require__(98758); - -// Public API -module.exports = serial; - -/** - * Runs iterator over provided array elements in series - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {function} callback - invoked when all elements processed - * @returns {function} - jobs terminator - */ -function serial(list, iterator, callback) -{ - return serialOrdered(list, iterator, null, callback); -} - - -/***/ }), + /** + * Creates a `cargoQueue` object with the specified payload. Tasks added to the + * cargoQueue will be processed together (up to the `payload` limit) in `concurrency` parallel workers. + * If the all `workers` are in progress, the task is queued until one becomes available. Once + * a `worker` has completed some tasks, each callback of those tasks is + * called. Check out [these](https://github.com/camo/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://github.com/camo/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) + * for how `cargo` and `queue` work. + * + * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers + * at a time, and [`cargo`]{@link module:ControlFlow.cargo} passes an array of tasks to a single worker, + * the cargoQueue passes an array of tasks to multiple parallel workers. + * + * @name cargoQueue + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @see [async.cargo]{@link module:ControlFLow.cargo} + * @category Control Flow + * @param {AsyncFunction} worker - An asynchronous function for processing an array + * of queued tasks. Invoked with `(tasks, callback)`. + * @param {number} [concurrency=1] - An `integer` for determining how many + * `worker` functions should be run in parallel. If omitted, the concurrency + * defaults to `1`. If the concurrency is `0`, an error is thrown. + * @param {number} [payload=Infinity] - An optional `integer` for determining + * how many tasks should be processed per round; if omitted, the default is + * unlimited. + * @returns {module:ControlFlow.QueueObject} A cargoQueue object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the cargoQueue and inner queue. + * @example + * + * // create a cargoQueue object with payload 2 and concurrency 2 + * var cargoQueue = async.cargoQueue(function(tasks, callback) { + * for (var i=0; i { + /** + * Reduces `coll` into a single value using an async `iteratee` to return each + * successive step. `memo` is the initial state of the reduction. This function + * only operates in series. + * + * For performance reasons, it may make sense to split a call to this function + * into a parallel map, and then use the normal `Array.prototype.reduce` on the + * results. This function is for situations where each step in the reduction + * needs to be async; if you can get the data before reducing it, then it's + * probably a good idea to do so. + * + * @name reduce + * @static + * @memberOf module:Collections + * @method + * @alias inject + * @alias foldl + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee completes with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file3.txt', 'file4.txt']; + * + * // asynchronous function that computes the file size in bytes + * // file size is added to the memoized value, then returned + * function getFileSizeInBytes(memo, file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, memo + stat.size); + * }); + * } + * + * // Using callbacks + * async.reduce(fileList, 0, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * } else { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(result); + * } + * }); + * + * // Using Promises + * async.reduce(fileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.reduce(fileList, 0, getFileSizeInBytes); + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ + function reduce(coll, memo, iteratee, callback) { + callback = once(callback); + var _iteratee = wrapAsync(iteratee); + return eachOfSeries$1(coll, (x, i, iterCb) => { + _iteratee(memo, x, (err, v) => { + memo = v; + iterCb(err); + }); + }, err => callback(err, memo)); + } + var reduce$1 = awaitify(reduce, 4); -var iterate = __nccwpck_require__(20966) - , initState = __nccwpck_require__(24725) - , terminator = __nccwpck_require__(82067) - ; + /** + * Version of the compose function that is more natural to read. Each function + * consumes the return value of the previous function. It is the equivalent of + * [compose]{@link module:ControlFlow.compose} with the arguments reversed. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name seq + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.compose]{@link module:ControlFlow.compose} + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} a function that composes the `functions` in order + * @example + * + * // Requires lodash (or underscore), express3 and dresende's orm2. + * // Part of an app, that fetches cats of the logged user. + * // This example uses `seq` function to avoid overnesting and error + * // handling clutter. + * app.get('/cats', function(request, response) { + * var User = request.models.User; + * async.seq( + * User.get.bind(User), // 'User.get' has signature (id, callback(err, data)) + * function(user, fn) { + * user.getCats(fn); // 'getCats' has signature (callback(err, data)) + * } + * )(req.session.user_id, function (err, cats) { + * if (err) { + * console.error(err); + * response.json({ status: 'error', message: err.message }); + * } else { + * response.json({ status: 'ok', message: 'Cats found', data: cats }); + * } + * }); + * }); + */ + function seq(...functions) { + var _functions = functions.map(wrapAsync); + return function (...args) { + var that = this; -// Public API -module.exports = serialOrdered; -// sorting helpers -module.exports.ascending = ascending; -module.exports.descending = descending; + var cb = args[args.length - 1]; + if (typeof cb == 'function') { + args.pop(); + } else { + cb = promiseCallback(); + } -/** - * Runs iterator over provided sorted array elements in series - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {function} sortMethod - custom sort function - * @param {function} callback - invoked when all elements processed - * @returns {function} - jobs terminator - */ -function serialOrdered(list, iterator, sortMethod, callback) -{ - var state = initState(list, sortMethod); + reduce$1(_functions, args, (newargs, fn, iterCb) => { + fn.apply(that, newargs.concat((err, ...nextargs) => { + iterCb(err, nextargs); + })); + }, + (err, results) => cb(err, ...results)); - iterate(list, iterator, state, function iteratorHandler(error, result) - { - if (error) - { - callback(error, result); - return; + return cb[PROMISE_SYMBOL] + }; } - state.index++; - - // are we there yet? - if (state.index < (state['keyedList'] || list).length) - { - iterate(list, iterator, state, iteratorHandler); - return; + /** + * Creates a function which is a composition of the passed asynchronous + * functions. Each function consumes the return value of the function that + * follows. Composing functions `f()`, `g()`, and `h()` would produce the result + * of `f(g(h()))`, only this version uses callbacks to obtain the return values. + * + * If the last argument to the composed function is not a function, a promise + * is returned when you call it. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name compose + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} an asynchronous function that is the composed + * asynchronous `functions` + * @example + * + * function add1(n, callback) { + * setTimeout(function () { + * callback(null, n + 1); + * }, 10); + * } + * + * function mul3(n, callback) { + * setTimeout(function () { + * callback(null, n * 3); + * }, 10); + * } + * + * var add1mul3 = async.compose(mul3, add1); + * add1mul3(4, function (err, result) { + * // result now equals 15 + * }); + */ + function compose(...args) { + return seq(...args.reverse()); } - // done here - callback(null, state.results); - }); - - return terminator.bind(state, callback); -} + /** + * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. + * + * @name mapLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function mapLimit (coll, limit, iteratee, callback) { + return _asyncMap(eachOfLimit$2(limit), coll, iteratee, callback) + } + var mapLimit$1 = awaitify(mapLimit, 4); -/* - * -- Sort methods - */ + /** + * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. + * + * @name concatLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapLimit + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ + function concatLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, ...args) => { + if (err) return iterCb(err); + return iterCb(err, args); + }); + }, (err, mapResults) => { + var result = []; + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + result = result.concat(...mapResults[i]); + } + } -/** - * sort helper to sort array elements in ascending order - * - * @param {mixed} a - an item to compare - * @param {mixed} b - an item to compare - * @returns {number} - comparison result - */ -function ascending(a, b) -{ - return a < b ? -1 : a > b ? 1 : 0; -} + return callback(err, result); + }); + } + var concatLimit$1 = awaitify(concatLimit, 4); -/** - * sort helper to sort array elements in descending order - * - * @param {mixed} a - an item to compare - * @param {mixed} b - an item to compare - * @returns {number} - comparison result - */ -function descending(a, b) -{ - return -1 * ascending(a, b); -} - - -/***/ }), - -/***/ 89948: -/***/ ((module) => { + /** + * Applies `iteratee` to each item in `coll`, concatenating the results. Returns + * the concatenated list. The `iteratee`s are called in parallel, and the + * results are concatenated as they return. The results array will be returned in + * the original order of `coll` passed to the `iteratee` function. + * + * @name concat + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @alias flatMap + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * let directoryList = ['dir1','dir2','dir3']; + * let withMissingDirectoryList = ['dir1','dir2','dir3', 'dir4']; + * + * // Using callbacks + * async.concat(directoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } else { + * console.log(results); + * } + * }); + * + * // Using Promises + * async.concat(directoryList, fs.readdir) + * .then(results => { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir) + * .then(results => { + * console.log(results); + * }).catch(err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.concat(directoryList, fs.readdir); + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let results = await async.concat(withMissingDirectoryList, fs.readdir); + * console.log(results); + * } catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } + * } + * + */ + function concat(coll, iteratee, callback) { + return concatLimit$1(coll, Infinity, iteratee, callback) + } + var concat$1 = awaitify(concat, 3); -"use strict"; + /** + * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. + * + * @name concatSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapSeries + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. + * The iteratee should complete with an array an array of results. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ + function concatSeries(coll, iteratee, callback) { + return concatLimit$1(coll, 1, iteratee, callback) + } + var concatSeries$1 = awaitify(concatSeries, 3); -module.exports = balanced; -function balanced(a, b, str) { - if (a instanceof RegExp) a = maybeMatch(a, str); - if (b instanceof RegExp) b = maybeMatch(b, str); + /** + * Returns a function that when called, calls-back with the values provided. + * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to + * [`auto`]{@link module:ControlFlow.auto}. + * + * @name constant + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {...*} arguments... - Any number of arguments to automatically invoke + * callback with. + * @returns {AsyncFunction} Returns a function that when invoked, automatically + * invokes the callback with the previous given arguments. + * @example + * + * async.waterfall([ + * async.constant(42), + * function (value, next) { + * // value === 42 + * }, + * //... + * ], callback); + * + * async.waterfall([ + * async.constant(filename, "utf8"), + * fs.readFile, + * function (fileData, next) { + * //... + * } + * //... + * ], callback); + * + * async.auto({ + * hostname: async.constant("https://server.net/"), + * port: findFreePort, + * launchServer: ["hostname", "port", function (options, cb) { + * startServer(options, cb); + * }], + * //... + * }, callback); + */ + function constant$1(...args) { + return function (...ignoredArgs/*, callback*/) { + var callback = ignoredArgs.pop(); + return callback(null, ...args); + }; + } - var r = range(a, b, str); + function _createTester(check, getResult) { + return (eachfn, arr, _iteratee, cb) => { + var testPassed = false; + var testResult; + const iteratee = wrapAsync(_iteratee); + eachfn(arr, (value, _, callback) => { + iteratee(value, (err, result) => { + if (err || err === false) return callback(err); - return r && { - start: r[0], - end: r[1], - pre: str.slice(0, r[0]), - body: str.slice(r[0] + a.length, r[1]), - post: str.slice(r[1] + b.length) - }; -} + if (check(result) && !testResult) { + testPassed = true; + testResult = getResult(true, value); + return callback(null, breakLoop$1); + } + callback(); + }); + }, err => { + if (err) return cb(err); + cb(null, testPassed ? testResult : getResult(false)); + }); + }; + } -function maybeMatch(reg, str) { - var m = str.match(reg); - return m ? m[0] : null; -} + /** + * Returns the first value in `coll` that passes an async truth test. The + * `iteratee` is applied in parallel, meaning the first iteratee to return + * `true` will fire the detect `callback` with that result. That means the + * result might not be the first item in the original `coll` (in terms of order) + * that passes the test. -balanced.range = range; -function range(a, b, str) { - var begs, beg, left, right, result; - var ai = str.indexOf(a); - var bi = str.indexOf(b, ai + 1); - var i = ai; + * If order within the original `coll` is important, then look at + * [`detectSeries`]{@link module:Collections.detectSeries}. + * + * @name detect + * @static + * @memberOf module:Collections + * @method + * @alias find + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * } + *); + * + * // Using Promises + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists) + * .then(result => { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists); + * console.log(result); + * // dir1/file1.txt + * // result now equals the file in the list that exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function detect(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOf$1, coll, iteratee, callback) + } + var detect$1 = awaitify(detect, 3); - if (ai >= 0 && bi > 0) { - if(a===b) { - return [ai, bi]; + /** + * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a + * time. + * + * @name detectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findLimit + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ + function detectLimit(coll, limit, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit$2(limit), coll, iteratee, callback) } - begs = []; - left = str.length; + var detectLimit$1 = awaitify(detectLimit, 4); - while (i >= 0 && !result) { - if (i == ai) { - begs.push(i); - ai = str.indexOf(a, i + 1); - } else if (begs.length == 1) { - result = [ begs.pop(), bi ]; - } else { - beg = begs.pop(); - if (beg < left) { - left = beg; - right = bi; - } + /** + * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. + * + * @name detectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findSeries + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ + function detectSeries(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit$2(1), coll, iteratee, callback) + } - bi = str.indexOf(b, i + 1); - } + var detectSeries$1 = awaitify(detectSeries, 3); - i = ai < bi && ai >= 0 ? ai : bi; + function consoleFunc(name) { + return (fn, ...args) => wrapAsync(fn)(...args, (err, ...resultArgs) => { + /* istanbul ignore else */ + if (typeof console === 'object') { + /* istanbul ignore else */ + if (err) { + /* istanbul ignore else */ + if (console.error) { + console.error(err); + } + } else if (console[name]) { /* istanbul ignore else */ + resultArgs.forEach(x => console[name](x)); + } + } + }) } - if (begs.length) { - result = [ left, right ]; - } - } + /** + * Logs the result of an [`async` function]{@link AsyncFunction} to the + * `console` using `console.dir` to display the properties of the resulting object. + * Only works in Node.js or in browsers that support `console.dir` and + * `console.error` (such as FF and Chrome). + * If multiple arguments are returned from the async function, + * `console.dir` is called on each argument in order. + * + * @name dir + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, {hello: name}); + * }, 1000); + * }; + * + * // in the node repl + * node> async.dir(hello, 'world'); + * {hello: 'world'} + */ + var dir = consoleFunc('dir'); - return result; -} + /** + * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in + * the order of operations, the arguments `test` and `iteratee` are switched. + * + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + * + * @name doWhilst + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - A function which is called each time `test` + * passes. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. + * `callback` will be passed an error and any arguments passed to the final + * `iteratee`'s callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ + function doWhilst(iteratee, test, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results; + function next(err, ...args) { + if (err) return callback(err); + if (err === false) return; + results = args; + _test(...args, check); + } -/***/ }), + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } -/***/ 18079: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return check(null, true); + } -var register = __nccwpck_require__(39367); -var addHook = __nccwpck_require__(55711); -var removeHook = __nccwpck_require__(90037); + var doWhilst$1 = awaitify(doWhilst, 3); -// bind with array of arguments: https://stackoverflow.com/a/21792913 -var bind = Function.bind; -var bindable = bind.bind(bind); + /** + * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the + * argument ordering differs from `until`. + * + * @name doUntil + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee` + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ + function doUntil(iteratee, test, callback) { + const _test = wrapAsync(test); + return doWhilst$1(iteratee, (...args) => { + const cb = args.pop(); + _test(...args, (err, truth) => cb (err, !truth)); + }, callback); + } -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 _withoutIndex(iteratee) { + return (value, index, callback) => iteratee(value, callback); + } -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; - - -/***/ }), - -/***/ 55711: -/***/ ((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, - }); -} - - -/***/ }), - -/***/ 39367: -/***/ ((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)(); - }); -} - - -/***/ }), - -/***/ 90037: -/***/ ((module) => { - -module.exports = removeHook; - -function removeHook(state, name, method) { - if (!state.registry[name]) { - return; - } - - var index = state.registry[name] - .map(function (registered) { - return registered.orig; - }) - .indexOf(method); - - if (index === -1) { - return; - } - - state.registry[name].splice(index, 1); -} - - -/***/ }), - -/***/ 34312: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* module decorator */ module = __nccwpck_require__.nmd(module); -var bigInt = (function (undefined) { - "use strict"; - - var BASE = 1e7, - LOG_BASE = 7, - MAX_INT = 9007199254740992, - MAX_INT_ARR = smallToArray(MAX_INT), - DEFAULT_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz"; - - var supportsNativeBigInt = typeof BigInt === "function"; - - function Integer(v, radix, alphabet, caseSensitive) { - if (typeof v === "undefined") return Integer[0]; - if (typeof radix !== "undefined") return +radix === 10 && !alphabet ? parseValue(v) : parseBase(v, radix, alphabet, caseSensitive); - return parseValue(v); + /** + * Applies the function `iteratee` to each item in `coll`, in parallel. + * The `iteratee` is called with an item from the list, and a callback for when + * it has finished. If the `iteratee` passes an error to its `callback`, the + * main `callback` (for the `each` function) is immediately called with the + * error. + * + * Note, that since this function applies `iteratee` to each item in parallel, + * there is no guarantee that the iteratee functions will complete in order. + * + * @name each + * @static + * @memberOf module:Collections + * @method + * @alias forEach + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to + * each item in `coll`. Invoked with (item, callback). + * The array index is not passed to the iteratee. + * If you need the index, use `eachOf`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt']; + * const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt']; + * + * // asynchronous function that deletes a file + * const deleteFile = function(file, callback) { + * fs.unlink(file, callback); + * }; + * + * // Using callbacks + * async.each(fileList, deleteFile, function(err) { + * if( err ) { + * console.log(err); + * } else { + * console.log('All files have been deleted successfully'); + * } + * }); + * + * // Error Handling + * async.each(withMissingFileList, deleteFile, function(err){ + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using Promises + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using async/await + * async () => { + * try { + * await async.each(files, deleteFile); + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * await async.each(withMissingFileList, deleteFile); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * } + * } + * + */ + function eachLimit$2(coll, iteratee, callback) { + return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback); } - function BigInteger(value, sign) { - this.value = value; - this.sign = sign; - this.isSmall = false; - } - BigInteger.prototype = Object.create(Integer.prototype); + var each = awaitify(eachLimit$2, 3); - function SmallInteger(value) { - this.value = value; - this.sign = value < 0; - this.isSmall = true; + /** + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachLimit(coll, limit, iteratee, callback) { + return eachOfLimit$2(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); } - SmallInteger.prototype = Object.create(Integer.prototype); + var eachLimit$1 = awaitify(eachLimit, 4); - function NativeBigInt(value) { - this.value = value; - } - NativeBigInt.prototype = Object.create(Integer.prototype); + /** + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. + * + * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item + * in series and therefore the iteratee functions will complete in order. - function isPrecise(n) { - return -MAX_INT < n && n < MAX_INT; + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachSeries(coll, iteratee, callback) { + return eachLimit$1(coll, 1, iteratee, callback) } + var eachSeries$1 = awaitify(eachSeries, 3); - function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes - if (n < 1e7) - return [n]; - if (n < 1e14) - return [n % 1e7, Math.floor(n / 1e7)]; - return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)]; + /** + * Wrap an async function and ensure it calls its callback on a later tick of + * the event loop. If the function already calls its callback on a next tick, + * no extra deferral is added. This is useful for preventing stack overflows + * (`RangeError: Maximum call stack size exceeded`) and generally keeping + * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) + * contained. ES2017 `async` functions are returned as-is -- they are immune + * to Zalgo's corrupting influences, as they always resolve on a later tick. + * + * @name ensureAsync + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - an async function, one that expects a node-style + * callback as its last argument. + * @returns {AsyncFunction} Returns a wrapped function with the exact same call + * signature as the function passed in. + * @example + * + * function sometimesAsync(arg, callback) { + * if (cache[arg]) { + * return callback(null, cache[arg]); // this would be synchronous!! + * } else { + * doSomeIO(arg, callback); // this IO would be asynchronous + * } + * } + * + * // this has a risk of stack overflows if many results are cached in a row + * async.mapSeries(args, sometimesAsync, done); + * + * // this will defer sometimesAsync's callback if necessary, + * // preventing stack overflows + * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); + */ + function ensureAsync(fn) { + if (isAsync(fn)) return fn; + return function (...args/*, callback*/) { + var callback = args.pop(); + var sync = true; + args.push((...innerArgs) => { + if (sync) { + setImmediate$1(() => callback(...innerArgs)); + } else { + callback(...innerArgs); + } + }); + fn.apply(this, args); + sync = false; + }; } - function arrayToSmall(arr) { // If BASE changes this function may need to change - trim(arr); - var length = arr.length; - if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) { - switch (length) { - case 0: return 0; - case 1: return arr[0]; - case 2: return arr[0] + arr[1] * BASE; - default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE; - } - } - return arr; + /** + * Returns `true` if every element in `coll` satisfies an async test. If any + * iteratee call returns `false`, the main `callback` is immediately called. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.every(fileList, fileExists, function(err, result) { + * console.log(result); + * // true + * // result is true since every file exists + * }); + * + * async.every(withMissingFileList, fileExists, function(err, result) { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }); + * + * // Using Promises + * async.every(fileList, fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.every(withMissingFileList, fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.every(fileList, fileExists); + * console.log(result); + * // true + * // result is true since every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.every(withMissingFileList, fileExists); + * console.log(result); + * // false + * // result is false since NOT every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function every(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOf$1, coll, iteratee, callback) } + var every$1 = awaitify(every, 3); - function trim(v) { - var i = v.length; - while (v[--i] === 0); - v.length = i + 1; + /** + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function everyLimit(coll, limit, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfLimit$2(limit), coll, iteratee, callback) } + var everyLimit$1 = awaitify(everyLimit, 4); - function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger - var x = new Array(length); - var i = -1; - while (++i < length) { - x[i] = 0; - } - return x; + /** + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function everySeries(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfSeries$1, coll, iteratee, callback) } + var everySeries$1 = awaitify(everySeries, 3); - function truncate(n) { - if (n > 0) return Math.floor(n); - return Math.ceil(n); + function filterArray(eachfn, arr, iteratee, callback) { + var truthValues = new Array(arr.length); + eachfn(arr, (x, index, iterCb) => { + iteratee(x, (err, v) => { + truthValues[index] = !!v; + iterCb(err); + }); + }, err => { + if (err) return callback(err); + var results = []; + for (var i = 0; i < arr.length; i++) { + if (truthValues[i]) results.push(arr[i]); + } + callback(null, results); + }); } - function add(a, b) { // assumes a and b are arrays with a.length >= b.length - var l_a = a.length, - l_b = b.length, - r = new Array(l_a), - carry = 0, - base = BASE, - sum, i; - for (i = 0; i < l_b; i++) { - sum = a[i] + b[i] + carry; - carry = sum >= base ? 1 : 0; - r[i] = sum - carry * base; - } - while (i < l_a) { - sum = a[i] + carry; - carry = sum === base ? 1 : 0; - r[i++] = sum - carry * base; - } - if (carry > 0) r.push(carry); - return r; - } - - function addAny(a, b) { - if (a.length >= b.length) return add(a, b); - return add(b, a); - } - - function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT - var l = a.length, - r = new Array(l), - base = BASE, - sum, i; - for (i = 0; i < l; i++) { - sum = a[i] - base + carry; - carry = Math.floor(sum / base); - r[i] = sum - carry * base; - carry += 1; - } - while (carry > 0) { - r[i++] = carry % base; - carry = Math.floor(carry / base); - } - return r; - } - - BigInteger.prototype.add = function (v) { - var n = parseValue(v); - if (this.sign !== n.sign) { - return this.subtract(n.negate()); - } - var a = this.value, b = n.value; - if (n.isSmall) { - return new BigInteger(addSmall(a, Math.abs(b)), this.sign); - } - return new BigInteger(addAny(a, b), this.sign); - }; - BigInteger.prototype.plus = BigInteger.prototype.add; - - SmallInteger.prototype.add = function (v) { - var n = parseValue(v); - var a = this.value; - if (a < 0 !== n.sign) { - return this.subtract(n.negate()); - } - var b = n.value; - if (n.isSmall) { - if (isPrecise(a + b)) return new SmallInteger(a + b); - b = smallToArray(Math.abs(b)); - } - return new BigInteger(addSmall(b, Math.abs(a)), a < 0); - }; - SmallInteger.prototype.plus = SmallInteger.prototype.add; - - NativeBigInt.prototype.add = function (v) { - return new NativeBigInt(this.value + parseValue(v).value); - } - NativeBigInt.prototype.plus = NativeBigInt.prototype.add; - - function subtract(a, b) { // assumes a and b are arrays with a >= b - var a_l = a.length, - b_l = b.length, - r = new Array(a_l), - borrow = 0, - base = BASE, - i, difference; - for (i = 0; i < b_l; i++) { - difference = a[i] - borrow - b[i]; - if (difference < 0) { - difference += base; - borrow = 1; - } else borrow = 0; - r[i] = difference; - } - for (i = b_l; i < a_l; i++) { - difference = a[i] - borrow; - if (difference < 0) difference += base; - else { - r[i++] = difference; - break; - } - r[i] = difference; - } - for (; i < a_l; i++) { - r[i] = a[i]; - } - trim(r); - return r; - } - - function subtractAny(a, b, sign) { - var value; - if (compareAbs(a, b) >= 0) { - value = subtract(a, b); - } else { - value = subtract(b, a); - sign = !sign; - } - value = arrayToSmall(value); - if (typeof value === "number") { - if (sign) value = -value; - return new SmallInteger(value); - } - return new BigInteger(value, sign); - } - - function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT - var l = a.length, - r = new Array(l), - carry = -b, - base = BASE, - i, difference; - for (i = 0; i < l; i++) { - difference = a[i] + carry; - carry = Math.floor(difference / base); - difference %= base; - r[i] = difference < 0 ? difference + base : difference; - } - r = arrayToSmall(r); - if (typeof r === "number") { - if (sign) r = -r; - return new SmallInteger(r); - } return new BigInteger(r, sign); - } - - BigInteger.prototype.subtract = function (v) { - var n = parseValue(v); - if (this.sign !== n.sign) { - return this.add(n.negate()); - } - var a = this.value, b = n.value; - if (n.isSmall) - return subtractSmall(a, Math.abs(b), this.sign); - return subtractAny(a, b, this.sign); - }; - BigInteger.prototype.minus = BigInteger.prototype.subtract; - - SmallInteger.prototype.subtract = function (v) { - var n = parseValue(v); - var a = this.value; - if (a < 0 !== n.sign) { - return this.add(n.negate()); - } - var b = n.value; - if (n.isSmall) { - return new SmallInteger(a - b); - } - return subtractSmall(b, Math.abs(a), a >= 0); - }; - SmallInteger.prototype.minus = SmallInteger.prototype.subtract; - - NativeBigInt.prototype.subtract = function (v) { - return new NativeBigInt(this.value - parseValue(v).value); - } - NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract; - - BigInteger.prototype.negate = function () { - return new BigInteger(this.value, !this.sign); - }; - SmallInteger.prototype.negate = function () { - var sign = this.sign; - var small = new SmallInteger(-this.value); - small.sign = !sign; - return small; - }; - NativeBigInt.prototype.negate = function () { - return new NativeBigInt(-this.value); - } - - BigInteger.prototype.abs = function () { - return new BigInteger(this.value, false); - }; - SmallInteger.prototype.abs = function () { - return new SmallInteger(Math.abs(this.value)); - }; - NativeBigInt.prototype.abs = function () { - return new NativeBigInt(this.value >= 0 ? this.value : -this.value); - } - - - function multiplyLong(a, b) { - var a_l = a.length, - b_l = b.length, - l = a_l + b_l, - r = createArray(l), - base = BASE, - product, carry, i, a_i, b_j; - for (i = 0; i < a_l; ++i) { - a_i = a[i]; - for (var j = 0; j < b_l; ++j) { - b_j = b[j]; - product = a_i * b_j + r[i + j]; - carry = Math.floor(product / base); - r[i + j] = product - carry * base; - r[i + j + 1] += carry; - } - } - trim(r); - return r; + function filterGeneric(eachfn, coll, iteratee, callback) { + var results = []; + eachfn(coll, (x, index, iterCb) => { + iteratee(x, (err, v) => { + if (err) return iterCb(err); + if (v) { + results.push({index, value: x}); + } + iterCb(err); + }); + }, err => { + if (err) return callback(err); + callback(null, results + .sort((a, b) => a.index - b.index) + .map(v => v.value)); + }); } - function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE - var l = a.length, - r = new Array(l), - base = BASE, - carry = 0, - product, i; - for (i = 0; i < l; i++) { - product = a[i] * b + carry; - carry = Math.floor(product / base); - r[i] = product - carry * base; - } - while (carry > 0) { - r[i++] = carry % base; - carry = Math.floor(carry / base); - } - return r; + function _filter(eachfn, coll, iteratee, callback) { + var filter = isArrayLike(coll) ? filterArray : filterGeneric; + return filter(eachfn, coll, wrapAsync(iteratee), callback); } - function shiftLeft(x, n) { - var r = []; - while (n-- > 0) r.push(0); - return r.concat(x); + /** + * Returns a new array of all the values in `coll` which pass an async truth + * test. This operation is performed in parallel, but the results array will be + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.filter(files, fileExists, function(err, results) { + * if(err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * }); + * + * // Using Promises + * async.filter(files, fileExists) + * .then(results => { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.filter(files, fileExists); + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function filter (coll, iteratee, callback) { + return _filter(eachOf$1, coll, iteratee, callback) } + var filter$1 = awaitify(filter, 3); - function multiplyKaratsuba(x, y) { - var n = Math.max(x.length, y.length); - - if (n <= 30) return multiplyLong(x, y); - n = Math.ceil(n / 2); - - var b = x.slice(n), - a = x.slice(0, n), - d = y.slice(n), - c = y.slice(0, n); - - var ac = multiplyKaratsuba(a, c), - bd = multiplyKaratsuba(b, d), - abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d)); - - var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n)); - trim(product); - return product; + /** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + */ + function filterLimit (coll, limit, iteratee, callback) { + return _filter(eachOfLimit$2(limit), coll, iteratee, callback) } + var filterLimit$1 = awaitify(filterLimit, 4); - // The following function is derived from a surface fit of a graph plotting the performance difference - // between long multiplication and karatsuba multiplication versus the lengths of the two arrays. - function useKaratsuba(l1, l2) { - return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0; + /** + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results) + * @returns {Promise} a promise, if no callback provided + */ + function filterSeries (coll, iteratee, callback) { + return _filter(eachOfSeries$1, coll, iteratee, callback) } + var filterSeries$1 = awaitify(filterSeries, 3); - BigInteger.prototype.multiply = function (v) { - var n = parseValue(v), - a = this.value, b = n.value, - sign = this.sign !== n.sign, - abs; - if (n.isSmall) { - if (b === 0) return Integer[0]; - if (b === 1) return this; - if (b === -1) return this.negate(); - abs = Math.abs(b); - if (abs < BASE) { - return new BigInteger(multiplySmall(a, abs), sign); - } - b = smallToArray(abs); - } - if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes - return new BigInteger(multiplyKaratsuba(a, b), sign); - return new BigInteger(multiplyLong(a, b), sign); - }; + /** + * Calls the asynchronous function `fn` with a callback parameter that allows it + * to call itself again, in series, indefinitely. - BigInteger.prototype.times = BigInteger.prototype.multiply; + * If an error is passed to the callback then `errback` is called with the + * error, and execution stops, otherwise it will never be called. + * + * @name forever + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} fn - an async function to call repeatedly. + * Invoked with (next). + * @param {Function} [errback] - when `fn` passes an error to it's callback, + * this function will be called, and execution stops. Invoked with (err). + * @returns {Promise} a promise that rejects if an error occurs and an errback + * is not passed + * @example + * + * async.forever( + * function(next) { + * // next is suitable for passing to things that need a callback(err [, whatever]); + * // it will result in this function being called again. + * }, + * function(err) { + * // if next is called with a value in its first parameter, it will appear + * // in here as 'err', and execution will stop. + * } + * ); + */ + function forever(fn, errback) { + var done = onlyOnce(errback); + var task = wrapAsync(ensureAsync(fn)); - function multiplySmallAndArray(a, b, sign) { // a >= 0 - if (a < BASE) { - return new BigInteger(multiplySmall(b, a), sign); - } - return new BigInteger(multiplyLong(b, smallToArray(a)), sign); - } - SmallInteger.prototype._multiplyBySmall = function (a) { - if (isPrecise(a.value * this.value)) { - return new SmallInteger(a.value * this.value); + function next(err) { + if (err) return done(err); + if (err === false) return; + task(next); } - return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign); - }; - BigInteger.prototype._multiplyBySmall = function (a) { - if (a.value === 0) return Integer[0]; - if (a.value === 1) return this; - if (a.value === -1) return this.negate(); - return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign); - }; - SmallInteger.prototype.multiply = function (v) { - return parseValue(v)._multiplyBySmall(this); - }; - SmallInteger.prototype.times = SmallInteger.prototype.multiply; - - NativeBigInt.prototype.multiply = function (v) { - return new NativeBigInt(this.value * parseValue(v).value); - } - NativeBigInt.prototype.times = NativeBigInt.prototype.multiply; - - function square(a) { - //console.assert(2 * BASE * BASE < MAX_INT); - var l = a.length, - r = createArray(l + l), - base = BASE, - product, carry, i, a_i, a_j; - for (i = 0; i < l; i++) { - a_i = a[i]; - carry = 0 - a_i * a_i; - for (var j = i; j < l; j++) { - a_j = a[j]; - product = 2 * (a_i * a_j) + r[i + j] + carry; - carry = Math.floor(product / base); - r[i + j] = product - carry * base; - } - r[i + l] = carry; - } - trim(r); - return r; + return next(); } + var forever$1 = awaitify(forever, 2); - BigInteger.prototype.square = function () { - return new BigInteger(square(this.value), false); - }; + /** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. + * + * @name groupByLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ + function groupByLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, key) => { + if (err) return iterCb(err); + return iterCb(err, {key, val}); + }); + }, (err, mapResults) => { + var result = {}; + // from MDN, handle object having an `hasOwnProperty` prop + var {hasOwnProperty} = Object.prototype; - SmallInteger.prototype.square = function () { - var value = this.value * this.value; - if (isPrecise(value)) return new SmallInteger(value); - return new BigInteger(square(smallToArray(Math.abs(this.value))), false); - }; + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + var {key} = mapResults[i]; + var {val} = mapResults[i]; - NativeBigInt.prototype.square = function (v) { - return new NativeBigInt(this.value * this.value); - } - - function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes. - var a_l = a.length, - b_l = b.length, - base = BASE, - result = createArray(b.length), - divisorMostSignificantDigit = b[b_l - 1], - // normalization - lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)), - remainder = multiplySmall(a, lambda), - divisor = multiplySmall(b, lambda), - quotientDigit, shift, carry, borrow, i, l, q; - if (remainder.length <= a_l) remainder.push(0); - divisor.push(0); - divisorMostSignificantDigit = divisor[b_l - 1]; - for (shift = a_l - b_l; shift >= 0; shift--) { - quotientDigit = base - 1; - if (remainder[shift + b_l] !== divisorMostSignificantDigit) { - quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit); - } - // quotientDigit <= base - 1 - carry = 0; - borrow = 0; - l = divisor.length; - for (i = 0; i < l; i++) { - carry += quotientDigit * divisor[i]; - q = Math.floor(carry / base); - borrow += remainder[shift + i] - (carry - q * base); - carry = q; - if (borrow < 0) { - remainder[shift + i] = borrow + base; - borrow = -1; - } else { - remainder[shift + i] = borrow; - borrow = 0; - } - } - while (borrow !== 0) { - quotientDigit -= 1; - carry = 0; - for (i = 0; i < l; i++) { - carry += remainder[shift + i] - base + divisor[i]; - if (carry < 0) { - remainder[shift + i] = carry + base; - carry = 0; + if (hasOwnProperty.call(result, key)) { + result[key].push(val); } else { - remainder[shift + i] = carry; - carry = 1; + result[key] = [val]; } } - borrow += carry; - } - result[shift] = quotientDigit; - } - // denormalization - remainder = divModSmall(remainder, lambda)[0]; - return [arrayToSmall(result), arrayToSmall(remainder)]; - } - - function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/ - // Performs faster than divMod1 on larger input sizes. - var a_l = a.length, - b_l = b.length, - result = [], - part = [], - base = BASE, - guess, xlen, highx, highy, check; - while (a_l) { - part.unshift(a[--a_l]); - trim(part); - if (compareAbs(part, b) < 0) { - result.push(0); - continue; - } - xlen = part.length; - highx = part[xlen - 1] * base + part[xlen - 2]; - highy = b[b_l - 1] * base + b[b_l - 2]; - if (xlen > b_l) { - highx = (highx + 1) * base; } - guess = Math.ceil(highx / highy); - do { - check = multiplySmall(b, guess); - if (compareAbs(check, part) <= 0) break; - guess--; - } while (guess); - result.push(guess); - part = subtract(part, check); - } - result.reverse(); - return [arrayToSmall(result), arrayToSmall(part)]; - } - - function divModSmall(value, lambda) { - var length = value.length, - quotient = createArray(length), - base = BASE, - i, q, remainder, divisor; - remainder = 0; - for (i = length - 1; i >= 0; --i) { - divisor = remainder * base + value[i]; - q = truncate(divisor / lambda); - remainder = divisor - q * lambda; - quotient[i] = q | 0; - } - return [quotient, remainder | 0]; - } - - function divModAny(self, v) { - var value, n = parseValue(v); - if (supportsNativeBigInt) { - return [new NativeBigInt(self.value / n.value), new NativeBigInt(self.value % n.value)]; - } - var a = self.value, b = n.value; - var quotient; - if (b === 0) throw new Error("Cannot divide by zero"); - if (self.isSmall) { - if (n.isSmall) { - return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)]; - } - return [Integer[0], self]; - } - if (n.isSmall) { - if (b === 1) return [self, Integer[0]]; - if (b == -1) return [self.negate(), Integer[0]]; - var abs = Math.abs(b); - if (abs < BASE) { - value = divModSmall(a, abs); - quotient = arrayToSmall(value[0]); - var remainder = value[1]; - if (self.sign) remainder = -remainder; - if (typeof quotient === "number") { - if (self.sign !== n.sign) quotient = -quotient; - return [new SmallInteger(quotient), new SmallInteger(remainder)]; - } - return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)]; - } - b = smallToArray(abs); - } - var comparison = compareAbs(a, b); - if (comparison === -1) return [Integer[0], self]; - if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]]; - - // divMod1 is faster on smaller input sizes - if (a.length + b.length <= 200) - value = divMod1(a, b); - else value = divMod2(a, b); - - quotient = value[0]; - var qSign = self.sign !== n.sign, - mod = value[1], - mSign = self.sign; - if (typeof quotient === "number") { - if (qSign) quotient = -quotient; - quotient = new SmallInteger(quotient); - } else quotient = new BigInteger(quotient, qSign); - if (typeof mod === "number") { - if (mSign) mod = -mod; - mod = new SmallInteger(mod); - } else mod = new BigInteger(mod, mSign); - return [quotient, mod]; - } - - BigInteger.prototype.divmod = function (v) { - var result = divModAny(this, v); - return { - quotient: result[0], - remainder: result[1] - }; - }; - NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod = BigInteger.prototype.divmod; + return callback(err, result); + }); + } - BigInteger.prototype.divide = function (v) { - return divModAny(this, v)[0]; - }; - NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function (v) { - return new NativeBigInt(this.value / parseValue(v).value); - }; - SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide; - - BigInteger.prototype.mod = function (v) { - return divModAny(this, v)[1]; - }; - NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function (v) { - return new NativeBigInt(this.value % parseValue(v).value); - }; - SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod; - - BigInteger.prototype.pow = function (v) { - var n = parseValue(v), - a = this.value, - b = n.value, - value, x, y; - if (b === 0) return Integer[1]; - if (a === 0) return Integer[0]; - if (a === 1) return Integer[1]; - if (a === -1) return n.isEven() ? Integer[1] : Integer[-1]; - if (n.sign) { - return Integer[0]; - } - if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large."); - if (this.isSmall) { - if (isPrecise(value = Math.pow(a, b))) - return new SmallInteger(truncate(value)); - } - x = this; - y = Integer[1]; - while (true) { - if (b & 1 === 1) { - y = y.times(x); - --b; - } - if (b === 0) break; - b /= 2; - x = x.square(); - } - return y; - }; - SmallInteger.prototype.pow = BigInteger.prototype.pow; - - NativeBigInt.prototype.pow = function (v) { - var n = parseValue(v); - var a = this.value, b = n.value; - var _0 = BigInt(0), _1 = BigInt(1), _2 = BigInt(2); - if (b === _0) return Integer[1]; - if (a === _0) return Integer[0]; - if (a === _1) return Integer[1]; - if (a === BigInt(-1)) return n.isEven() ? Integer[1] : Integer[-1]; - if (n.isNegative()) return new NativeBigInt(_0); - var x = this; - var y = Integer[1]; - while (true) { - if ((b & _1) === _1) { - y = y.times(x); - --b; - } - if (b === _0) break; - b /= _2; - x = x.square(); - } - return y; - } - - BigInteger.prototype.modPow = function (exp, mod) { - exp = parseValue(exp); - mod = parseValue(mod); - if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0"); - var r = Integer[1], - base = this.mod(mod); - if (exp.isNegative()) { - exp = exp.multiply(Integer[-1]); - base = base.modInv(mod); - } - while (exp.isPositive()) { - if (base.isZero()) return Integer[0]; - if (exp.isOdd()) r = r.multiply(base).mod(mod); - exp = exp.divide(2); - base = base.square().mod(mod); - } - return r; - }; - NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow = BigInteger.prototype.modPow; + var groupByLimit$1 = awaitify(groupByLimit, 4); - function compareAbs(a, b) { - if (a.length !== b.length) { - return a.length > b.length ? 1 : -1; - } - for (var i = a.length - 1; i >= 0; i--) { - if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1; - } - return 0; + /** + * Returns a new object, where each value corresponds to an array of items, from + * `coll`, that returned the corresponding key. That is, the keys of the object + * correspond to the values passed to the `iteratee` callback. + * + * Note: Since this function applies the `iteratee` to each item in parallel, + * there is no guarantee that the `iteratee` functions will complete in order. + * However, the values for each key in the `result` will be in the same order as + * the original `coll`. For Objects, the values will roughly be in the order of + * the original Objects' keys (but this can vary across JavaScript engines). + * + * @name groupBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const files = ['dir1/file1.txt','dir2','dir4'] + * + * // asynchronous function that detects file type as none, file, or directory + * function detectFile(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(null, 'none'); + * } + * callback(null, stat.isDirectory() ? 'directory' : 'file'); + * }); + * } + * + * //Using callbacks + * async.groupBy(files, detectFile, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } + * }); + * + * // Using Promises + * async.groupBy(files, detectFile) + * .then( result => { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.groupBy(files, detectFile); + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function groupBy (coll, iteratee, callback) { + return groupByLimit$1(coll, Infinity, iteratee, callback) } - BigInteger.prototype.compareAbs = function (v) { - var n = parseValue(v), - a = this.value, - b = n.value; - if (n.isSmall) return 1; - return compareAbs(a, b); - }; - SmallInteger.prototype.compareAbs = function (v) { - var n = parseValue(v), - a = Math.abs(this.value), - b = n.value; - if (n.isSmall) { - b = Math.abs(b); - return a === b ? 0 : a > b ? 1 : -1; - } - return -1; - }; - NativeBigInt.prototype.compareAbs = function (v) { - var a = this.value; - var b = parseValue(v).value; - a = a >= 0 ? a : -a; - b = b >= 0 ? b : -b; - return a === b ? 0 : a > b ? 1 : -1; + /** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. + * + * @name groupBySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whose + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ + function groupBySeries (coll, iteratee, callback) { + return groupByLimit$1(coll, 1, iteratee, callback) } - BigInteger.prototype.compare = function (v) { - // See discussion about comparison with Infinity: - // https://github.com/peterolson/BigInteger.js/issues/61 - if (v === Infinity) { - return -1; - } - if (v === -Infinity) { - return 1; - } - - var n = parseValue(v), - a = this.value, - b = n.value; - if (this.sign !== n.sign) { - return n.sign ? 1 : -1; - } - if (n.isSmall) { - return this.sign ? -1 : 1; - } - return compareAbs(a, b) * (this.sign ? -1 : 1); - }; - BigInteger.prototype.compareTo = BigInteger.prototype.compare; - - SmallInteger.prototype.compare = function (v) { - if (v === Infinity) { - return -1; - } - if (v === -Infinity) { - return 1; - } - - var n = parseValue(v), - a = this.value, - b = n.value; - if (n.isSmall) { - return a == b ? 0 : a > b ? 1 : -1; - } - if (a < 0 !== n.sign) { - return a < 0 ? -1 : 1; - } - return a < 0 ? 1 : -1; - }; - SmallInteger.prototype.compareTo = SmallInteger.prototype.compare; + /** + * Logs the result of an `async` function to the `console`. Only works in + * Node.js or in browsers that support `console.log` and `console.error` (such + * as FF and Chrome). If multiple arguments are returned from the async + * function, `console.log` is called on each argument in order. + * + * @name log + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, 'hello ' + name); + * }, 1000); + * }; + * + * // in the node repl + * node> async.log(hello, 'world'); + * 'hello world' + */ + var log = consoleFunc('log'); - NativeBigInt.prototype.compare = function (v) { - if (v === Infinity) { - return -1; - } - if (v === -Infinity) { - return 1; - } - var a = this.value; - var b = parseValue(v).value; - return a === b ? 0 : a > b ? 1 : -1; + /** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a + * time. + * + * @name mapValuesLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ + function mapValuesLimit(obj, limit, iteratee, callback) { + callback = once(callback); + var newObj = {}; + var _iteratee = wrapAsync(iteratee); + return eachOfLimit$2(limit)(obj, (val, key, next) => { + _iteratee(val, key, (err, result) => { + if (err) return next(err); + newObj[key] = result; + next(err); + }); + }, err => callback(err, newObj)); } - NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare; - - BigInteger.prototype.equals = function (v) { - return this.compare(v) === 0; - }; - NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals; - - BigInteger.prototype.notEquals = function (v) { - return this.compare(v) !== 0; - }; - NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals; - - BigInteger.prototype.greater = function (v) { - return this.compare(v) > 0; - }; - NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater; - - BigInteger.prototype.lesser = function (v) { - return this.compare(v) < 0; - }; - NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser; - - BigInteger.prototype.greaterOrEquals = function (v) { - return this.compare(v) >= 0; - }; - NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals; - - BigInteger.prototype.lesserOrEquals = function (v) { - return this.compare(v) <= 0; - }; - NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals; - BigInteger.prototype.isEven = function () { - return (this.value[0] & 1) === 0; - }; - SmallInteger.prototype.isEven = function () { - return (this.value & 1) === 0; - }; - NativeBigInt.prototype.isEven = function () { - return (this.value & BigInt(1)) === BigInt(0); - } + var mapValuesLimit$1 = awaitify(mapValuesLimit, 4); - BigInteger.prototype.isOdd = function () { - return (this.value[0] & 1) === 1; - }; - SmallInteger.prototype.isOdd = function () { - return (this.value & 1) === 1; - }; - NativeBigInt.prototype.isOdd = function () { - return (this.value & BigInt(1)) === BigInt(1); - } - - BigInteger.prototype.isPositive = function () { - return !this.sign; - }; - SmallInteger.prototype.isPositive = function () { - return this.value > 0; - }; - NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive; - - BigInteger.prototype.isNegative = function () { - return this.sign; - }; - SmallInteger.prototype.isNegative = function () { - return this.value < 0; - }; - NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative; - - BigInteger.prototype.isUnit = function () { - return false; - }; - SmallInteger.prototype.isUnit = function () { - return Math.abs(this.value) === 1; - }; - NativeBigInt.prototype.isUnit = function () { - return this.abs().value === BigInt(1); + /** + * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. + * + * Produces a new Object by mapping each value of `obj` through the `iteratee` + * function. The `iteratee` is called each `value` and `key` from `obj` and a + * callback for when it has finished processing. Each of these callbacks takes + * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` + * passes an error to its callback, the main `callback` (for the `mapValues` + * function) is immediately called with the error. + * + * Note, the order of the keys in the result is not guaranteed. The keys will + * be roughly in the order they complete, (but this is very engine-specific) + * + * @name mapValues + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file3.txt' + * }; + * + * const withMissingFileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file4.txt' + * }; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, key, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.mapValues(fileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * } else { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * }); + * + * // Error handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(result); + * } + * }); + * + * // Using Promises + * async.mapValues(fileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * }).catch (err => { + * console.log(err); + * }); + * + * // Error Handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch (err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.mapValues(fileMap, getFileSizeInBytes); + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ + function mapValues(obj, iteratee, callback) { + return mapValuesLimit$1(obj, Infinity, iteratee, callback) } - BigInteger.prototype.isZero = function () { - return false; - }; - SmallInteger.prototype.isZero = function () { - return this.value === 0; - }; - NativeBigInt.prototype.isZero = function () { - return this.value === BigInt(0); + /** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. + * + * @name mapValuesSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ + function mapValuesSeries(obj, iteratee, callback) { + return mapValuesLimit$1(obj, 1, iteratee, callback) } - BigInteger.prototype.isDivisibleBy = function (v) { - var n = parseValue(v); - if (n.isZero()) return false; - if (n.isUnit()) return true; - if (n.compareAbs(2) === 0) return this.isEven(); - return this.mod(n).isZero(); - }; - NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy; - - function isBasicPrime(v) { - var n = v.abs(); - if (n.isUnit()) return false; - if (n.equals(2) || n.equals(3) || n.equals(5)) return true; - if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false; - if (n.lesser(49)) return true; - // we don't know if it's prime: let the other functions figure it out - } - - function millerRabinTest(n, a) { - var nPrev = n.prev(), - b = nPrev, - r = 0, - d, t, i, x; - while (b.isEven()) b = b.divide(2), r++; - next: for (i = 0; i < a.length; i++) { - if (n.lesser(a[i])) continue; - x = bigInt(a[i]).modPow(b, n); - if (x.isUnit() || x.equals(nPrev)) continue; - for (d = r - 1; d != 0; d--) { - x = x.square().mod(n); - if (x.isUnit()) return false; - if (x.equals(nPrev)) continue next; + /** + * Caches the results of an async function. When creating a hash to store + * function results against, the callback is omitted from the hash and an + * optional hash function can be used. + * + * **Note: if the async function errs, the result will not be cached and + * subsequent calls will call the wrapped function.** + * + * If no hash function is specified, the first argument is used as a hash key, + * which may work reasonably if it is a string or a data type that converts to a + * distinct string. Note that objects and arrays will not behave reasonably. + * Neither will cases where the other arguments are significant. In such cases, + * specify your own hash function. + * + * The cache of results is exposed as the `memo` property of the function + * returned by `memoize`. + * + * @name memoize + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function to proxy and cache results from. + * @param {Function} hasher - An optional function for generating a custom hash + * for storing results. It has all the arguments applied to it apart from the + * callback, and must be synchronous. + * @returns {AsyncFunction} a memoized version of `fn` + * @example + * + * var slow_fn = function(name, callback) { + * // do something + * callback(null, result); + * }; + * var fn = async.memoize(slow_fn); + * + * // fn can now be used as if it were slow_fn + * fn('some name', function() { + * // callback + * }); + */ + function memoize(fn, hasher = v => v) { + var memo = Object.create(null); + var queues = Object.create(null); + var _fn = wrapAsync(fn); + var memoized = initialParams((args, callback) => { + var key = hasher(...args); + if (key in memo) { + setImmediate$1(() => callback(null, ...memo[key])); + } else if (key in queues) { + queues[key].push(callback); + } else { + queues[key] = [callback]; + _fn(...args, (err, ...resultArgs) => { + // #1465 don't memoize if an error occurred + if (!err) { + memo[key] = resultArgs; + } + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i](err, ...resultArgs); + } + }); } - return false; - } - return true; - } - - // Set "strict" to true to force GRH-supported lower bound of 2*log(N)^2 - BigInteger.prototype.isPrime = function (strict) { - var isPrime = isBasicPrime(this); - if (isPrime !== undefined) return isPrime; - var n = this.abs(); - var bits = n.bitLength(); - if (bits <= 64) - return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]); - var logN = Math.log(2) * bits.toJSNumber(); - var t = Math.ceil((strict === true) ? (2 * Math.pow(logN, 2)) : logN); - for (var a = [], i = 0; i < t; i++) { - a.push(bigInt(i + 2)); - } - return millerRabinTest(n, a); - }; - NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime; - - BigInteger.prototype.isProbablePrime = function (iterations, rng) { - var isPrime = isBasicPrime(this); - if (isPrime !== undefined) return isPrime; - var n = this.abs(); - var t = iterations === undefined ? 5 : iterations; - for (var a = [], i = 0; i < t; i++) { - a.push(bigInt.randBetween(2, n.minus(2), rng)); - } - return millerRabinTest(n, a); - }; - NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime; - - BigInteger.prototype.modInv = function (n) { - var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR; - while (!newR.isZero()) { - q = r.divide(newR); - lastT = t; - lastR = r; - t = newT; - r = newR; - newT = lastT.subtract(q.multiply(newT)); - newR = lastR.subtract(q.multiply(newR)); - } - if (!r.isUnit()) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime"); - if (t.compare(0) === -1) { - t = t.add(n); - } - if (this.isNegative()) { - return t.negate(); - } - return t; - }; - - NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv = BigInteger.prototype.modInv; - - BigInteger.prototype.next = function () { - var value = this.value; - if (this.sign) { - return subtractSmall(value, 1, this.sign); - } - return new BigInteger(addSmall(value, 1), this.sign); - }; - SmallInteger.prototype.next = function () { - var value = this.value; - if (value + 1 < MAX_INT) return new SmallInteger(value + 1); - return new BigInteger(MAX_INT_ARR, false); - }; - NativeBigInt.prototype.next = function () { - return new NativeBigInt(this.value + BigInt(1)); + }); + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; } - BigInteger.prototype.prev = function () { - var value = this.value; - if (this.sign) { - return new BigInteger(addSmall(value, 1), true); - } - return subtractSmall(value, 1, this.sign); - }; - SmallInteger.prototype.prev = function () { - var value = this.value; - if (value - 1 > -MAX_INT) return new SmallInteger(value - 1); - return new BigInteger(MAX_INT_ARR, true); - }; - NativeBigInt.prototype.prev = function () { - return new NativeBigInt(this.value - BigInt(1)); - } + /* istanbul ignore file */ - var powersOfTwo = [1]; - while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]); - var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1]; + /** + * Calls `callback` on a later loop around the event loop. In Node.js this just + * calls `process.nextTick`. In the browser it will use `setImmediate` if + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name nextTick + * @static + * @memberOf module:Utils + * @method + * @see [async.setImmediate]{@link module:Utils.setImmediate} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ + var _defer; - function shift_isSmall(n) { - return Math.abs(n) <= BASE; + if (hasNextTick) { + _defer = process.nextTick; + } else if (hasSetImmediate) { + _defer = setImmediate; + } else { + _defer = fallback; } - BigInteger.prototype.shiftLeft = function (v) { - var n = parseValue(v).toJSNumber(); - if (!shift_isSmall(n)) { - throw new Error(String(n) + " is too large for shifting."); - } - if (n < 0) return this.shiftRight(-n); - var result = this; - if (result.isZero()) return result; - while (n >= powers2Length) { - result = result.multiply(highestPower2); - n -= powers2Length - 1; - } - return result.multiply(powersOfTwo[n]); - }; - NativeBigInt.prototype.shiftLeft = SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft; - - BigInteger.prototype.shiftRight = function (v) { - var remQuo; - var n = parseValue(v).toJSNumber(); - if (!shift_isSmall(n)) { - throw new Error(String(n) + " is too large for shifting."); - } - if (n < 0) return this.shiftLeft(-n); - var result = this; - while (n >= powers2Length) { - if (result.isZero() || (result.isNegative() && result.isUnit())) return result; - remQuo = divModAny(result, highestPower2); - result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; - n -= powers2Length - 1; - } - remQuo = divModAny(result, powersOfTwo[n]); - return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; - }; - NativeBigInt.prototype.shiftRight = SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight; + var nextTick = wrap(_defer); - function bitwise(x, y, fn) { - y = parseValue(y); - var xSign = x.isNegative(), ySign = y.isNegative(); - var xRem = xSign ? x.not() : x, - yRem = ySign ? y.not() : y; - var xDigit = 0, yDigit = 0; - var xDivMod = null, yDivMod = null; - var result = []; - while (!xRem.isZero() || !yRem.isZero()) { - xDivMod = divModAny(xRem, highestPower2); - xDigit = xDivMod[1].toJSNumber(); - if (xSign) { - xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers - } + var _parallel = awaitify((eachfn, tasks, callback) => { + var results = isArrayLike(tasks) ? [] : {}; - yDivMod = divModAny(yRem, highestPower2); - yDigit = yDivMod[1].toJSNumber(); - if (ySign) { - yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers - } + eachfn(tasks, (task, key, taskCb) => { + wrapAsync(task)((err, ...result) => { + if (result.length < 2) { + [result] = result; + } + results[key] = result; + taskCb(err); + }); + }, err => callback(err, results)); + }, 3); - xRem = xDivMod[0]; - yRem = yDivMod[0]; - result.push(fn(xDigit, yDigit)); - } - var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0); - for (var i = result.length - 1; i >= 0; i -= 1) { - sum = sum.multiply(highestPower2).add(bigInt(result[i])); - } - return sum; + /** + * Run the `tasks` collection of functions in parallel, without waiting until + * the previous function has completed. If any of the functions pass an error to + * its callback, the main `callback` is immediately called with the value of the + * error. Once the `tasks` have completed, the results are passed to the final + * `callback` as an array. + * + * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about + * parallel execution of code. If your tasks do not use any timers or perform + * any I/O, they will actually be executed in series. Any synchronous setup + * sections for each task will happen one after the other. JavaScript remains + * single-threaded. + * + * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the + * execution of other tasks when a task fails. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.parallel}. + * + * @name parallel + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * + * //Using Callbacks + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }); + * + * //Using Promises + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * }).catch(err => { + * console.log(err); + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function parallel(tasks, callback) { + return _parallel(eachOf$1, tasks, callback); } - BigInteger.prototype.not = function () { - return this.negate().prev(); - }; - NativeBigInt.prototype.not = SmallInteger.prototype.not = BigInteger.prototype.not; - - BigInteger.prototype.and = function (n) { - return bitwise(this, n, function (a, b) { return a & b; }); - }; - NativeBigInt.prototype.and = SmallInteger.prototype.and = BigInteger.prototype.and; - - BigInteger.prototype.or = function (n) { - return bitwise(this, n, function (a, b) { return a | b; }); - }; - NativeBigInt.prototype.or = SmallInteger.prototype.or = BigInteger.prototype.or; + /** + * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a + * time. + * + * @name parallelLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.parallel]{@link module:ControlFlow.parallel} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + */ + function parallelLimit(tasks, limit, callback) { + return _parallel(eachOfLimit$2(limit), tasks, callback); + } - BigInteger.prototype.xor = function (n) { - return bitwise(this, n, function (a, b) { return a ^ b; }); - }; - NativeBigInt.prototype.xor = SmallInteger.prototype.xor = BigInteger.prototype.xor; - - var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I; - function roughLOB(n) { // get lowestOneBit (rough) - // SmallInteger: return Min(lowestOneBit(n), 1 << 30) - // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7] - var v = n.value, - x = typeof v === "number" ? v | LOBMASK_I : - typeof v === "bigint" ? v | BigInt(LOBMASK_I) : - v[0] + v[1] * BASE | LOBMASK_BI; - return x & -x; - } - - function integerLogarithm(value, base) { - if (base.compareTo(value) <= 0) { - var tmp = integerLogarithm(value, base.square(base)); - var p = tmp.p; - var e = tmp.e; - var t = p.multiply(base); - return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 }; - } - return { p: bigInt(1), e: 0 }; - } - - BigInteger.prototype.bitLength = function () { - var n = this; - if (n.compareTo(bigInt(0)) < 0) { - n = n.negate().subtract(bigInt(1)); - } - if (n.compareTo(bigInt(0)) === 0) { - return bigInt(0); - } - return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1)); - } - NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength; - - function max(a, b) { - a = parseValue(a); - b = parseValue(b); - return a.greater(b) ? a : b; - } - function min(a, b) { - a = parseValue(a); - b = parseValue(b); - return a.lesser(b) ? a : b; - } - function gcd(a, b) { - a = parseValue(a).abs(); - b = parseValue(b).abs(); - if (a.equals(b)) return a; - if (a.isZero()) return b; - if (b.isZero()) return a; - var c = Integer[1], d, t; - while (a.isEven() && b.isEven()) { - d = min(roughLOB(a), roughLOB(b)); - a = a.divide(d); - b = b.divide(d); - c = c.multiply(d); - } - while (a.isEven()) { - a = a.divide(roughLOB(a)); - } - do { - while (b.isEven()) { - b = b.divide(roughLOB(b)); - } - if (a.greater(b)) { - t = b; b = a; a = t; - } - b = b.subtract(a); - } while (!b.isZero()); - return c.isUnit() ? a : a.multiply(c); - } - function lcm(a, b) { - a = parseValue(a).abs(); - b = parseValue(b).abs(); - return a.divide(gcd(a, b)).multiply(b); - } - function randBetween(a, b, rng) { - a = parseValue(a); - b = parseValue(b); - var usedRNG = rng || Math.random; - var low = min(a, b), high = max(a, b); - var range = high.subtract(low).add(1); - if (range.isSmall) return low.add(Math.floor(usedRNG() * range)); - var digits = toBase(range, BASE).value; - var result = [], restricted = true; - for (var i = 0; i < digits.length; i++) { - var top = restricted ? digits[i] + (i + 1 < digits.length ? digits[i + 1] / BASE : 0) : BASE; - var digit = truncate(usedRNG() * top); - result.push(digit); - if (digit < digits[i]) restricted = false; - } - return low.add(Integer.fromArray(result, BASE, false)); - } - - var parseBase = function (text, base, alphabet, caseSensitive) { - alphabet = alphabet || DEFAULT_ALPHABET; - text = String(text); - if (!caseSensitive) { - text = text.toLowerCase(); - alphabet = alphabet.toLowerCase(); - } - var length = text.length; - var i; - var absBase = Math.abs(base); - var alphabetValues = {}; - for (i = 0; i < alphabet.length; i++) { - alphabetValues[alphabet[i]] = i; - } - for (i = 0; i < length; i++) { - var c = text[i]; - if (c === "-") continue; - if (c in alphabetValues) { - if (alphabetValues[c] >= absBase) { - if (c === "1" && absBase === 1) continue; - throw new Error(c + " is not a valid digit in base " + base + "."); - } - } - } - base = parseValue(base); - var digits = []; - var isNegative = text[0] === "-"; - for (i = isNegative ? 1 : 0; i < text.length; i++) { - var c = text[i]; - if (c in alphabetValues) digits.push(parseValue(alphabetValues[c])); - else if (c === "<") { - var start = i; - do { i++; } while (text[i] !== ">" && i < text.length); - digits.push(parseValue(text.slice(start + 1, i))); - } - else throw new Error(c + " is not a valid character"); - } - return parseBaseFromArray(digits, base, isNegative); - }; + /** + * A queue of tasks for the worker function to complete. + * @typedef {Iterable} QueueObject + * @memberOf module:ControlFlow + * @property {Function} length - a function returning the number of items + * waiting to be processed. Invoke with `queue.length()`. + * @property {boolean} started - a boolean indicating whether or not any + * items have been pushed and processed by the queue. + * @property {Function} running - a function returning the number of items + * currently being processed. Invoke with `queue.running()`. + * @property {Function} workersList - a function returning the array of items + * currently being processed. Invoke with `queue.workersList()`. + * @property {Function} idle - a function returning false if there are items + * waiting or being processed, or true if not. Invoke with `queue.idle()`. + * @property {number} concurrency - an integer for determining how many `worker` + * functions should be run in parallel. This property can be changed after a + * `queue` is created to alter the concurrency on-the-fly. + * @property {number} payload - an integer that specifies how many items are + * passed to the worker function at a time. only applies if this is a + * [cargo]{@link module:ControlFlow.cargo} object + * @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback` + * once the `worker` has finished processing the task. Instead of a single task, + * a `tasks` array can be submitted. The respective callback is used for every + * task in the list. Invoke with `queue.push(task, [callback])`, + * @property {AsyncFunction} unshift - add a new task to the front of the `queue`. + * Invoke with `queue.unshift(task, [callback])`. + * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns + * a promise that rejects if an error occurs. + * @property {AsyncFunction} unshiftAsync - the same as `q.unshift`, except this returns + * a promise that rejects if an error occurs. + * @property {Function} remove - remove items from the queue that match a test + * function. The test function will be passed an object with a `data` property, + * and a `priority` property, if this is a + * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. + * Invoked with `queue.remove(testFn)`, where `testFn` is of the form + * `function ({data, priority}) {}` and returns a Boolean. + * @property {Function} saturated - a function that sets a callback that is + * called when the number of running workers hits the `concurrency` limit, and + * further tasks will be queued. If the callback is omitted, `q.saturated()` + * returns a promise for the next occurrence. + * @property {Function} unsaturated - a function that sets a callback that is + * called when the number of running workers is less than the `concurrency` & + * `buffer` limits, and further tasks will not be queued. If the callback is + * omitted, `q.unsaturated()` returns a promise for the next occurrence. + * @property {number} buffer - A minimum threshold buffer in order to say that + * the `queue` is `unsaturated`. + * @property {Function} empty - a function that sets a callback that is called + * when the last item from the `queue` is given to a `worker`. If the callback + * is omitted, `q.empty()` returns a promise for the next occurrence. + * @property {Function} drain - a function that sets a callback that is called + * when the last item from the `queue` has returned from the `worker`. If the + * callback is omitted, `q.drain()` returns a promise for the next occurrence. + * @property {Function} error - a function that sets a callback that is called + * when a task errors. Has the signature `function(error, task)`. If the + * callback is omitted, `error()` returns a promise that rejects on the next + * error. + * @property {boolean} paused - a boolean for determining whether the queue is + * in a paused state. + * @property {Function} pause - a function that pauses the processing of tasks + * until `resume()` is called. Invoke with `queue.pause()`. + * @property {Function} resume - a function that resumes the processing of + * queued tasks when the queue is paused. Invoke with `queue.resume()`. + * @property {Function} kill - a function that removes the `drain` callback and + * empties remaining tasks from the queue forcing it to go idle. No more tasks + * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. + * + * @example + * const q = async.queue(worker, 2) + * q.push(item1) + * q.push(item2) + * q.push(item3) + * // queues are iterable, spread into an array to inspect + * const items = [...q] // [item1, item2, item3] + * // or use for of + * for (let item of q) { + * console.log(item) + * } + * + * q.drain(() => { + * console.log('all done') + * }) + * // or + * await q.drain() + */ - function parseBaseFromArray(digits, base, isNegative) { - var val = Integer[0], pow = Integer[1], i; - for (i = digits.length - 1; i >= 0; i--) { - val = val.add(digits[i].times(pow)); - pow = pow.times(base); - } - return isNegative ? val.negate() : val; + /** + * Creates a `queue` object with the specified `concurrency`. Tasks added to the + * `queue` are processed in parallel (up to the `concurrency` limit). If all + * `worker`s are in progress, the task is queued until one becomes available. + * Once a `worker` completes a `task`, that `task`'s callback is called. + * + * @name queue + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. Invoked with (task, callback). + * @param {number} [concurrency=1] - An `integer` for determining how many + * `worker` functions should be run in parallel. If omitted, the concurrency + * defaults to `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be + * attached as certain properties to listen for specific events during the + * lifecycle of the queue. + * @example + * + * // create a queue object with concurrency 2 + * var q = async.queue(function(task, callback) { + * console.log('hello ' + task.name); + * callback(); + * }, 2); + * + * // assign a callback + * q.drain(function() { + * console.log('all items have been processed'); + * }); + * // or await the end + * await q.drain() + * + * // assign an error callback + * q.error(function(err, task) { + * console.error('task experienced an error'); + * }); + * + * // add some items to the queue + * q.push({name: 'foo'}, function(err) { + * console.log('finished processing foo'); + * }); + * // callback is optional + * q.push({name: 'bar'}); + * + * // add some items to the queue (batch-wise) + * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { + * console.log('finished processing item'); + * }); + * + * // add some items to the front of the queue + * q.unshift({name: 'bar'}, function (err) { + * console.log('finished processing bar'); + * }); + */ + function queue (worker, concurrency) { + var _worker = wrapAsync(worker); + return queue$1((items, cb) => { + _worker(items[0], cb); + }, concurrency, 1); } - function stringify(digit, alphabet) { - alphabet = alphabet || DEFAULT_ALPHABET; - if (digit < alphabet.length) { - return alphabet[digit]; + // Binary min-heap implementation used for priority queue. + // Implementation is stable, i.e. push time is considered for equal priorities + class Heap { + constructor() { + this.heap = []; + this.pushCount = Number.MIN_SAFE_INTEGER; } - return "<" + digit + ">"; - } - function toBase(n, base) { - base = bigInt(base); - if (base.isZero()) { - if (n.isZero()) return { value: [0], isNegative: false }; - throw new Error("Cannot convert nonzero numbers to base 0."); + get length() { + return this.heap.length; } - if (base.equals(-1)) { - if (n.isZero()) return { value: [0], isNegative: false }; - if (n.isNegative()) - return { - value: [].concat.apply([], Array.apply(null, Array(-n.toJSNumber())) - .map(Array.prototype.valueOf, [1, 0]) - ), - isNegative: false - }; - var arr = Array.apply(null, Array(n.toJSNumber() - 1)) - .map(Array.prototype.valueOf, [0, 1]); - arr.unshift([1]); - return { - value: [].concat.apply([], arr), - isNegative: false - }; + empty () { + this.heap = []; + return this; } - var neg = false; - if (n.isNegative() && base.isPositive()) { - neg = true; - n = n.abs(); - } - if (base.isUnit()) { - if (n.isZero()) return { value: [0], isNegative: false }; + percUp(index) { + let p; - return { - value: Array.apply(null, Array(n.toJSNumber())) - .map(Number.prototype.valueOf, 1), - isNegative: neg - }; - } - var out = []; - var left = n, divmod; - while (left.isNegative() || left.compareAbs(base) >= 0) { - divmod = left.divmod(base); - left = divmod.quotient; - var digit = divmod.remainder; - if (digit.isNegative()) { - digit = base.minus(digit).abs(); - left = left.next(); + while (index > 0 && smaller(this.heap[index], this.heap[p=parent(index)])) { + let t = this.heap[index]; + this.heap[index] = this.heap[p]; + this.heap[p] = t; + + index = p; } - out.push(digit.toJSNumber()); } - out.push(left.toJSNumber()); - return { value: out.reverse(), isNegative: neg }; - } - function toBaseString(n, base, alphabet) { - var arr = toBase(n, base); - return (arr.isNegative ? "-" : "") + arr.value.map(function (x) { - return stringify(x, alphabet); - }).join(''); - } + percDown(index) { + let l; - BigInteger.prototype.toArray = function (radix) { - return toBase(this, radix); - }; + while ((l=leftChi(index)) < this.heap.length) { + if (l+1 < this.heap.length && smaller(this.heap[l+1], this.heap[l])) { + l = l+1; + } - SmallInteger.prototype.toArray = function (radix) { - return toBase(this, radix); - }; + if (smaller(this.heap[index], this.heap[l])) { + break; + } - NativeBigInt.prototype.toArray = function (radix) { - return toBase(this, radix); - }; + let t = this.heap[index]; + this.heap[index] = this.heap[l]; + this.heap[l] = t; - BigInteger.prototype.toString = function (radix, alphabet) { - if (radix === undefined) radix = 10; - if (radix !== 10) return toBaseString(this, radix, alphabet); - var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit; - while (--l >= 0) { - digit = String(v[l]); - str += zeros.slice(digit.length) + digit; + index = l; + } } - var sign = this.sign ? "-" : ""; - return sign + str; - }; - - SmallInteger.prototype.toString = function (radix, alphabet) { - if (radix === undefined) radix = 10; - if (radix != 10) return toBaseString(this, radix, alphabet); - return String(this.value); - }; - - NativeBigInt.prototype.toString = SmallInteger.prototype.toString; - NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString(); } + push(node) { + node.pushCount = ++this.pushCount; + this.heap.push(node); + this.percUp(this.heap.length-1); + } - BigInteger.prototype.valueOf = function () { - return parseInt(this.toString(), 10); - }; - BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf; + unshift(node) { + return this.heap.push(node); + } - SmallInteger.prototype.valueOf = function () { - return this.value; - }; - SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf; - NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function () { - return parseInt(this.toString(), 10); - } - - function parseStringValue(v) { - if (isPrecise(+v)) { - var x = +v; - if (x === truncate(x)) - return supportsNativeBigInt ? new NativeBigInt(BigInt(x)) : new SmallInteger(x); - throw new Error("Invalid integer: " + v); - } - var sign = v[0] === "-"; - if (sign) v = v.slice(1); - var split = v.split(/e/i); - if (split.length > 2) throw new Error("Invalid integer: " + split.join("e")); - if (split.length === 2) { - var exp = split[1]; - if (exp[0] === "+") exp = exp.slice(1); - exp = +exp; - if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent."); - var text = split[0]; - var decimalPlace = text.indexOf("."); - if (decimalPlace >= 0) { - exp -= text.length - decimalPlace - 1; - text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1); - } - if (exp < 0) throw new Error("Cannot include negative exponent part for integers"); - text += (new Array(exp + 1)).join("0"); - v = text; - } - var isValid = /^([0-9][0-9]*)$/.test(v); - if (!isValid) throw new Error("Invalid integer: " + v); - if (supportsNativeBigInt) { - return new NativeBigInt(BigInt(sign ? "-" + v : v)); - } - var r = [], max = v.length, l = LOG_BASE, min = max - l; - while (max > 0) { - r.push(+v.slice(min, max)); - min -= l; - if (min < 0) min = 0; - max -= l; - } - trim(r); - return new BigInteger(r, sign); - } - - function parseNumberValue(v) { - if (supportsNativeBigInt) { - return new NativeBigInt(BigInt(v)); - } - if (isPrecise(v)) { - if (v !== truncate(v)) throw new Error(v + " is not an integer."); - return new SmallInteger(v); - } - return parseStringValue(v.toString()); - } - - function parseValue(v) { - if (typeof v === "number") { - return parseNumberValue(v); - } - if (typeof v === "string") { - return parseStringValue(v); - } - if (typeof v === "bigint") { - return new NativeBigInt(v); - } - return v; - } - // Pre-define numbers in range [-999,999] - for (var i = 0; i < 1000; i++) { - Integer[i] = parseValue(i); - if (i > 0) Integer[-i] = parseValue(-i); - } - // Backwards compatibility - Integer.one = Integer[1]; - Integer.zero = Integer[0]; - Integer.minusOne = Integer[-1]; - Integer.max = max; - Integer.min = min; - Integer.gcd = gcd; - Integer.lcm = lcm; - Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger || x instanceof NativeBigInt; }; - Integer.randBetween = randBetween; - - Integer.fromArray = function (digits, base, isNegative) { - return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative); - }; + shift() { + let [top] = this.heap; - return Integer; -})(); + this.heap[0] = this.heap[this.heap.length-1]; + this.heap.pop(); + this.percDown(0); -// Node.js check -if ( true && module.hasOwnProperty("exports")) { - module.exports = bigInt; -} + return top; + } -//amd check -if (typeof define === "function" && define.amd) { - define( function () { - return bigInt; - }); -} + toArray() { + return [...this]; + } + *[Symbol.iterator] () { + for (let i = 0; i < this.heap.length; i++) { + yield this.heap[i].data; + } + } -/***/ }), + remove (testFn) { + let j = 0; + for (let i = 0; i < this.heap.length; i++) { + if (!testFn(this.heap[i])) { + this.heap[j] = this.heap[i]; + j++; + } + } -/***/ 59099: -/***/ ((module, exports, __nccwpck_require__) => { + this.heap.splice(j); -var Chainsaw = __nccwpck_require__(9242); -var EventEmitter = (__nccwpck_require__(82361).EventEmitter); -var Buffers = __nccwpck_require__(53913); -var Vars = __nccwpck_require__(25738); -var Stream = (__nccwpck_require__(12781).Stream); + for (let i = parent(this.heap.length-1); i >= 0; i--) { + this.percDown(i); + } -exports = module.exports = function (bufOrEm, eventName) { - if (Buffer.isBuffer(bufOrEm)) { - return exports.parse(bufOrEm); - } - - var s = exports.stream(); - if (bufOrEm && bufOrEm.pipe) { - bufOrEm.pipe(s); + return this; + } } - else if (bufOrEm) { - bufOrEm.on(eventName || 'data', function (buf) { - s.write(buf); - }); - - bufOrEm.on('end', function () { - s.end(); - }); + + function leftChi(i) { + return (i<<1)+1; } - return s; -}; -exports.stream = function (input) { - if (input) return exports.apply(null, arguments); - - var pending = null; - function getBytes (bytes, cb, skip) { - pending = { - bytes : bytes, - skip : skip, - cb : function (buf) { - pending = null; - cb(buf); - }, - }; - dispatch(); + function parent(i) { + return ((i+1)>>1)-1; } - - var offset = null; - function dispatch () { - if (!pending) { - if (caughtEnd) done = true; - return; - } - if (typeof pending === 'function') { - pending(); + + function smaller(x, y) { + if (x.priority !== y.priority) { + return x.priority < y.priority; } else { - var bytes = offset + pending.bytes; - - if (buffers.length >= bytes) { - var buf; - if (offset == null) { - buf = buffers.splice(0, bytes); - if (!pending.skip) { - buf = buf.slice(); - } - } - else { - if (!pending.skip) { - buf = buffers.slice(offset, bytes); - } - offset = bytes; - } - - if (pending.skip) { - pending.cb(); - } - else { - pending.cb(buf); - } - } + return x.pushCount < y.pushCount; } } - - function builder (saw) { - function next () { if (!done) saw.next() } - - var self = words(function (bytes, cb) { - return function (name) { - getBytes(bytes, function (buf) { - vars.set(name, cb(buf)); - next(); - }); + + /** + * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and + * completed in ascending priority order. + * + * @name priorityQueue + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. + * Invoked with (task, callback). + * @param {number} concurrency - An `integer` for determining how many `worker` + * functions should be run in parallel. If omitted, the concurrency defaults to + * `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are three + * differences between `queue` and `priorityQueue` objects: + * * `push(task, priority, [callback])` - `priority` should be a number. If an + * array of `tasks` is given, all tasks will be assigned the same priority. + * * `pushAsync(task, priority, [callback])` - the same as `priorityQueue.push`, + * except this returns a promise that rejects if an error occurs. + * * The `unshift` and `unshiftAsync` methods were removed. + */ + function priorityQueue(worker, concurrency) { + // Start with a normal queue + var q = queue(worker, concurrency); + + var { + push, + pushAsync + } = q; + + q._tasks = new Heap(); + q._createTaskItem = ({data, priority}, callback) => { + return { + data, + priority, + callback }; - }); - - self.tap = function (cb) { - saw.nest(cb, vars.store); - }; - - self.into = function (key, cb) { - if (!vars.get(key)) vars.set(key, {}); - var parent = vars; - vars = Vars(parent.get(key)); - - saw.nest(function () { - cb.apply(this, arguments); - this.tap(function () { - vars = parent; - }); - }, vars.store); - }; - - self.flush = function () { - vars.store = {}; - next(); - }; - - self.loop = function (cb) { - var end = false; - - saw.nest(false, function loop () { - this.vars = vars.store; - cb.call(this, function () { - end = true; - next(); - }, vars.store); - this.tap(function () { - if (end) saw.next() - else loop.call(this) - }.bind(this)); - }, vars.store); - }; - - self.buffer = function (name, bytes) { - if (typeof bytes === 'string') { - bytes = vars.get(bytes); - } - - getBytes(bytes, function (buf) { - vars.set(name, buf); - next(); - }); - }; - - self.skip = function (bytes) { - if (typeof bytes === 'string') { - bytes = vars.get(bytes); - } - - getBytes(bytes, function () { - next(); - }); }; - - self.scan = function find (name, search) { - if (typeof search === 'string') { - search = new Buffer(search); - } - else if (!Buffer.isBuffer(search)) { - throw new Error('search must be a Buffer or a string'); + + function createDataItems(tasks, priority) { + if (!Array.isArray(tasks)) { + return {data: tasks, priority}; } - - var taken = 0; - pending = function () { - var pos = buffers.indexOf(search, offset + taken); - var i = pos-offset-taken; - if (pos !== -1) { - pending = null; - if (offset != null) { - vars.set( - name, - buffers.slice(offset, offset + taken + i) - ); - offset += taken + i + search.length; - } - else { - vars.set( - name, - buffers.slice(0, taken + i) - ); - buffers.splice(0, taken + i + search.length); - } - next(); - dispatch(); - } else { - i = Math.max(buffers.length - search.length - offset - taken, 0); - } - taken += i; - }; - dispatch(); + return tasks.map(data => { return {data, priority}; }); + } + + // Override push to accept second parameter representing priority + q.push = function(data, priority = 0, callback) { + return push(createDataItems(data, priority), callback); }; - - self.peek = function (cb) { - offset = 0; - saw.nest(function () { - cb.call(this, vars.store); - this.tap(function () { - offset = null; - }); - }); + + q.pushAsync = function(data, priority = 0, callback) { + return pushAsync(createDataItems(data, priority), callback); }; - - return self; - }; - - var stream = Chainsaw.light(builder); - stream.writable = true; - - var buffers = Buffers(); - - stream.write = function (buf) { - buffers.push(buf); - dispatch(); - }; - - var vars = Vars(); - - var done = false, caughtEnd = false; - stream.end = function () { - caughtEnd = true; - }; - - stream.pipe = Stream.prototype.pipe; - Object.getOwnPropertyNames(EventEmitter.prototype).forEach(function (name) { - stream[name] = EventEmitter.prototype[name]; - }); - - return stream; -}; -exports.parse = function parse (buffer) { - var self = words(function (bytes, cb) { - return function (name) { - if (offset + bytes <= buffer.length) { - var buf = buffer.slice(offset, offset + bytes); - offset += bytes; - vars.set(name, cb(buf)); - } - else { - vars.set(name, null); - } - return self; - }; - }); - - var offset = 0; - var vars = Vars(); - self.vars = vars.store; - - self.tap = function (cb) { - cb.call(self, vars.store); - return self; - }; - - self.into = function (key, cb) { - if (!vars.get(key)) { - vars.set(key, {}); - } - var parent = vars; - vars = Vars(parent.get(key)); - cb.call(self, vars.store); - vars = parent; - return self; - }; - - self.loop = function (cb) { - var end = false; - var ender = function () { end = true }; - while (end === false) { - cb.call(self, ender, vars.store); - } - return self; - }; - - self.buffer = function (name, size) { - if (typeof size === 'string') { - size = vars.get(size); - } - var buf = buffer.slice(offset, Math.min(buffer.length, offset + size)); - offset += size; - vars.set(name, buf); - - return self; - }; - - self.skip = function (bytes) { - if (typeof bytes === 'string') { - bytes = vars.get(bytes); - } - offset += bytes; - - return self; - }; - - self.scan = function (name, search) { - if (typeof search === 'string') { - search = new Buffer(search); - } - else if (!Buffer.isBuffer(search)) { - throw new Error('search must be a Buffer or a string'); - } - vars.set(name, null); - - // simple but slow string search - for (var i = 0; i + offset <= buffer.length - search.length + 1; i++) { - for ( - var j = 0; - j < search.length && buffer[offset+i+j] === search[j]; - j++ - ); - if (j === search.length) break; - } - - vars.set(name, buffer.slice(offset, offset + i)); - offset += i + search.length; - return self; - }; - - self.peek = function (cb) { - var was = offset; - cb.call(self, vars.store); - offset = was; - return self; - }; - - self.flush = function () { - vars.store = {}; - return self; - }; - - self.eof = function () { - return offset >= buffer.length; - }; - - return self; -}; + // Remove unshift functions + delete q.unshift; + delete q.unshiftAsync; -// convert byte strings to unsigned little endian numbers -function decodeLEu (bytes) { - var acc = 0; - for (var i = 0; i < bytes.length; i++) { - acc += Math.pow(256,i) * bytes[i]; + return q; } - return acc; -} -// convert byte strings to unsigned big endian numbers -function decodeBEu (bytes) { - var acc = 0; - for (var i = 0; i < bytes.length; i++) { - acc += Math.pow(256, bytes.length - i - 1) * bytes[i]; + /** + * Runs the `tasks` array of functions in parallel, without waiting until the + * previous function has completed. Once any of the `tasks` complete or pass an + * error to its callback, the main `callback` is immediately called. It's + * equivalent to `Promise.race()`. + * + * @name race + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} + * to run. Each function can complete with an optional `result` value. + * @param {Function} callback - A callback to run once any of the functions have + * completed. This function gets an error or result from the first function that + * completed. Invoked with (err, result). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * async.race([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // main callback + * function(err, result) { + * // the result will be equal to 'two' as it finishes earlier + * }); + */ + function race(tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); + if (!tasks.length) return callback(); + for (var i = 0, l = tasks.length; i < l; i++) { + wrapAsync(tasks[i])(callback); + } } - return acc; -} -// convert byte strings to signed big endian numbers -function decodeBEs (bytes) { - var val = decodeBEu(bytes); - if ((bytes[0] & 0x80) == 0x80) { - val -= Math.pow(256, bytes.length); - } - return val; -} + var race$1 = awaitify(race, 2); -// convert byte strings to signed little endian numbers -function decodeLEs (bytes) { - var val = decodeLEu(bytes); - if ((bytes[bytes.length - 1] & 0x80) == 0x80) { - val -= Math.pow(256, bytes.length); + /** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee completes with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + */ + function reduceRight (array, memo, iteratee, callback) { + var reversed = [...array].reverse(); + return reduce$1(reversed, memo, iteratee, callback); } - return val; -} - -function words (decode) { - var self = {}; - - [ 1, 2, 4, 8 ].forEach(function (bytes) { - var bits = bytes * 8; - - self['word' + bits + 'le'] - = self['word' + bits + 'lu'] - = decode(bytes, decodeLEu); - - self['word' + bits + 'ls'] - = decode(bytes, decodeLEs); - - self['word' + bits + 'be'] - = self['word' + bits + 'bu'] - = decode(bytes, decodeBEu); - - self['word' + bits + 'bs'] - = decode(bytes, decodeBEs); - }); - - // word8be(n) == word8le(n) for all n - self.word8 = self.word8u = self.word8be; - self.word8s = self.word8bs; - - return self; -} - - -/***/ }), -/***/ 25738: -/***/ ((module) => { + /** + * Wraps the async function in another function that always completes with a + * result object, even when it errors. + * + * The result object has either the property `error` or `value`. + * + * @name reflect + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function you want to wrap + * @returns {Function} - A function that always passes null to it's callback as + * the error. The second argument to the callback will be an `object` with + * either an `error` or a `value` property. + * @example + * + * async.parallel([ + * async.reflect(function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }), + * async.reflect(function(callback) { + * // do some more stuff but error ... + * callback('bad stuff happened'); + * }), + * async.reflect(function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * }) + * ], + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = 'bad stuff happened' + * // results[2].value = 'two' + * }); + */ + function reflect(fn) { + var _fn = wrapAsync(fn); + return initialParams(function reflectOn(args, reflectCallback) { + args.push((error, ...cbArgs) => { + let retVal = {}; + if (error) { + retVal.error = error; + } + if (cbArgs.length > 0){ + var value = cbArgs; + if (cbArgs.length <= 1) { + [value] = cbArgs; + } + retVal.value = value; + } + reflectCallback(null, retVal); + }); -module.exports = function (store) { - function getset (name, value) { - var node = vars.store; - var keys = name.split('.'); - keys.slice(0,-1).forEach(function (k) { - if (node[k] === undefined) node[k] = {}; - node = node[k] + return _fn.apply(this, args); }); - var key = keys[keys.length - 1]; - if (arguments.length == 1) { - return node[key]; - } - else { - return node[key] = value; - } } - - var vars = { - get : function (name) { - return getset(name); - }, - set : function (name, value) { - return getset(name, value); - }, - store : store || {}, - }; - return vars; -}; - - -/***/ }), -/***/ 15710: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** + * A helper function that wraps an array or an object of functions with `reflect`. + * + * @name reflectAll + * @static + * @memberOf module:Utils + * @method + * @see [async.reflect]{@link module:Utils.reflect} + * @category Util + * @param {Array|Object|Iterable} tasks - The collection of + * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. + * @returns {Array} Returns an array of async functions, each wrapped in + * `async.reflect` + * @example + * + * let tasks = [ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * // do some more stuff but error ... + * callback(new Error('bad stuff happened')); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = Error('bad stuff happened') + * // results[2].value = 'two' + * }); + * + * // an example using an object instead of an array + * let tasks = { + * one: function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * two: function(callback) { + * callback('two'); + * }, + * three: function(callback) { + * setTimeout(function() { + * callback(null, 'three'); + * }, 100); + * } + * }; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results.one.value = 'one' + * // results.two.error = 'two' + * // results.three.value = 'three' + * }); + */ + function reflectAll(tasks) { + var results; + if (Array.isArray(tasks)) { + results = tasks.map(reflect); + } else { + results = {}; + Object.keys(tasks).forEach(key => { + results[key] = reflect.call(this, tasks[key]); + }); + } + return results; + } -"use strict"; + function reject$2(eachfn, arr, _iteratee, callback) { + const iteratee = wrapAsync(_iteratee); + return _filter(eachfn, arr, (value, cb) => { + iteratee(value, (err, v) => { + cb(err, !v); + }); + }, callback); + } + /** + * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. + * + * @name reject + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.reject(fileList, fileExists, function(err, results) { + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * }); + * + * // Using Promises + * async.reject(fileList, fileExists) + * .then( results => { + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.reject(fileList, fileExists); + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function reject (coll, iteratee, callback) { + return reject$2(eachOf$1, coll, iteratee, callback) + } + var reject$1 = awaitify(reject, 3); -const { Buffer } = __nccwpck_require__(14300) -const symbol = Symbol.for('BufferList') + /** + * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a + * time. + * + * @name rejectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function rejectLimit (coll, limit, iteratee, callback) { + return reject$2(eachOfLimit$2(limit), coll, iteratee, callback) + } + var rejectLimit$1 = awaitify(rejectLimit, 4); -function BufferList (buf) { - if (!(this instanceof BufferList)) { - return new BufferList(buf) - } - - BufferList._init.call(this, buf) -} - -BufferList._init = function _init (buf) { - Object.defineProperty(this, symbol, { value: true }) - - this._bufs = [] - this.length = 0 - - if (buf) { - this.append(buf) - } -} - -BufferList.prototype._new = function _new (buf) { - return new BufferList(buf) -} - -BufferList.prototype._offset = function _offset (offset) { - if (offset === 0) { - return [0, 0] - } - - let tot = 0 - - for (let i = 0; i < this._bufs.length; i++) { - const _t = tot + this._bufs[i].length - if (offset < _t || i === this._bufs.length - 1) { - return [i, offset - tot] - } - tot = _t - } -} - -BufferList.prototype._reverseOffset = function (blOffset) { - const bufferId = blOffset[0] - let offset = blOffset[1] - - for (let i = 0; i < bufferId; i++) { - offset += this._bufs[i].length - } - - return offset -} - -BufferList.prototype.get = function get (index) { - if (index > this.length || index < 0) { - return undefined - } - - const offset = this._offset(index) - - return this._bufs[offset[0]][offset[1]] -} - -BufferList.prototype.slice = function slice (start, end) { - if (typeof start === 'number' && start < 0) { - start += this.length - } - - if (typeof end === 'number' && end < 0) { - end += this.length - } - - return this.copy(null, 0, start, end) -} - -BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) { - if (typeof srcStart !== 'number' || srcStart < 0) { - srcStart = 0 - } - - if (typeof srcEnd !== 'number' || srcEnd > this.length) { - srcEnd = this.length - } - - if (srcStart >= this.length) { - return dst || Buffer.alloc(0) - } - - if (srcEnd <= 0) { - return dst || Buffer.alloc(0) - } - - const copy = !!dst - const off = this._offset(srcStart) - const len = srcEnd - srcStart - let bytes = len - let bufoff = (copy && dstStart) || 0 - let start = off[1] - - // copy/slice everything - if (srcStart === 0 && srcEnd === this.length) { - if (!copy) { - // slice, but full concat if multiple buffers - return this._bufs.length === 1 - ? this._bufs[0] - : Buffer.concat(this._bufs, this.length) - } - - // copy, need to copy individual buffers - for (let i = 0; i < this._bufs.length; i++) { - this._bufs[i].copy(dst, bufoff) - bufoff += this._bufs[i].length - } - - return dst - } - - // easy, cheap case where it's a subset of one of the buffers - if (bytes <= this._bufs[off[0]].length - start) { - return copy - ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) - : this._bufs[off[0]].slice(start, start + bytes) - } - - if (!copy) { - // a slice, we need something to copy in to - dst = Buffer.allocUnsafe(len) - } - - for (let i = off[0]; i < this._bufs.length; i++) { - const l = this._bufs[i].length - start - - if (bytes > l) { - this._bufs[i].copy(dst, bufoff, start) - bufoff += l - } else { - this._bufs[i].copy(dst, bufoff, start, start + bytes) - bufoff += l - break + /** + * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. + * + * @name rejectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function rejectSeries (coll, iteratee, callback) { + return reject$2(eachOfSeries$1, coll, iteratee, callback) } + var rejectSeries$1 = awaitify(rejectSeries, 3); - bytes -= l - - if (start) { - start = 0 + function constant(value) { + return function () { + return value; + } } - } - // safeguard so that we don't return uninitialized memory - if (dst.length > bufoff) return dst.slice(0, bufoff) - - return dst -} - -BufferList.prototype.shallowSlice = function shallowSlice (start, end) { - start = start || 0 - end = typeof end !== 'number' ? this.length : end - - if (start < 0) { - start += this.length - } - - if (end < 0) { - end += this.length - } - - if (start === end) { - return this._new() - } - - const startOffset = this._offset(start) - const endOffset = this._offset(end) - const buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1) + /** + * Attempts to get a successful response from `task` no more than `times` times + * before returning an error. If the task is successful, the `callback` will be + * passed the result of the successful task. If all attempts fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name retry + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @see [async.retryable]{@link module:ControlFlow.retryable} + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an + * object with `times` and `interval` or a number. + * * `times` - The number of attempts to make before giving up. The default + * is `5`. + * * `interval` - The time to wait between retries, in milliseconds. The + * default is `0`. The interval may also be specified as a function of the + * retry count (see example). + * * `errorFilter` - An optional synchronous function that is invoked on + * erroneous result. If it returns `true` the retry attempts will continue; + * if the function returns `false` the retry flow is aborted with the current + * attempt's error and result being returned to the final callback. + * Invoked with (err). + * * If `opts` is a number, the number specifies the number of times to retry, + * with the default interval of `0`. + * @param {AsyncFunction} task - An async function to retry. + * Invoked with (callback). + * @param {Function} [callback] - An optional callback which is called when the + * task has succeeded, or after the final failed attempt. It receives the `err` + * and `result` arguments of the last attempt at completing the `task`. Invoked + * with (err, results). + * @returns {Promise} a promise if no callback provided + * + * @example + * + * // The `retry` function can be used as a stand-alone control flow by passing + * // a callback, as shown below: + * + * // try calling apiMethod 3 times + * async.retry(3, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 3 times, waiting 200 ms between each retry + * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 10 times with exponential backoff + * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) + * async.retry({ + * times: 10, + * interval: function(retryCount) { + * return 50 * Math.pow(2, retryCount); + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod the default 5 times no delay between each retry + * async.retry(apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod only when error condition satisfies, all other + * // errors will abort the retry control flow and return to final callback + * async.retry({ + * errorFilter: function(err) { + * return err.message === 'Temporary error'; // only retry on a specific error + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // to retry individual methods that are not as reliable within other + * // control flow functions, use the `retryable` wrapper: + * async.auto({ + * users: api.getUsers.bind(api), + * payments: async.retryable(3, api.getPayments.bind(api)) + * }, function(err, results) { + * // do something with the results + * }); + * + */ + const DEFAULT_TIMES = 5; + const DEFAULT_INTERVAL = 0; - if (endOffset[1] === 0) { - buffers.pop() - } else { - buffers[buffers.length - 1] = buffers[buffers.length - 1].slice(0, endOffset[1]) - } + function retry(opts, task, callback) { + var options = { + times: DEFAULT_TIMES, + intervalFunc: constant(DEFAULT_INTERVAL) + }; - if (startOffset[1] !== 0) { - buffers[0] = buffers[0].slice(startOffset[1]) - } + if (arguments.length < 3 && typeof opts === 'function') { + callback = task || promiseCallback(); + task = opts; + } else { + parseTimes(options, opts); + callback = callback || promiseCallback(); + } - return this._new(buffers) -} + if (typeof task !== 'function') { + throw new Error("Invalid arguments for async.retry"); + } -BufferList.prototype.toString = function toString (encoding, start, end) { - return this.slice(start, end).toString(encoding) -} + var _task = wrapAsync(task); -BufferList.prototype.consume = function consume (bytes) { - // first, normalize the argument, in accordance with how Buffer does it - bytes = Math.trunc(bytes) - // do nothing if not a positive number - if (Number.isNaN(bytes) || bytes <= 0) return this + var attempt = 1; + function retryAttempt() { + _task((err, ...args) => { + if (err === false) return + if (err && attempt++ < options.times && + (typeof options.errorFilter != 'function' || + options.errorFilter(err))) { + setTimeout(retryAttempt, options.intervalFunc(attempt - 1)); + } else { + callback(err, ...args); + } + }); + } - while (this._bufs.length) { - if (bytes >= this._bufs[0].length) { - bytes -= this._bufs[0].length - this.length -= this._bufs[0].length - this._bufs.shift() - } else { - this._bufs[0] = this._bufs[0].slice(bytes) - this.length -= bytes - break + retryAttempt(); + return callback[PROMISE_SYMBOL] } - } - - return this -} - -BufferList.prototype.duplicate = function duplicate () { - const copy = this._new() - for (let i = 0; i < this._bufs.length; i++) { - copy.append(this._bufs[i]) - } - - return copy -} + function parseTimes(acc, t) { + if (typeof t === 'object') { + acc.times = +t.times || DEFAULT_TIMES; -BufferList.prototype.append = function append (buf) { - if (buf == null) { - return this - } + acc.intervalFunc = typeof t.interval === 'function' ? + t.interval : + constant(+t.interval || DEFAULT_INTERVAL); - if (buf.buffer) { - // append a view of the underlying ArrayBuffer - this._appendBuffer(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)) - } else if (Array.isArray(buf)) { - for (let i = 0; i < buf.length; i++) { - this.append(buf[i]) - } - } else if (this._isBufferList(buf)) { - // unwrap argument into individual BufferLists - for (let i = 0; i < buf._bufs.length; i++) { - this.append(buf._bufs[i]) - } - } else { - // coerce number arguments to strings, since Buffer(number) does - // uninitialized memory allocation - if (typeof buf === 'number') { - buf = buf.toString() + acc.errorFilter = t.errorFilter; + } else if (typeof t === 'number' || typeof t === 'string') { + acc.times = +t || DEFAULT_TIMES; + } else { + throw new Error("Invalid arguments for async.retry"); + } } - this._appendBuffer(Buffer.from(buf)) - } - - return this -} - -BufferList.prototype._appendBuffer = function appendBuffer (buf) { - this._bufs.push(buf) - this.length += buf.length -} - -BufferList.prototype.indexOf = function (search, offset, encoding) { - if (encoding === undefined && typeof offset === 'string') { - encoding = offset - offset = undefined - } - - if (typeof search === 'function' || Array.isArray(search)) { - throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.') - } else if (typeof search === 'number') { - search = Buffer.from([search]) - } else if (typeof search === 'string') { - search = Buffer.from(search, encoding) - } else if (this._isBufferList(search)) { - search = search.slice() - } else if (Array.isArray(search.buffer)) { - search = Buffer.from(search.buffer, search.byteOffset, search.byteLength) - } else if (!Buffer.isBuffer(search)) { - search = Buffer.from(search) - } - - offset = Number(offset || 0) - - if (isNaN(offset)) { - offset = 0 - } - - if (offset < 0) { - offset = this.length + offset - } - - if (offset < 0) { - offset = 0 - } - - if (search.length === 0) { - return offset > this.length ? this.length : offset - } - - const blOffset = this._offset(offset) - let blIndex = blOffset[0] // index of which internal buffer we're working on - let buffOffset = blOffset[1] // offset of the internal buffer we're working on - - // scan over each buffer - for (; blIndex < this._bufs.length; blIndex++) { - const buff = this._bufs[blIndex] - - while (buffOffset < buff.length) { - const availableWindow = buff.length - buffOffset - - if (availableWindow >= search.length) { - const nativeSearchResult = buff.indexOf(search, buffOffset) - - if (nativeSearchResult !== -1) { - return this._reverseOffset([blIndex, nativeSearchResult]) + /** + * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method + * wraps a task and makes it retryable, rather than immediately calling it + * with retries. + * + * @name retryable + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.retry]{@link module:ControlFlow.retry} + * @category Control Flow + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional + * options, exactly the same as from `retry`, except for a `opts.arity` that + * is the arity of the `task` function, defaulting to `task.length` + * @param {AsyncFunction} task - the asynchronous function to wrap. + * This function will be passed any arguments passed to the returned wrapper. + * Invoked with (...args, callback). + * @returns {AsyncFunction} The wrapped function, which when invoked, will + * retry on an error, based on the parameters specified in `opts`. + * This function will accept the same parameters as `task`. + * @example + * + * async.auto({ + * dep1: async.retryable(3, getFromFlakyService), + * process: ["dep1", async.retryable(3, function (results, cb) { + * maybeProcessData(results.dep1, cb); + * })] + * }, callback); + */ + function retryable (opts, task) { + if (!task) { + task = opts; + opts = null; } - - buffOffset = buff.length - search.length + 1 // end of native search window - } else { - const revOffset = this._reverseOffset([blIndex, buffOffset]) - - if (this._match(revOffset, search)) { - return revOffset + let arity = (opts && opts.arity) || task.length; + if (isAsync(task)) { + arity += 1; } + var _task = wrapAsync(task); + return initialParams((args, callback) => { + if (args.length < arity - 1 || callback == null) { + args.push(callback); + callback = promiseCallback(); + } + function taskFn(cb) { + _task(...args, cb); + } - buffOffset++ - } - } - - buffOffset = 0 - } - - return -1 -} - -BufferList.prototype._match = function (offset, search) { - if (this.length - offset < search.length) { - return false - } + if (opts) retry(opts, taskFn, callback); + else retry(taskFn, callback); - for (let searchOffset = 0; searchOffset < search.length; searchOffset++) { - if (this.get(offset + searchOffset) !== search[searchOffset]) { - return false + return callback[PROMISE_SYMBOL] + }); } - } - return true -} - -;(function () { - const methods = { - readDoubleBE: 8, - readDoubleLE: 8, - readFloatBE: 4, - readFloatLE: 4, - readInt32BE: 4, - readInt32LE: 4, - readUInt32BE: 4, - readUInt32LE: 4, - readInt16BE: 2, - readInt16LE: 2, - readUInt16BE: 2, - readUInt16LE: 2, - readInt8: 1, - readUInt8: 1, - readIntBE: null, - readIntLE: null, - readUIntBE: null, - readUIntLE: null - } - - for (const m in methods) { - (function (m) { - if (methods[m] === null) { - BufferList.prototype[m] = function (offset, byteLength) { - return this.slice(offset, offset + byteLength)[m](0, byteLength) - } - } else { - BufferList.prototype[m] = function (offset = 0) { - return this.slice(offset, offset + methods[m])[m](0) - } - } - }(m)) - } -}()) - -// Used internally by the class and also as an indicator of this object being -// a `BufferList`. It's not possible to use `instanceof BufferList` in a browser -// environment because there could be multiple different copies of the -// BufferList class and some `BufferList`s might be `BufferList`s. -BufferList.prototype._isBufferList = function _isBufferList (b) { - return b instanceof BufferList || BufferList.isBufferList(b) -} - -BufferList.isBufferList = function isBufferList (b) { - return b != null && b[symbol] -} - -module.exports = BufferList - - -/***/ }), - -/***/ 69056: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const DuplexStream = (__nccwpck_require__(84123).Duplex) -const inherits = __nccwpck_require__(42991) -const BufferList = __nccwpck_require__(15710) - -function BufferListStream (callback) { - if (!(this instanceof BufferListStream)) { - return new BufferListStream(callback) - } - - if (typeof callback === 'function') { - this._callback = callback - - const piper = function piper (err) { - if (this._callback) { - this._callback(err) - this._callback = null - } - }.bind(this) - - this.on('pipe', function onPipe (src) { - src.on('error', piper) - }) - this.on('unpipe', function onUnpipe (src) { - src.removeListener('error', piper) - }) - - callback = null - } - - BufferList._init.call(this, callback) - DuplexStream.call(this) -} - -inherits(BufferListStream, DuplexStream) -Object.assign(BufferListStream.prototype, BufferList.prototype) - -BufferListStream.prototype._new = function _new (callback) { - return new BufferListStream(callback) -} - -BufferListStream.prototype._write = function _write (buf, encoding, callback) { - this._appendBuffer(buf) - - if (typeof callback === 'function') { - callback() - } -} - -BufferListStream.prototype._read = function _read (size) { - if (!this.length) { - return this.push(null) - } - - size = Math.min(size, this.length) - this.push(this.slice(0, size)) - this.consume(size) -} - -BufferListStream.prototype.end = function end (chunk) { - DuplexStream.prototype.end.call(this, chunk) - - if (this._callback) { - this._callback(null, this.slice()) - this._callback = null - } -} - -BufferListStream.prototype._destroy = function _destroy (err, cb) { - this._bufs.length = 0 - this.length = 0 - cb(err) -} - -BufferListStream.prototype._isBufferList = function _isBufferList (b) { - return b instanceof BufferListStream || b instanceof BufferList || BufferListStream.isBufferList(b) -} - -BufferListStream.isBufferList = BufferList.isBufferList - -module.exports = BufferListStream -module.exports.BufferListStream = BufferListStream -module.exports.BufferList = BufferList - - -/***/ }), - -/***/ 67044: -/***/ ((module) => { - -"use strict"; - -module.exports = function(Promise) { -var SomePromiseArray = Promise._SomePromiseArray; -function any(promises) { - var ret = new SomePromiseArray(promises); - var promise = ret.promise(); - ret.setHowMany(1); - ret.setUnwrap(); - ret.init(); - return promise; -} - -Promise.any = function (promises) { - return any(promises); -}; - -Promise.prototype.any = function () { - return any(this); -}; - -}; - - -/***/ }), - -/***/ 66812: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var firstLineError; -try {throw new Error(); } catch (e) {firstLineError = e;} -var schedule = __nccwpck_require__(73484); -var Queue = __nccwpck_require__(36872); -var util = __nccwpck_require__(37180); - -function Async() { - this._customScheduler = false; - this._isTickUsed = false; - this._lateQueue = new Queue(16); - this._normalQueue = new Queue(16); - this._haveDrainedQueues = false; - this._trampolineEnabled = true; - var self = this; - this.drainQueues = function () { - self._drainQueues(); - }; - this._schedule = schedule; -} - -Async.prototype.setScheduler = function(fn) { - var prev = this._schedule; - this._schedule = fn; - this._customScheduler = true; - return prev; -}; - -Async.prototype.hasCustomScheduler = function() { - return this._customScheduler; -}; - -Async.prototype.enableTrampoline = function() { - this._trampolineEnabled = true; -}; -Async.prototype.disableTrampolineIfNecessary = function() { - if (util.hasDevTools) { - this._trampolineEnabled = false; + /** + * Run the functions in the `tasks` collection in series, each one running once + * the previous function has completed. If any functions in the series pass an + * error to its callback, no more functions are run, and `callback` is + * immediately called with the value of the error. Otherwise, `callback` + * receives an array of results when `tasks` have completed. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function, and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.series}. + * + * **Note** that while many implementations preserve the order of object + * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) + * explicitly states that + * + * > The mechanics and order of enumerating the properties is not specified. + * + * So if you rely on the order in which your series of functions are executed, + * and want this to work on all platforms, consider using an array. + * + * @name series + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing + * [async functions]{@link AsyncFunction} to run in series. + * Each function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This function gets a results array (or object) + * containing all the result arguments passed to the `task` callbacks. Invoked + * with (err, result). + * @return {Promise} a promise, if no callback is passed + * @example + * + * //Using Callbacks + * async.series([ + * function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); + * } + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] + * }); + * + * // an example using objects instead of arrays + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }); + * + * //Using Promises + * async.series([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] + * }).catch(err => { + * console.log(err); + * }); + * + * // an example using an object instead of an array + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.series([ + * function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function series(tasks, callback) { + return _parallel(eachOfSeries$1, tasks, callback); } -}; - -Async.prototype.haveItemsQueued = function () { - return this._isTickUsed || this._haveDrainedQueues; -}; - -Async.prototype.fatalError = function(e, isNode) { - if (isNode) { - process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) + - "\n"); - process.exit(2); - } else { - this.throwLater(e); + /** + * Returns `true` if at least one element in the `coll` satisfies an async test. + * If any iteratee call returns `true`, the main `callback` is immediately + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + *); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // false + * // result is false since none of the files exists + * } + *); + * + * // Using Promises + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since some file in the list exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since none of the files exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists); + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists); + * console.log(result); + * // false + * // result is false since none of the files exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function some(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOf$1, coll, iteratee, callback) } -}; + var some$1 = awaitify(some, 3); -Async.prototype.throwLater = function(fn, arg) { - if (arguments.length === 1) { - arg = fn; - fn = function () { throw arg; }; - } - if (typeof setTimeout !== "undefined") { - setTimeout(function() { - fn(arg); - }, 0); - } else try { - this._schedule(function() { - fn(arg); - }); - } catch (e) { - throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + /** + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function someLimit(coll, limit, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfLimit$2(limit), coll, iteratee, callback) } -}; - -function AsyncInvokeLater(fn, receiver, arg) { - this._lateQueue.push(fn, receiver, arg); - this._queueTick(); -} - -function AsyncInvoke(fn, receiver, arg) { - this._normalQueue.push(fn, receiver, arg); - this._queueTick(); -} - -function AsyncSettlePromises(promise) { - this._normalQueue._pushOne(promise); - this._queueTick(); -} + var someLimit$1 = awaitify(someLimit, 4); -if (!util.hasDevTools) { - Async.prototype.invokeLater = AsyncInvokeLater; - Async.prototype.invoke = AsyncInvoke; - Async.prototype.settlePromises = AsyncSettlePromises; -} else { - Async.prototype.invokeLater = function (fn, receiver, arg) { - if (this._trampolineEnabled) { - AsyncInvokeLater.call(this, fn, receiver, arg); - } else { - this._schedule(function() { - setTimeout(function() { - fn.call(receiver, arg); - }, 100); - }); - } - }; + /** + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function someSeries(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfSeries$1, coll, iteratee, callback) + } + var someSeries$1 = awaitify(someSeries, 3); - Async.prototype.invoke = function (fn, receiver, arg) { - if (this._trampolineEnabled) { - AsyncInvoke.call(this, fn, receiver, arg); - } else { - this._schedule(function() { - fn.call(receiver, arg); - }); - } - }; - - Async.prototype.settlePromises = function(promise) { - if (this._trampolineEnabled) { - AsyncSettlePromises.call(this, promise); - } else { - this._schedule(function() { - promise._settlePromises(); + /** + * Sorts a list by the results of running each `coll` value through an async + * `iteratee`. + * + * @name sortBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a value to use as the sort criteria as + * its `result`. + * Invoked with (item, callback). + * @param {Function} callback - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is the items + * from the original `coll` sorted by the values returned by the `iteratee` + * calls. Invoked with (err, results). + * @returns {Promise} a promise, if no callback passed + * @example + * + * // bigfile.txt is a file that is 251100 bytes in size + * // mediumfile.txt is a file that is 11000 bytes in size + * // smallfile.txt is a file that is 121 bytes in size + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); + * + * // By modifying the callback parameter the + * // sorting order can be influenced: + * + * // ascending order + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) return callback(getFileSizeErr); + * callback(null, fileSize); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); + * + * // descending order + * async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) { + * return callback(getFileSizeErr); + * } + * callback(null, fileSize * -1); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'bigfile.txt', 'mediumfile.txt', 'smallfile.txt'] + * } + * } + * ); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * } + * ); + * + * // Using Promises + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * }).catch( err => { + * console.log(err); + * }); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * (async () => { + * try { + * let results = await async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * // Error handling + * async () => { + * try { + * let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ + function sortBy (coll, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return map$1(coll, (x, iterCb) => { + _iteratee(x, (err, criteria) => { + if (err) return iterCb(err); + iterCb(err, {value: x, criteria}); }); - } - }; -} - -Async.prototype._drainQueue = function(queue) { - while (queue.length() > 0) { - var fn = queue.shift(); - if (typeof fn !== "function") { - fn._settlePromises(); - continue; - } - var receiver = queue.shift(); - var arg = queue.shift(); - fn.call(receiver, arg); - } -}; - -Async.prototype._drainQueues = function () { - this._drainQueue(this._normalQueue); - this._reset(); - this._haveDrainedQueues = true; - this._drainQueue(this._lateQueue); -}; - -Async.prototype._queueTick = function () { - if (!this._isTickUsed) { - this._isTickUsed = true; - this._schedule(this.drainQueues); - } -}; - -Async.prototype._reset = function () { - this._isTickUsed = false; -}; - -module.exports = Async; -module.exports.firstLineError = firstLineError; - - -/***/ }), - -/***/ 4999: -/***/ ((module) => { - -"use strict"; - -module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { -var calledBind = false; -var rejectThis = function(_, e) { - this._reject(e); -}; - -var targetRejected = function(e, context) { - context.promiseRejectionQueued = true; - context.bindingPromise._then(rejectThis, rejectThis, null, this, e); -}; - -var bindingResolved = function(thisArg, context) { - if (((this._bitField & 50397184) === 0)) { - this._resolveCallback(context.target); - } -}; - -var bindingRejected = function(e, context) { - if (!context.promiseRejectionQueued) this._reject(e); -}; - -Promise.prototype.bind = function (thisArg) { - if (!calledBind) { - calledBind = true; - Promise.prototype._propagateFrom = debug.propagateFromFunction(); - Promise.prototype._boundValue = debug.boundValueFunction(); - } - var maybePromise = tryConvertToPromise(thisArg); - var ret = new Promise(INTERNAL); - ret._propagateFrom(this, 1); - var target = this._target(); - ret._setBoundTo(maybePromise); - if (maybePromise instanceof Promise) { - var context = { - promiseRejectionQueued: false, - promise: ret, - target: target, - bindingPromise: maybePromise - }; - target._then(INTERNAL, targetRejected, undefined, ret, context); - maybePromise._then( - bindingResolved, bindingRejected, undefined, ret, context); - ret._setOnCancel(maybePromise); - } else { - ret._resolveCallback(target); - } - return ret; -}; - -Promise.prototype._setBoundTo = function (obj) { - if (obj !== undefined) { - this._bitField = this._bitField | 2097152; - this._boundTo = obj; - } else { - this._bitField = this._bitField & (~2097152); - } -}; - -Promise.prototype._isBound = function () { - return (this._bitField & 2097152) === 2097152; -}; - -Promise.bind = function (thisArg, value) { - return Promise.resolve(value).bind(thisArg); -}; -}; - - -/***/ }), - -/***/ 94453: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var old; -if (typeof Promise !== "undefined") old = Promise; -function noConflict() { - try { if (Promise === bluebird) Promise = old; } - catch (e) {} - return bluebird; -} -var bluebird = __nccwpck_require__(73807)(); -bluebird.noConflict = noConflict; -module.exports = bluebird; - - -/***/ }), - -/***/ 89343: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var cr = Object.create; -if (cr) { - var callerCache = cr(null); - var getterCache = cr(null); - callerCache[" size"] = getterCache[" size"] = 0; -} - -module.exports = function(Promise) { -var util = __nccwpck_require__(37180); -var canEvaluate = util.canEvaluate; -var isIdentifier = util.isIdentifier; - -var getMethodCaller; -var getGetter; -if (true) { -var makeMethodCaller = function (methodName) { - return new Function("ensureMethod", " \n\ - return function(obj) { \n\ - 'use strict' \n\ - var len = this.length; \n\ - ensureMethod(obj, 'methodName'); \n\ - switch(len) { \n\ - case 1: return obj.methodName(this[0]); \n\ - case 2: return obj.methodName(this[0], this[1]); \n\ - case 3: return obj.methodName(this[0], this[1], this[2]); \n\ - case 0: return obj.methodName(); \n\ - default: \n\ - return obj.methodName.apply(obj, this); \n\ - } \n\ - }; \n\ - ".replace(/methodName/g, methodName))(ensureMethod); -}; - -var makeGetter = function (propertyName) { - return new Function("obj", " \n\ - 'use strict'; \n\ - return obj.propertyName; \n\ - ".replace("propertyName", propertyName)); -}; - -var getCompiled = function(name, compiler, cache) { - var ret = cache[name]; - if (typeof ret !== "function") { - if (!isIdentifier(name)) { - return null; - } - ret = compiler(name); - cache[name] = ret; - cache[" size"]++; - if (cache[" size"] > 512) { - var keys = Object.keys(cache); - for (var i = 0; i < 256; ++i) delete cache[keys[i]]; - cache[" size"] = keys.length - 256; - } - } - return ret; -}; - -getMethodCaller = function(name) { - return getCompiled(name, makeMethodCaller, callerCache); -}; - -getGetter = function(name) { - return getCompiled(name, makeGetter, getterCache); -}; -} - -function ensureMethod(obj, methodName) { - var fn; - if (obj != null) fn = obj[methodName]; - if (typeof fn !== "function") { - var message = "Object " + util.classString(obj) + " has no method '" + - util.toString(methodName) + "'"; - throw new Promise.TypeError(message); - } - return fn; -} - -function caller(obj) { - var methodName = this.pop(); - var fn = ensureMethod(obj, methodName); - return fn.apply(obj, this); -} -Promise.prototype.call = function (methodName) { - var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}; - if (true) { - if (canEvaluate) { - var maybeCaller = getMethodCaller(methodName); - if (maybeCaller !== null) { - return this._then( - maybeCaller, undefined, undefined, args, undefined); - } - } - } - args.push(methodName); - return this._then(caller, undefined, undefined, args, undefined); -}; - -function namedGetter(obj) { - return obj[this]; -} -function indexedGetter(obj) { - var index = +this; - if (index < 0) index = Math.max(0, index + obj.length); - return obj[index]; -} -Promise.prototype.get = function (propertyName) { - var isIndex = (typeof propertyName === "number"); - var getter; - if (!isIndex) { - if (canEvaluate) { - var maybeGetter = getGetter(propertyName); - getter = maybeGetter !== null ? maybeGetter : namedGetter; - } else { - getter = namedGetter; - } - } else { - getter = indexedGetter; - } - return this._then(getter, undefined, undefined, propertyName, undefined); -}; -}; - - -/***/ }), - -/***/ 27862: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = function(Promise, PromiseArray, apiRejection, debug) { -var util = __nccwpck_require__(37180); -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -var async = Promise._async; - -Promise.prototype["break"] = Promise.prototype.cancel = function() { - if (!debug.cancellation()) return this._warn("cancellation is disabled"); - - var promise = this; - var child = promise; - while (promise._isCancellable()) { - if (!promise._cancelBy(child)) { - if (child._isFollowing()) { - child._followee().cancel(); - } else { - child._cancelBranched(); - } - break; - } - - var parent = promise._cancellationParent; - if (parent == null || !parent._isCancellable()) { - if (promise._isFollowing()) { - promise._followee().cancel(); - } else { - promise._cancelBranched(); - } - break; - } else { - if (promise._isFollowing()) promise._followee().cancel(); - promise._setWillBeCancelled(); - child = promise; - promise = parent; - } - } -}; - -Promise.prototype._branchHasCancelled = function() { - this._branchesRemainingToCancel--; -}; - -Promise.prototype._enoughBranchesHaveCancelled = function() { - return this._branchesRemainingToCancel === undefined || - this._branchesRemainingToCancel <= 0; -}; + }, (err, results) => { + if (err) return callback(err); + callback(null, results.sort(comparator).map(v => v.value)); + }); -Promise.prototype._cancelBy = function(canceller) { - if (canceller === this) { - this._branchesRemainingToCancel = 0; - this._invokeOnCancel(); - return true; - } else { - this._branchHasCancelled(); - if (this._enoughBranchesHaveCancelled()) { - this._invokeOnCancel(); - return true; + function comparator(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; } } - return false; -}; - -Promise.prototype._cancelBranched = function() { - if (this._enoughBranchesHaveCancelled()) { - this._cancel(); - } -}; - -Promise.prototype._cancel = function() { - if (!this._isCancellable()) return; - this._setCancelled(); - async.invoke(this._cancelPromises, this, undefined); -}; - -Promise.prototype._cancelPromises = function() { - if (this._length() > 0) this._settlePromises(); -}; - -Promise.prototype._unsetOnCancel = function() { - this._onCancelField = undefined; -}; + var sortBy$1 = awaitify(sortBy, 3); -Promise.prototype._isCancellable = function() { - return this.isPending() && !this._isCancelled(); -}; + /** + * Sets a time limit on an asynchronous function. If the function does not call + * its callback within the specified milliseconds, it will be called with a + * timeout error. The code property for the error object will be `'ETIMEDOUT'`. + * + * @name timeout + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} asyncFn - The async function to limit in time. + * @param {number} milliseconds - The specified time limit. + * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) + * to timeout Error for more information.. + * @returns {AsyncFunction} Returns a wrapped function that can be used with any + * of the control flow functions. + * Invoke this function with the same parameters as you would `asyncFunc`. + * @example + * + * function myFunction(foo, callback) { + * doAsyncTask(foo, function(err, data) { + * // handle errors + * if (err) return callback(err); + * + * // do some stuff ... + * + * // return processed data + * return callback(null, data); + * }); + * } + * + * var wrapped = async.timeout(myFunction, 1000); + * + * // call `wrapped` as you would `myFunction` + * wrapped({ bar: 'bar' }, function(err, data) { + * // if `myFunction` takes < 1000 ms to execute, `err` + * // and `data` will have their expected values + * + * // else `err` will be an Error with the code 'ETIMEDOUT' + * }); + */ + function timeout(asyncFn, milliseconds, info) { + var fn = wrapAsync(asyncFn); -Promise.prototype.isCancellable = function() { - return this.isPending() && !this.isCancelled(); -}; + return initialParams((args, callback) => { + var timedOut = false; + var timer; -Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) { - if (util.isArray(onCancelCallback)) { - for (var i = 0; i < onCancelCallback.length; ++i) { - this._doInvokeOnCancel(onCancelCallback[i], internalOnly); - } - } else if (onCancelCallback !== undefined) { - if (typeof onCancelCallback === "function") { - if (!internalOnly) { - var e = tryCatch(onCancelCallback).call(this._boundValue()); - if (e === errorObj) { - this._attachExtraTrace(e.e); - async.throwLater(e.e); + function timeoutCallback() { + var name = asyncFn.name || 'anonymous'; + var error = new Error('Callback function "' + name + '" timed out.'); + error.code = 'ETIMEDOUT'; + if (info) { + error.info = info; } + timedOut = true; + callback(error); } - } else { - onCancelCallback._resultCancelled(this); - } - } -}; -Promise.prototype._invokeOnCancel = function() { - var onCancelCallback = this._onCancel(); - this._unsetOnCancel(); - async.invoke(this._doInvokeOnCancel, this, onCancelCallback); -}; + args.push((...cbArgs) => { + if (!timedOut) { + callback(...cbArgs); + clearTimeout(timer); + } + }); -Promise.prototype._invokeInternalOnCancel = function() { - if (this._isCancellable()) { - this._doInvokeOnCancel(this._onCancel(), true); - this._unsetOnCancel(); + // setup timer and call original function + timer = setTimeout(timeoutCallback, milliseconds); + fn(...args); + }); } -}; - -Promise.prototype._resultCancelled = function() { - this.cancel(); -}; - -}; - -/***/ }), - -/***/ 87855: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = function(NEXT_FILTER) { -var util = __nccwpck_require__(37180); -var getKeys = (__nccwpck_require__(61713).keys); -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; - -function catchFilter(instances, cb, promise) { - return function(e) { - var boundTo = promise._boundValue(); - predicateLoop: for (var i = 0; i < instances.length; ++i) { - var item = instances[i]; - - if (item === Error || - (item != null && item.prototype instanceof Error)) { - if (e instanceof item) { - return tryCatch(cb).call(boundTo, e); - } - } else if (typeof item === "function") { - var matchesPredicate = tryCatch(item).call(boundTo, e); - if (matchesPredicate === errorObj) { - return matchesPredicate; - } else if (matchesPredicate) { - return tryCatch(cb).call(boundTo, e); - } - } else if (util.isObject(e)) { - var keys = getKeys(item); - for (var j = 0; j < keys.length; ++j) { - var key = keys[j]; - if (item[key] != e[key]) { - continue predicateLoop; - } - } - return tryCatch(cb).call(boundTo, e); - } + function range(size) { + var result = Array(size); + while (size--) { + result[size] = size; } - return NEXT_FILTER; - }; -} - -return catchFilter; -}; - - -/***/ }), - -/***/ 38518: -/***/ ((module) => { - -"use strict"; - -module.exports = function(Promise) { -var longStackTraces = false; -var contextStack = []; - -Promise.prototype._promiseCreated = function() {}; -Promise.prototype._pushContext = function() {}; -Promise.prototype._popContext = function() {return null;}; -Promise._peekContext = Promise.prototype._peekContext = function() {}; - -function Context() { - this._trace = new Context.CapturedTrace(peekContext()); -} -Context.prototype._pushContext = function () { - if (this._trace !== undefined) { - this._trace._promiseCreated = null; - contextStack.push(this._trace); + return result; } -}; -Context.prototype._popContext = function () { - if (this._trace !== undefined) { - var trace = contextStack.pop(); - var ret = trace._promiseCreated; - trace._promiseCreated = null; - return ret; + /** + * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a + * time. + * + * @name timesLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} count - The number of times to run the function. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see [async.map]{@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ + function timesLimit(count, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(range(count), limit, _iteratee, callback); } - return null; -}; - -function createContext() { - if (longStackTraces) return new Context(); -} -function peekContext() { - var lastIndex = contextStack.length - 1; - if (lastIndex >= 0) { - return contextStack[lastIndex]; + /** + * Calls the `iteratee` function `n` times, and accumulates results in the same + * manner you would use with [map]{@link module:Collections.map}. + * + * @name times + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.map]{@link module:Collections.map} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + * @example + * + * // Pretend this is some complicated async factory + * var createUser = function(id, callback) { + * callback(null, { + * id: 'user' + id + * }); + * }; + * + * // generate 5 users + * async.times(5, function(n, next) { + * createUser(n, function(err, user) { + * next(err, user); + * }); + * }, function(err, users) { + * // we should now have 5 users + * }); + */ + function times (n, iteratee, callback) { + return timesLimit(n, Infinity, iteratee, callback) } - return undefined; -} -Context.CapturedTrace = null; -Context.create = createContext; -Context.deactivateLongStackTraces = function() {}; -Context.activateLongStackTraces = function() { - var Promise_pushContext = Promise.prototype._pushContext; - var Promise_popContext = Promise.prototype._popContext; - var Promise_PeekContext = Promise._peekContext; - var Promise_peekContext = Promise.prototype._peekContext; - var Promise_promiseCreated = Promise.prototype._promiseCreated; - Context.deactivateLongStackTraces = function() { - Promise.prototype._pushContext = Promise_pushContext; - Promise.prototype._popContext = Promise_popContext; - Promise._peekContext = Promise_PeekContext; - Promise.prototype._peekContext = Promise_peekContext; - Promise.prototype._promiseCreated = Promise_promiseCreated; - longStackTraces = false; - }; - longStackTraces = true; - Promise.prototype._pushContext = Context.prototype._pushContext; - Promise.prototype._popContext = Context.prototype._popContext; - Promise._peekContext = Promise.prototype._peekContext = peekContext; - Promise.prototype._promiseCreated = function() { - var ctx = this._peekContext(); - if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; - }; -}; -return Context; -}; - - -/***/ }), - -/***/ 30581: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = function(Promise, Context) { -var getDomain = Promise._getDomain; -var async = Promise._async; -var Warning = (__nccwpck_require__(44581).Warning); -var util = __nccwpck_require__(37180); -var canAttachTrace = util.canAttachTrace; -var unhandledRejectionHandled; -var possiblyUnhandledRejection; -var bluebirdFramePattern = - /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; -var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/; -var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/; -var stackFramePattern = null; -var formatStack = null; -var indentStackFrames = false; -var printWarning; -var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && - ( false || - util.env("BLUEBIRD_DEBUG") || - util.env("NODE_ENV") === "development")); -var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && - (debugging || util.env("BLUEBIRD_WARNINGS"))); - -var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && - (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); - -var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && - (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); - -Promise.prototype.suppressUnhandledRejections = function() { - var target = this._target(); - target._bitField = ((target._bitField & (~1048576)) | - 524288); -}; - -Promise.prototype._ensurePossibleRejectionHandled = function () { - if ((this._bitField & 524288) !== 0) return; - this._setRejectionIsUnhandled(); - async.invokeLater(this._notifyUnhandledRejection, this, undefined); -}; - -Promise.prototype._notifyUnhandledRejectionIsHandled = function () { - fireRejectionEvent("rejectionHandled", - unhandledRejectionHandled, undefined, this); -}; - -Promise.prototype._setReturnedNonUndefined = function() { - this._bitField = this._bitField | 268435456; -}; - -Promise.prototype._returnedNonUndefined = function() { - return (this._bitField & 268435456) !== 0; -}; - -Promise.prototype._notifyUnhandledRejection = function () { - if (this._isRejectionUnhandled()) { - var reason = this._settledValue(); - this._setUnhandledRejectionIsNotified(); - fireRejectionEvent("unhandledRejection", - possiblyUnhandledRejection, reason, this); + /** + * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. + * + * @name timesSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ + function timesSeries (n, iteratee, callback) { + return timesLimit(n, 1, iteratee, callback) } -}; -Promise.prototype._setUnhandledRejectionIsNotified = function () { - this._bitField = this._bitField | 262144; -}; - -Promise.prototype._unsetUnhandledRejectionIsNotified = function () { - this._bitField = this._bitField & (~262144); -}; - -Promise.prototype._isUnhandledRejectionNotified = function () { - return (this._bitField & 262144) > 0; -}; - -Promise.prototype._setRejectionIsUnhandled = function () { - this._bitField = this._bitField | 1048576; -}; + /** + * A relative of `reduce`. Takes an Object or Array, and iterates over each + * element in parallel, each step potentially mutating an `accumulator` value. + * The type of the accumulator defaults to the type of collection passed in. + * + * @name transform + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} [accumulator] - The initial state of the transform. If omitted, + * it will default to an empty Object or Array, depending on the type of `coll` + * @param {AsyncFunction} iteratee - A function applied to each item in the + * collection that potentially modifies the accumulator. + * Invoked with (accumulator, item, key, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the transformed accumulator. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); + * }); + * } + * + * // Using callbacks + * async.transform(fileList, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } + * }); + * + * // Using Promises + * async.transform(fileList, transformFileSize) + * .then(result => { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.transform(fileList, transformFileSize); + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileMap = { f1: 'file1.txt', f2: 'file2.txt', f3: 'file3.txt' }; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); + * }); + * } + * + * // Using callbacks + * async.transform(fileMap, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * }); + * + * // Using Promises + * async.transform(fileMap, transformFileSize) + * .then(result => { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.transform(fileMap, transformFileSize); + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function transform (coll, accumulator, iteratee, callback) { + if (arguments.length <= 3 && typeof accumulator === 'function') { + callback = iteratee; + iteratee = accumulator; + accumulator = Array.isArray(coll) ? [] : {}; + } + callback = once(callback || promiseCallback()); + var _iteratee = wrapAsync(iteratee); -Promise.prototype._unsetRejectionIsUnhandled = function () { - this._bitField = this._bitField & (~1048576); - if (this._isUnhandledRejectionNotified()) { - this._unsetUnhandledRejectionIsNotified(); - this._notifyUnhandledRejectionIsHandled(); + eachOf$1(coll, (v, k, cb) => { + _iteratee(accumulator, v, k, cb); + }, err => callback(err, accumulator)); + return callback[PROMISE_SYMBOL] } -}; - -Promise.prototype._isRejectionUnhandled = function () { - return (this._bitField & 1048576) > 0; -}; -Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { - return warn(message, shouldUseOwnTrace, promise || this); -}; + /** + * It runs each task in series but stops whenever any of the functions were + * successful. If one of the tasks were successful, the `callback` will be + * passed the result of the successful task. If all tasks fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name tryEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to + * run, each function is passed a `callback(err, result)` it must call on + * completion with an error `err` (which can be `null`) and an optional `result` + * value. + * @param {Function} [callback] - An optional callback which is called when one + * of the tasks has succeeded, or all have failed. It receives the `err` and + * `result` arguments of the last attempt at completing the `task`. Invoked with + * (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * async.tryEach([ + * function getDataFromFirstWebsite(callback) { + * // Try getting the data from the first website + * callback(err, data); + * }, + * function getDataFromSecondWebsite(callback) { + * // First website failed, + * // Try getting the data from the backup website + * callback(err, data); + * } + * ], + * // optional callback + * function(err, results) { + * Now do something with the data. + * }); + * + */ + function tryEach(tasks, callback) { + var error = null; + var result; + return eachSeries$1(tasks, (task, taskCb) => { + wrapAsync(task)((err, ...args) => { + if (err === false) return taskCb(err); -Promise.onPossiblyUnhandledRejection = function (fn) { - var domain = getDomain(); - possiblyUnhandledRejection = - typeof fn === "function" ? (domain === null ? - fn : util.domainBind(domain, fn)) - : undefined; -}; + if (args.length < 2) { + [result] = args; + } else { + result = args; + } + error = err; + taskCb(err ? null : {}); + }); + }, () => callback(error, result)); + } -Promise.onUnhandledRejectionHandled = function (fn) { - var domain = getDomain(); - unhandledRejectionHandled = - typeof fn === "function" ? (domain === null ? - fn : util.domainBind(domain, fn)) - : undefined; -}; + var tryEach$1 = awaitify(tryEach); -var disableLongStackTraces = function() {}; -Promise.longStackTraces = function () { - if (async.haveItemsQueued() && !config.longStackTraces) { - throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - if (!config.longStackTraces && longStackTracesIsSupported()) { - var Promise_captureStackTrace = Promise.prototype._captureStackTrace; - var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; - config.longStackTraces = true; - disableLongStackTraces = function() { - if (async.haveItemsQueued() && !config.longStackTraces) { - throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - Promise.prototype._captureStackTrace = Promise_captureStackTrace; - Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; - Context.deactivateLongStackTraces(); - async.enableTrampoline(); - config.longStackTraces = false; + /** + * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, + * unmemoized form. Handy for testing. + * + * @name unmemoize + * @static + * @memberOf module:Utils + * @method + * @see [async.memoize]{@link module:Utils.memoize} + * @category Util + * @param {AsyncFunction} fn - the memoized function + * @returns {AsyncFunction} a function that calls the original unmemoized function + */ + function unmemoize(fn) { + return (...args) => { + return (fn.unmemoized || fn)(...args); }; - Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; - Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; - Context.activateLongStackTraces(); - async.disableTrampolineIfNecessary(); } -}; -Promise.hasLongStackTraces = function () { - return config.longStackTraces && longStackTracesIsSupported(); -}; + /** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + * @example + * + * var count = 0; + * async.whilst( + * function test(cb) { cb(null, count < 5); }, + * function iter(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ + function whilst(test, iteratee, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results = []; -var fireDomEvent = (function() { - try { - if (typeof CustomEvent === "function") { - var event = new CustomEvent("CustomEvent"); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = new CustomEvent(name.toLowerCase(), { - detail: event, - cancelable: true - }); - return !util.global.dispatchEvent(domEvent); - }; - } else if (typeof Event === "function") { - var event = new Event("CustomEvent"); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = new Event(name.toLowerCase(), { - cancelable: true - }); - domEvent.detail = event; - return !util.global.dispatchEvent(domEvent); - }; - } else { - var event = document.createEvent("CustomEvent"); - event.initCustomEvent("testingtheevent", false, true, {}); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = document.createEvent("CustomEvent"); - domEvent.initCustomEvent(name.toLowerCase(), false, true, - event); - return !util.global.dispatchEvent(domEvent); - }; + function next(err, ...rest) { + if (err) return callback(err); + results = rest; + if (err === false) return; + _test(check); } - } catch (e) {} - return function() { - return false; - }; -})(); -var fireGlobalEvent = (function() { - if (util.isNode) { - return function() { - return process.emit.apply(process, arguments); - }; - } else { - if (!util.global) { - return function() { - return false; - }; + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); } - return function(name) { - var methodName = "on" + name.toLowerCase(); - var method = util.global[methodName]; - if (!method) return false; - method.apply(util.global, [].slice.call(arguments, 1)); - return true; - }; - } -})(); - -function generatePromiseLifecycleEventObject(name, promise) { - return {promise: promise}; -} - -var eventToObjectGenerator = { - promiseCreated: generatePromiseLifecycleEventObject, - promiseFulfilled: generatePromiseLifecycleEventObject, - promiseRejected: generatePromiseLifecycleEventObject, - promiseResolved: generatePromiseLifecycleEventObject, - promiseCancelled: generatePromiseLifecycleEventObject, - promiseChained: function(name, promise, child) { - return {promise: promise, child: child}; - }, - warning: function(name, warning) { - return {warning: warning}; - }, - unhandledRejection: function (name, reason, promise) { - return {reason: reason, promise: promise}; - }, - rejectionHandled: generatePromiseLifecycleEventObject -}; -var activeFireEvent = function (name) { - var globalEventFired = false; - try { - globalEventFired = fireGlobalEvent.apply(null, arguments); - } catch (e) { - async.throwLater(e); - globalEventFired = true; + return _test(check); } + var whilst$1 = awaitify(whilst, 3); - var domEventFired = false; - try { - domEventFired = fireDomEvent(name, - eventToObjectGenerator[name].apply(null, arguments)); - } catch (e) { - async.throwLater(e); - domEventFired = true; + /** + * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. `callback` will be passed an error and any + * arguments passed to the final `iteratee`'s callback. + * + * The inverse of [whilst]{@link module:ControlFlow.whilst}. + * + * @name until + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * const results = [] + * let finished = false + * async.until(function test(cb) { + * cb(null, finished) + * }, function iter(next) { + * fetchPage(url, (err, body) => { + * if (err) return next(err) + * results = results.concat(body.objects) + * finished = !!body.next + * next(err) + * }) + * }, function done (err) { + * // all pages have been fetched + * }) + */ + function until(test, iteratee, callback) { + const _test = wrapAsync(test); + return whilst$1((cb) => _test((err, truth) => cb (err, !truth)), iteratee, callback); } - return domEventFired || globalEventFired; -}; + /** + * Runs the `tasks` array of functions in series, each passing their results to + * the next in the array. However, if any of the `tasks` pass an error to their + * own callback, the next function is not executed, and the main `callback` is + * immediately called with the error. + * + * @name waterfall + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} + * to run. + * Each function should complete with any number of `result` values. + * The `result` values will be passed as arguments, in order, to the next task. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This will be passed the results of the last task's + * callback. Invoked with (err, [results]). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * async.waterfall([ + * function(callback) { + * callback(null, 'one', 'two'); + * }, + * function(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * }, + * function(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + * ], function (err, result) { + * // result now equals 'done' + * }); + * + * // Or, with named functions: + * async.waterfall([ + * myFirstFunction, + * mySecondFunction, + * myLastFunction, + * ], function (err, result) { + * // result now equals 'done' + * }); + * function myFirstFunction(callback) { + * callback(null, 'one', 'two'); + * } + * function mySecondFunction(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * } + * function myLastFunction(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + */ + function waterfall (tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); + if (!tasks.length) return callback(); + var taskIndex = 0; -Promise.config = function(opts) { - opts = Object(opts); - if ("longStackTraces" in opts) { - if (opts.longStackTraces) { - Promise.longStackTraces(); - } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { - disableLongStackTraces(); + function nextTask(args) { + var task = wrapAsync(tasks[taskIndex++]); + task(...args, onlyOnce(next)); } - } - if ("warnings" in opts) { - var warningsOption = opts.warnings; - config.warnings = !!warningsOption; - wForgottenReturn = config.warnings; - if (util.isObject(warningsOption)) { - if ("wForgottenReturn" in warningsOption) { - wForgottenReturn = !!warningsOption.wForgottenReturn; + function next(err, ...args) { + if (err === false) return + if (err || taskIndex === tasks.length) { + return callback(err, ...args); } + nextTask(args); } - } - if ("cancellation" in opts && opts.cancellation && !config.cancellation) { - if (async.haveItemsQueued()) { - throw new Error( - "cannot enable cancellation after promises are in use"); - } - Promise.prototype._clearCancellationData = - cancellationClearCancellationData; - Promise.prototype._propagateFrom = cancellationPropagateFrom; - Promise.prototype._onCancel = cancellationOnCancel; - Promise.prototype._setOnCancel = cancellationSetOnCancel; - Promise.prototype._attachCancellationCallback = - cancellationAttachCancellationCallback; - Promise.prototype._execute = cancellationExecute; - propagateFromFunction = cancellationPropagateFrom; - config.cancellation = true; - } - if ("monitoring" in opts) { - if (opts.monitoring && !config.monitoring) { - config.monitoring = true; - Promise.prototype._fireEvent = activeFireEvent; - } else if (!opts.monitoring && config.monitoring) { - config.monitoring = false; - Promise.prototype._fireEvent = defaultFireEvent; - } - } - return Promise; -}; - -function defaultFireEvent() { return false; } - -Promise.prototype._fireEvent = defaultFireEvent; -Promise.prototype._execute = function(executor, resolve, reject) { - try { - executor(resolve, reject); - } catch (e) { - return e; - } -}; -Promise.prototype._onCancel = function () {}; -Promise.prototype._setOnCancel = function (handler) { ; }; -Promise.prototype._attachCancellationCallback = function(onCancel) { - ; -}; -Promise.prototype._captureStackTrace = function () {}; -Promise.prototype._attachExtraTrace = function () {}; -Promise.prototype._clearCancellationData = function() {}; -Promise.prototype._propagateFrom = function (parent, flags) { - ; - ; -}; - -function cancellationExecute(executor, resolve, reject) { - var promise = this; - try { - executor(resolve, reject, function(onCancel) { - if (typeof onCancel !== "function") { - throw new TypeError("onCancel must be a function, got: " + - util.toString(onCancel)); - } - promise._attachCancellationCallback(onCancel); - }); - } catch (e) { - return e; - } -} -function cancellationAttachCancellationCallback(onCancel) { - if (!this._isCancellable()) return this; - - var previousOnCancel = this._onCancel(); - if (previousOnCancel !== undefined) { - if (util.isArray(previousOnCancel)) { - previousOnCancel.push(onCancel); - } else { - this._setOnCancel([previousOnCancel, onCancel]); - } - } else { - this._setOnCancel(onCancel); + nextTask([]); } -} - -function cancellationOnCancel() { - return this._onCancelField; -} - -function cancellationSetOnCancel(onCancel) { - this._onCancelField = onCancel; -} -function cancellationClearCancellationData() { - this._cancellationParent = undefined; - this._onCancelField = undefined; -} + var waterfall$1 = awaitify(waterfall); -function cancellationPropagateFrom(parent, flags) { - if ((flags & 1) !== 0) { - this._cancellationParent = parent; - var branchesRemainingToCancel = parent._branchesRemainingToCancel; - if (branchesRemainingToCancel === undefined) { - branchesRemainingToCancel = 0; - } - parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; - } - if ((flags & 2) !== 0 && parent._isBound()) { - this._setBoundTo(parent._boundTo); - } -} + /** + * An "async function" in the context of Async is an asynchronous function with + * a variable number of parameters, with the final parameter being a callback. + * (`function (arg1, arg2, ..., callback) {}`) + * The final callback is of the form `callback(err, results...)`, which must be + * called once the function is completed. The callback should be called with a + * Error as its first argument to signal that an error occurred. + * Otherwise, if no error occurred, it should be called with `null` as the first + * argument, and any additional `result` arguments that may apply, to signal + * successful completion. + * The callback must be called exactly once, ideally on a later tick of the + * JavaScript event loop. + * + * This type of function is also referred to as a "Node-style async function", + * or a "continuation passing-style function" (CPS). Most of the methods of this + * library are themselves CPS/Node-style async functions, or functions that + * return CPS/Node-style async functions. + * + * Wherever we accept a Node-style async function, we also directly accept an + * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. + * In this case, the `async` function will not be passed a final callback + * argument, and any thrown error will be used as the `err` argument of the + * implicit callback, and the return value will be used as the `result` value. + * (i.e. a `rejected` of the returned Promise becomes the `err` callback + * argument, and a `resolved` value becomes the `result`.) + * + * Note, due to JavaScript limitations, we can only detect native `async` + * functions and not transpilied implementations. + * Your environment must have `async`/`await` support for this to work. + * (e.g. Node > v7.6, or a recent version of a modern browser). + * If you are using `async` functions through a transpiler (e.g. Babel), you + * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, + * because the `async function` will be compiled to an ordinary function that + * returns a promise. + * + * @typedef {Function} AsyncFunction + * @static + */ -function bindingPropagateFrom(parent, flags) { - if ((flags & 2) !== 0 && parent._isBound()) { - this._setBoundTo(parent._boundTo); - } -} -var propagateFromFunction = bindingPropagateFrom; -function boundValueFunction() { - var ret = this._boundTo; - if (ret !== undefined) { - if (ret instanceof Promise) { - if (ret.isFulfilled()) { - return ret.value(); - } else { - return undefined; - } - } - } - return ret; -} - -function longStackTracesCaptureStackTrace() { - this._trace = new CapturedTrace(this._peekContext()); -} + var index = { + apply, + applyEach, + applyEachSeries, + asyncify, + auto, + autoInject, + cargo: cargo$1, + cargoQueue: cargo, + compose, + concat: concat$1, + concatLimit: concatLimit$1, + concatSeries: concatSeries$1, + constant: constant$1, + detect: detect$1, + detectLimit: detectLimit$1, + detectSeries: detectSeries$1, + dir, + doUntil, + doWhilst: doWhilst$1, + each, + eachLimit: eachLimit$1, + eachOf: eachOf$1, + eachOfLimit: eachOfLimit$1, + eachOfSeries: eachOfSeries$1, + eachSeries: eachSeries$1, + ensureAsync, + every: every$1, + everyLimit: everyLimit$1, + everySeries: everySeries$1, + filter: filter$1, + filterLimit: filterLimit$1, + filterSeries: filterSeries$1, + forever: forever$1, + groupBy, + groupByLimit: groupByLimit$1, + groupBySeries, + log, + map: map$1, + mapLimit: mapLimit$1, + mapSeries: mapSeries$1, + mapValues, + mapValuesLimit: mapValuesLimit$1, + mapValuesSeries, + memoize, + nextTick, + parallel, + parallelLimit, + priorityQueue, + queue, + race: race$1, + reduce: reduce$1, + reduceRight, + reflect, + reflectAll, + reject: reject$1, + rejectLimit: rejectLimit$1, + rejectSeries: rejectSeries$1, + retry, + retryable, + seq, + series, + setImmediate: setImmediate$1, + some: some$1, + someLimit: someLimit$1, + someSeries: someSeries$1, + sortBy: sortBy$1, + timeout, + times, + timesLimit, + timesSeries, + transform, + tryEach: tryEach$1, + unmemoize, + until, + waterfall: waterfall$1, + whilst: whilst$1, -function longStackTracesAttachExtraTrace(error, ignoreSelf) { - if (canAttachTrace(error)) { - var trace = this._trace; - if (trace !== undefined) { - if (ignoreSelf) trace = trace._parent; - } - if (trace !== undefined) { - trace.attachExtraTrace(error); - } else if (!error.__stackCleaned__) { - var parsed = parseStackAndMessage(error); - util.notEnumerableProp(error, "stack", - parsed.message + "\n" + parsed.stack.join("\n")); - util.notEnumerableProp(error, "__stackCleaned__", true); - } - } -} + // aliases + all: every$1, + allLimit: everyLimit$1, + allSeries: everySeries$1, + any: some$1, + anyLimit: someLimit$1, + anySeries: someSeries$1, + find: detect$1, + findLimit: detectLimit$1, + findSeries: detectSeries$1, + flatMap: concat$1, + flatMapLimit: concatLimit$1, + flatMapSeries: concatSeries$1, + forEach: each, + forEachSeries: eachSeries$1, + forEachLimit: eachLimit$1, + forEachOf: eachOf$1, + forEachOfSeries: eachOfSeries$1, + forEachOfLimit: eachOfLimit$1, + inject: reduce$1, + foldl: reduce$1, + foldr: reduceRight, + select: filter$1, + selectLimit: filterLimit$1, + selectSeries: filterSeries$1, + wrapSync: asyncify, + during: whilst$1, + doDuring: doWhilst$1 + }; -function checkForgottenReturns(returnValue, promiseCreated, name, promise, - parent) { - if (returnValue === undefined && promiseCreated !== null && - wForgottenReturn) { - if (parent !== undefined && parent._returnedNonUndefined()) return; - if ((promise._bitField & 65535) === 0) return; + exports.all = every$1; + exports.allLimit = everyLimit$1; + exports.allSeries = everySeries$1; + exports.any = some$1; + exports.anyLimit = someLimit$1; + exports.anySeries = someSeries$1; + exports.apply = apply; + exports.applyEach = applyEach; + exports.applyEachSeries = applyEachSeries; + exports.asyncify = asyncify; + exports.auto = auto; + exports.autoInject = autoInject; + exports.cargo = cargo$1; + exports.cargoQueue = cargo; + exports.compose = compose; + exports.concat = concat$1; + exports.concatLimit = concatLimit$1; + exports.concatSeries = concatSeries$1; + exports.constant = constant$1; + exports.default = index; + exports.detect = detect$1; + exports.detectLimit = detectLimit$1; + exports.detectSeries = detectSeries$1; + exports.dir = dir; + exports.doDuring = doWhilst$1; + exports.doUntil = doUntil; + exports.doWhilst = doWhilst$1; + exports.during = whilst$1; + exports.each = each; + exports.eachLimit = eachLimit$1; + exports.eachOf = eachOf$1; + exports.eachOfLimit = eachOfLimit$1; + exports.eachOfSeries = eachOfSeries$1; + exports.eachSeries = eachSeries$1; + exports.ensureAsync = ensureAsync; + exports.every = every$1; + exports.everyLimit = everyLimit$1; + exports.everySeries = everySeries$1; + exports.filter = filter$1; + exports.filterLimit = filterLimit$1; + exports.filterSeries = filterSeries$1; + exports.find = detect$1; + exports.findLimit = detectLimit$1; + exports.findSeries = detectSeries$1; + exports.flatMap = concat$1; + exports.flatMapLimit = concatLimit$1; + exports.flatMapSeries = concatSeries$1; + exports.foldl = reduce$1; + exports.foldr = reduceRight; + exports.forEach = each; + exports.forEachLimit = eachLimit$1; + exports.forEachOf = eachOf$1; + exports.forEachOfLimit = eachOfLimit$1; + exports.forEachOfSeries = eachOfSeries$1; + exports.forEachSeries = eachSeries$1; + exports.forever = forever$1; + exports.groupBy = groupBy; + exports.groupByLimit = groupByLimit$1; + exports.groupBySeries = groupBySeries; + exports.inject = reduce$1; + exports.log = log; + exports.map = map$1; + exports.mapLimit = mapLimit$1; + exports.mapSeries = mapSeries$1; + exports.mapValues = mapValues; + exports.mapValuesLimit = mapValuesLimit$1; + exports.mapValuesSeries = mapValuesSeries; + exports.memoize = memoize; + exports.nextTick = nextTick; + exports.parallel = parallel; + exports.parallelLimit = parallelLimit; + exports.priorityQueue = priorityQueue; + exports.queue = queue; + exports.race = race$1; + exports.reduce = reduce$1; + exports.reduceRight = reduceRight; + exports.reflect = reflect; + exports.reflectAll = reflectAll; + exports.reject = reject$1; + exports.rejectLimit = rejectLimit$1; + exports.rejectSeries = rejectSeries$1; + exports.retry = retry; + exports.retryable = retryable; + exports.select = filter$1; + exports.selectLimit = filterLimit$1; + exports.selectSeries = filterSeries$1; + exports.seq = seq; + exports.series = series; + exports.setImmediate = setImmediate$1; + exports.some = some$1; + exports.someLimit = someLimit$1; + exports.someSeries = someSeries$1; + exports.sortBy = sortBy$1; + exports.timeout = timeout; + exports.times = times; + exports.timesLimit = timesLimit; + exports.timesSeries = timesSeries; + exports.transform = transform; + exports.tryEach = tryEach$1; + exports.unmemoize = unmemoize; + exports.until = until; + exports.waterfall = waterfall$1; + exports.whilst = whilst$1; + exports.wrapSync = asyncify; - if (name) name = name + " "; - var handlerLine = ""; - var creatorLine = ""; - if (promiseCreated._trace) { - var traceLines = promiseCreated._trace.stack.split("\n"); - var stack = cleanStack(traceLines); - for (var i = stack.length - 1; i >= 0; --i) { - var line = stack[i]; - if (!nodeFramePattern.test(line)) { - var lineMatches = line.match(parseLinePattern); - if (lineMatches) { - handlerLine = "at " + lineMatches[1] + - ":" + lineMatches[2] + ":" + lineMatches[3] + " "; - } - break; - } - } + Object.defineProperty(exports, '__esModule', { value: true }); - if (stack.length > 0) { - var firstUserLine = stack[0]; - for (var i = 0; i < traceLines.length; ++i) { +})); - if (traceLines[i] === firstUserLine) { - if (i > 0) { - creatorLine = "\n" + traceLines[i - 1]; - } - break; - } - } - } - } - var msg = "a promise was created in a " + name + - "handler " + handlerLine + "but was not returned from it, " + - "see http://goo.gl/rRqMUw" + - creatorLine; - promise._warn(msg, true, promiseCreated); - } -} +/***/ }), -function deprecated(name, replacement) { - var message = name + - " is deprecated and will be removed in a future version."; - if (replacement) message += " Use " + replacement + " instead."; - return warn(message); -} +/***/ 14812: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function warn(message, shouldUseOwnTrace, promise) { - if (!config.warnings) return; - var warning = new Warning(message); - var ctx; - if (shouldUseOwnTrace) { - promise._attachExtraTrace(warning); - } else if (config.longStackTraces && (ctx = Promise._peekContext())) { - ctx.attachExtraTrace(warning); - } else { - var parsed = parseStackAndMessage(warning); - warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); - } +module.exports = +{ + parallel : __nccwpck_require__(8210), + serial : __nccwpck_require__(50445), + serialOrdered : __nccwpck_require__(3578) +}; - if (!activeFireEvent("warning", warning)) { - formatAndLogError(warning, "", true); - } -} -function reconstructStack(message, stacks) { - for (var i = 0; i < stacks.length - 1; ++i) { - stacks[i].push("From previous event:"); - stacks[i] = stacks[i].join("\n"); - } - if (i < stacks.length) { - stacks[i] = stacks[i].join("\n"); - } - return message + "\n" + stacks.join("\n"); -} +/***/ }), -function removeDuplicateOrEmptyJumps(stacks) { - for (var i = 0; i < stacks.length; ++i) { - if (stacks[i].length === 0 || - ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { - stacks.splice(i, 1); - i--; - } - } -} +/***/ 1700: +/***/ ((module) => { -function removeCommonRoots(stacks) { - var current = stacks[0]; - for (var i = 1; i < stacks.length; ++i) { - var prev = stacks[i]; - var currentLastIndex = current.length - 1; - var currentLastLine = current[currentLastIndex]; - var commonRootMeetPoint = -1; +// API +module.exports = abort; - for (var j = prev.length - 1; j >= 0; --j) { - if (prev[j] === currentLastLine) { - commonRootMeetPoint = j; - break; - } - } +/** + * Aborts leftover active jobs + * + * @param {object} state - current state object + */ +function abort(state) +{ + Object.keys(state.jobs).forEach(clean.bind(state)); - for (var j = commonRootMeetPoint; j >= 0; --j) { - var line = prev[j]; - if (current[currentLastIndex] === line) { - current.pop(); - currentLastIndex--; - } else { - break; - } - } - current = prev; - } + // reset leftover jobs + state.jobs = {}; } -function cleanStack(stack) { - var ret = []; - for (var i = 0; i < stack.length; ++i) { - var line = stack[i]; - var isTraceLine = " (No stack trace)" === line || - stackFramePattern.test(line); - var isInternalFrame = isTraceLine && shouldIgnore(line); - if (isTraceLine && !isInternalFrame) { - if (indentStackFrames && line.charAt(0) !== " ") { - line = " " + line; - } - ret.push(line); - } - } - return ret; +/** + * Cleans up leftover job by invoking abort function for the provided job id + * + * @this state + * @param {string|number} key - job id to abort + */ +function clean(key) +{ + if (typeof this.jobs[key] == 'function') + { + this.jobs[key](); + } } -function stackFramesAsArray(error) { - var stack = error.stack.replace(/\s+$/g, "").split("\n"); - for (var i = 0; i < stack.length; ++i) { - var line = stack[i]; - if (" (No stack trace)" === line || stackFramePattern.test(line)) { - break; - } - } - if (i > 0 && error.name != "SyntaxError") { - stack = stack.slice(i); - } - return stack; -} -function parseStackAndMessage(error) { - var stack = error.stack; - var message = error.toString(); - stack = typeof stack === "string" && stack.length > 0 - ? stackFramesAsArray(error) : [" (No stack trace)"]; - return { - message: message, - stack: error.name == "SyntaxError" ? stack : cleanStack(stack) - }; -} +/***/ }), -function formatAndLogError(error, title, isSoft) { - if (typeof console !== "undefined") { - var message; - if (util.isObject(error)) { - var stack = error.stack; - message = title + formatStack(stack, error); - } else { - message = title + String(error); - } - if (typeof printWarning === "function") { - printWarning(message, isSoft); - } else if (typeof console.log === "function" || - typeof console.log === "object") { - console.log(message); - } - } -} +/***/ 72794: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function fireRejectionEvent(name, localHandler, reason, promise) { - var localEventFired = false; - try { - if (typeof localHandler === "function") { - localEventFired = true; - if (name === "rejectionHandled") { - localHandler(promise); - } else { - localHandler(reason, promise); - } - } - } catch (e) { - async.throwLater(e); - } +var defer = __nccwpck_require__(15295); - if (name === "unhandledRejection") { - if (!activeFireEvent(name, reason, promise) && !localEventFired) { - formatAndLogError(reason, "Unhandled rejection "); - } - } else { - activeFireEvent(name, promise); - } -} +// API +module.exports = async; -function formatNonError(obj) { - var str; - if (typeof obj === "function") { - str = "[function " + - (obj.name || "anonymous") + - "]"; - } else { - str = obj && typeof obj.toString === "function" - ? obj.toString() : util.toString(obj); - var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; - if (ruselessToString.test(str)) { - try { - var newStr = JSON.stringify(obj); - str = newStr; - } - catch(e) { +/** + * Runs provided callback asynchronously + * even if callback itself is not + * + * @param {function} callback - callback to invoke + * @returns {function} - augmented callback + */ +function async(callback) +{ + var isAsync = false; - } - } - if (str.length === 0) { - str = "(empty array)"; - } - } - return ("(<" + snip(str) + ">, no stack trace)"); -} + // check if async happened + defer(function() { isAsync = true; }); -function snip(str) { - var maxChars = 41; - if (str.length < maxChars) { - return str; + return function async_callback(err, result) + { + if (isAsync) + { + callback(err, result); } - return str.substr(0, maxChars - 3) + "..."; -} - -function longStackTracesIsSupported() { - return typeof captureStackTrace === "function"; -} - -var shouldIgnore = function() { return false; }; -var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; -function parseLineInfo(line) { - var matches = line.match(parseLineInfoRegex); - if (matches) { - return { - fileName: matches[1], - line: parseInt(matches[2], 10) - }; + else + { + defer(function nextTick_callback() + { + callback(err, result); + }); } + }; } -function setBounds(firstLineError, lastLineError) { - if (!longStackTracesIsSupported()) return; - var firstStackLines = firstLineError.stack.split("\n"); - var lastStackLines = lastLineError.stack.split("\n"); - var firstIndex = -1; - var lastIndex = -1; - var firstFileName; - var lastFileName; - for (var i = 0; i < firstStackLines.length; ++i) { - var result = parseLineInfo(firstStackLines[i]); - if (result) { - firstFileName = result.fileName; - firstIndex = result.line; - break; - } - } - for (var i = 0; i < lastStackLines.length; ++i) { - var result = parseLineInfo(lastStackLines[i]); - if (result) { - lastFileName = result.fileName; - lastIndex = result.line; - break; - } - } - if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || - firstFileName !== lastFileName || firstIndex >= lastIndex) { - return; - } - - shouldIgnore = function(line) { - if (bluebirdFramePattern.test(line)) return true; - var info = parseLineInfo(line); - if (info) { - if (info.fileName === firstFileName && - (firstIndex <= info.line && info.line <= lastIndex)) { - return true; - } - } - return false; - }; -} -function CapturedTrace(parent) { - this._parent = parent; - this._promisesCreated = 0; - var length = this._length = 1 + (parent === undefined ? 0 : parent._length); - captureStackTrace(this, CapturedTrace); - if (length > 32) this.uncycle(); -} -util.inherits(CapturedTrace, Error); -Context.CapturedTrace = CapturedTrace; - -CapturedTrace.prototype.uncycle = function() { - var length = this._length; - if (length < 2) return; - var nodes = []; - var stackToIndex = {}; - - for (var i = 0, node = this; node !== undefined; ++i) { - nodes.push(node); - node = node._parent; - } - length = this._length = i; - for (var i = length - 1; i >= 0; --i) { - var stack = nodes[i].stack; - if (stackToIndex[stack] === undefined) { - stackToIndex[stack] = i; - } - } - for (var i = 0; i < length; ++i) { - var currentStack = nodes[i].stack; - var index = stackToIndex[currentStack]; - if (index !== undefined && index !== i) { - if (index > 0) { - nodes[index - 1]._parent = undefined; - nodes[index - 1]._length = 1; - } - nodes[i]._parent = undefined; - nodes[i]._length = 1; - var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; - - if (index < length - 1) { - cycleEdgeNode._parent = nodes[index + 1]; - cycleEdgeNode._parent.uncycle(); - cycleEdgeNode._length = - cycleEdgeNode._parent._length + 1; - } else { - cycleEdgeNode._parent = undefined; - cycleEdgeNode._length = 1; - } - var currentChildLength = cycleEdgeNode._length + 1; - for (var j = i - 2; j >= 0; --j) { - nodes[j]._length = currentChildLength; - currentChildLength++; - } - return; - } - } -}; +/***/ }), -CapturedTrace.prototype.attachExtraTrace = function(error) { - if (error.__stackCleaned__) return; - this.uncycle(); - var parsed = parseStackAndMessage(error); - var message = parsed.message; - var stacks = [parsed.stack]; +/***/ 15295: +/***/ ((module) => { - var trace = this; - while (trace !== undefined) { - stacks.push(cleanStack(trace.stack.split("\n"))); - trace = trace._parent; - } - removeCommonRoots(stacks); - removeDuplicateOrEmptyJumps(stacks); - util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); - util.notEnumerableProp(error, "__stackCleaned__", true); -}; +module.exports = defer; -var captureStackTrace = (function stackDetection() { - var v8stackFramePattern = /^\s*at\s*/; - var v8stackFormatter = function(stack, error) { - if (typeof stack === "string") return stack; +/** + * Runs provided function on next iteration of the event loop + * + * @param {function} fn - function to run + */ +function defer(fn) +{ + var nextTick = typeof setImmediate == 'function' + ? setImmediate + : ( + typeof process == 'object' && typeof process.nextTick == 'function' + ? process.nextTick + : null + ); - if (error.name !== undefined && - error.message !== undefined) { - return error.toString(); - } - return formatNonError(error); - }; + if (nextTick) + { + nextTick(fn); + } + else + { + setTimeout(fn, 0); + } +} - if (typeof Error.stackTraceLimit === "number" && - typeof Error.captureStackTrace === "function") { - Error.stackTraceLimit += 6; - stackFramePattern = v8stackFramePattern; - formatStack = v8stackFormatter; - var captureStackTrace = Error.captureStackTrace; - shouldIgnore = function(line) { - return bluebirdFramePattern.test(line); - }; - return function(receiver, ignoreUntil) { - Error.stackTraceLimit += 6; - captureStackTrace(receiver, ignoreUntil); - Error.stackTraceLimit -= 6; - }; - } - var err = new Error(); +/***/ }), - if (typeof err.stack === "string" && - err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { - stackFramePattern = /@/; - formatStack = v8stackFormatter; - indentStackFrames = true; - return function captureStackTrace(o) { - o.stack = new Error().stack; - }; - } +/***/ 9023: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var hasStackAfterThrow; - try { throw new Error(); } - catch(e) { - hasStackAfterThrow = ("stack" in e); - } - if (!("stack" in err) && hasStackAfterThrow && - typeof Error.stackTraceLimit === "number") { - stackFramePattern = v8stackFramePattern; - formatStack = v8stackFormatter; - return function captureStackTrace(o) { - Error.stackTraceLimit += 6; - try { throw new Error(); } - catch(e) { o.stack = e.stack; } - Error.stackTraceLimit -= 6; - }; - } +var async = __nccwpck_require__(72794) + , abort = __nccwpck_require__(1700) + ; - formatStack = function(stack, error) { - if (typeof stack === "string") return stack; +// API +module.exports = iterate; - if ((typeof error === "object" || - typeof error === "function") && - error.name !== undefined && - error.message !== undefined) { - return error.toString(); - } - return formatNonError(error); - }; +/** + * Iterates over each job object + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {object} state - current job status + * @param {function} callback - invoked when all elements processed + */ +function iterate(list, iterator, state, callback) +{ + // store current index + var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; - return null; + state.jobs[key] = runJob(iterator, key, list[key], function(error, output) + { + // don't repeat yourself + // skip secondary callbacks + if (!(key in state.jobs)) + { + return; + } -})([]); + // clean up jobs + delete state.jobs[key]; -if (typeof console !== "undefined" && typeof console.warn !== "undefined") { - printWarning = function (message) { - console.warn(message); - }; - if (util.isNode && process.stderr.isTTY) { - printWarning = function(message, isSoft) { - var color = isSoft ? "\u001b[33m" : "\u001b[31m"; - console.warn(color + message + "\u001b[0m\n"); - }; - } else if (!util.isNode && typeof (new Error().stack) === "string") { - printWarning = function(message, isSoft) { - console.warn("%c" + message, - isSoft ? "color: darkorange" : "color: red"); - }; + if (error) + { + // don't process rest of the results + // stop still active jobs + // and reset the list + abort(state); + } + else + { + state.results[key] = output; } + + // return salvaged results + callback(error, state.results); + }); } -var config = { - warnings: warnings, - longStackTraces: false, - cancellation: false, - monitoring: false -}; +/** + * Runs iterator over provided job element + * + * @param {function} iterator - iterator to invoke + * @param {string|number} key - key/index of the element in the list of jobs + * @param {mixed} item - job description + * @param {function} callback - invoked after iterator is done with the job + * @returns {function|mixed} - job abort function or something else + */ +function runJob(iterator, key, item, callback) +{ + var aborter; -if (longStackTraces) Promise.longStackTraces(); + // allow shortcut if iterator expects only two arguments + if (iterator.length == 2) + { + aborter = iterator(item, async(callback)); + } + // otherwise go with full three arguments + else + { + aborter = iterator(item, key, async(callback)); + } -return { - longStackTraces: function() { - return config.longStackTraces; - }, - warnings: function() { - return config.warnings; - }, - cancellation: function() { - return config.cancellation; - }, - monitoring: function() { - return config.monitoring; - }, - propagateFromFunction: function() { - return propagateFromFunction; - }, - boundValueFunction: function() { - return boundValueFunction; - }, - checkForgottenReturns: checkForgottenReturns, - setBounds: setBounds, - warn: warn, - deprecated: deprecated, - CapturedTrace: CapturedTrace, - fireDomEvent: fireDomEvent, - fireGlobalEvent: fireGlobalEvent -}; -}; + return aborter; +} /***/ }), -/***/ 36037: +/***/ 42474: /***/ ((module) => { -"use strict"; +// API +module.exports = state; -module.exports = function(Promise) { -function returner() { - return this.value; -} -function thrower() { - throw this.reason; -} +/** + * Creates initial state object + * for iteration over list + * + * @param {array|object} list - list to iterate over + * @param {function|null} sortMethod - function to use for keys sort, + * or `null` to keep them as is + * @returns {object} - initial state object + */ +function state(list, sortMethod) +{ + var isNamedList = !Array.isArray(list) + , initState = + { + index : 0, + keyedList: isNamedList || sortMethod ? Object.keys(list) : null, + jobs : {}, + results : isNamedList ? {} : [], + size : isNamedList ? Object.keys(list).length : list.length + } + ; -Promise.prototype["return"] = -Promise.prototype.thenReturn = function (value) { - if (value instanceof Promise) value.suppressUnhandledRejections(); - return this._then( - returner, undefined, undefined, {value: value}, undefined); -}; + if (sortMethod) + { + // sort array keys based on it's values + // sort object's keys just on own merit + initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) + { + return sortMethod(list[a], list[b]); + }); + } -Promise.prototype["throw"] = -Promise.prototype.thenThrow = function (reason) { - return this._then( - thrower, undefined, undefined, {reason: reason}, undefined); -}; + return initState; +} -Promise.prototype.catchThrow = function (reason) { - if (arguments.length <= 1) { - return this._then( - undefined, thrower, undefined, {reason: reason}, undefined); - } else { - var _reason = arguments[1]; - var handler = function() {throw _reason;}; - return this.caught(reason, handler); - } -}; -Promise.prototype.catchReturn = function (value) { - if (arguments.length <= 1) { - if (value instanceof Promise) value.suppressUnhandledRejections(); - return this._then( - undefined, returner, undefined, {value: value}, undefined); - } else { - var _value = arguments[1]; - if (_value instanceof Promise) _value.suppressUnhandledRejections(); - var handler = function() {return _value;}; - return this.caught(value, handler); - } -}; -}; +/***/ }), +/***/ 37942: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/***/ }), +var abort = __nccwpck_require__(1700) + , async = __nccwpck_require__(72794) + ; -/***/ 56189: -/***/ ((module) => { +// API +module.exports = terminator; -"use strict"; +/** + * Terminates jobs in the attached state context + * + * @this AsyncKitState# + * @param {function} callback - final callback to invoke after termination + */ +function terminator(callback) +{ + if (!Object.keys(this.jobs).length) + { + return; + } -module.exports = function(Promise, INTERNAL) { -var PromiseReduce = Promise.reduce; -var PromiseAll = Promise.all; + // fast forward iteration index + this.index = this.size; -function promiseAllThis() { - return PromiseAll(this); -} + // abort jobs + abort(this); -function PromiseMapSeries(promises, fn) { - return PromiseReduce(promises, fn, INTERNAL, INTERNAL); + // send back results we have so far + async(callback)(null, this.results); } -Promise.prototype.each = function (fn) { - return PromiseReduce(this, fn, INTERNAL, 0) - ._then(promiseAllThis, undefined, undefined, this, undefined); -}; - -Promise.prototype.mapSeries = function (fn) { - return PromiseReduce(this, fn, INTERNAL, INTERNAL); -}; -Promise.each = function (promises, fn) { - return PromiseReduce(promises, fn, INTERNAL, 0) - ._then(promiseAllThis, undefined, undefined, promises, undefined); -}; +/***/ }), -Promise.mapSeries = PromiseMapSeries; -}; +/***/ 8210: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var iterate = __nccwpck_require__(9023) + , initState = __nccwpck_require__(42474) + , terminator = __nccwpck_require__(37942) + ; +// Public API +module.exports = parallel; -/***/ }), +/** + * Runs iterator over provided array elements in parallel + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function parallel(list, iterator, callback) +{ + var state = initState(list); -/***/ 44581: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + while (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, function(error, result) + { + if (error) + { + callback(error, result); + return; + } -"use strict"; + // looks like it's the last one + if (Object.keys(state.jobs).length === 0) + { + callback(null, state.results); + return; + } + }); -var es5 = __nccwpck_require__(61713); -var Objectfreeze = es5.freeze; -var util = __nccwpck_require__(37180); -var inherits = util.inherits; -var notEnumerableProp = util.notEnumerableProp; - -function subError(nameProperty, defaultMessage) { - function SubError(message) { - if (!(this instanceof SubError)) return new SubError(message); - notEnumerableProp(this, "message", - typeof message === "string" ? message : defaultMessage); - notEnumerableProp(this, "name", nameProperty); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } else { - Error.call(this); - } - } - inherits(SubError, Error); - return SubError; -} + state.index++; + } -var _TypeError, _RangeError; -var Warning = subError("Warning", "warning"); -var CancellationError = subError("CancellationError", "cancellation error"); -var TimeoutError = subError("TimeoutError", "timeout error"); -var AggregateError = subError("AggregateError", "aggregate error"); -try { - _TypeError = TypeError; - _RangeError = RangeError; -} catch(e) { - _TypeError = subError("TypeError", "type error"); - _RangeError = subError("RangeError", "range error"); + return terminator.bind(state, callback); } -var methods = ("join pop push shift unshift slice filter forEach some " + - "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); -for (var i = 0; i < methods.length; ++i) { - if (typeof Array.prototype[methods[i]] === "function") { - AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; - } -} +/***/ }), -es5.defineProperty(AggregateError.prototype, "length", { - value: 0, - configurable: false, - writable: true, - enumerable: true -}); -AggregateError.prototype["isOperational"] = true; -var level = 0; -AggregateError.prototype.toString = function() { - var indent = Array(level * 4 + 1).join(" "); - var ret = "\n" + indent + "AggregateError of:" + "\n"; - level++; - indent = Array(level * 4 + 1).join(" "); - for (var i = 0; i < this.length; ++i) { - var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; - var lines = str.split("\n"); - for (var j = 0; j < lines.length; ++j) { - lines[j] = indent + lines[j]; - } - str = lines.join("\n"); - ret += str + "\n"; - } - level--; - return ret; -}; +/***/ 50445: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function OperationalError(message) { - if (!(this instanceof OperationalError)) - return new OperationalError(message); - notEnumerableProp(this, "name", "OperationalError"); - notEnumerableProp(this, "message", message); - this.cause = message; - this["isOperational"] = true; +var serialOrdered = __nccwpck_require__(3578); - if (message instanceof Error) { - notEnumerableProp(this, "message", message.message); - notEnumerableProp(this, "stack", message.stack); - } else if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } +// Public API +module.exports = serial; +/** + * Runs iterator over provided array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function serial(list, iterator, callback) +{ + return serialOrdered(list, iterator, null, callback); } -inherits(OperationalError, Error); -var errorTypes = Error["__BluebirdErrorTypes__"]; -if (!errorTypes) { - errorTypes = Objectfreeze({ - CancellationError: CancellationError, - TimeoutError: TimeoutError, - OperationalError: OperationalError, - RejectionError: OperationalError, - AggregateError: AggregateError - }); - es5.defineProperty(Error, "__BluebirdErrorTypes__", { - value: errorTypes, - writable: false, - enumerable: false, - configurable: false - }); -} -module.exports = { - Error: Error, - TypeError: _TypeError, - RangeError: _RangeError, - CancellationError: errorTypes.CancellationError, - OperationalError: errorTypes.OperationalError, - TimeoutError: errorTypes.TimeoutError, - AggregateError: errorTypes.AggregateError, - Warning: Warning -}; +/***/ }), +/***/ 3578: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/***/ }), +var iterate = __nccwpck_require__(9023) + , initState = __nccwpck_require__(42474) + , terminator = __nccwpck_require__(37942) + ; -/***/ 61713: -/***/ ((module) => { +// Public API +module.exports = serialOrdered; +// sorting helpers +module.exports.ascending = ascending; +module.exports.descending = descending; -var isES5 = (function(){ - "use strict"; - return this === undefined; -})(); +/** + * Runs iterator over provided sorted array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} sortMethod - custom sort function + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function serialOrdered(list, iterator, sortMethod, callback) +{ + var state = initState(list, sortMethod); -if (isES5) { - module.exports = { - freeze: Object.freeze, - defineProperty: Object.defineProperty, - getDescriptor: Object.getOwnPropertyDescriptor, - keys: Object.keys, - names: Object.getOwnPropertyNames, - getPrototypeOf: Object.getPrototypeOf, - isArray: Array.isArray, - isES5: isES5, - propertyIsWritable: function(obj, prop) { - var descriptor = Object.getOwnPropertyDescriptor(obj, prop); - return !!(!descriptor || descriptor.writable || descriptor.set); - } - }; -} else { - var has = {}.hasOwnProperty; - var str = {}.toString; - var proto = {}.constructor.prototype; + iterate(list, iterator, state, function iteratorHandler(error, result) + { + if (error) + { + callback(error, result); + return; + } - var ObjectKeys = function (o) { - var ret = []; - for (var key in o) { - if (has.call(o, key)) { - ret.push(key); - } - } - return ret; - }; + state.index++; - var ObjectGetDescriptor = function(o, key) { - return {value: o[key]}; - }; + // are we there yet? + if (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, iteratorHandler); + return; + } - var ObjectDefineProperty = function (o, key, desc) { - o[key] = desc.value; - return o; - }; + // done here + callback(null, state.results); + }); - var ObjectFreeze = function (obj) { - return obj; - }; + return terminator.bind(state, callback); +} - var ObjectGetPrototypeOf = function (obj) { - try { - return Object(obj).constructor.prototype; - } - catch (e) { - return proto; - } - }; +/* + * -- Sort methods + */ - var ArrayIsArray = function (obj) { - try { - return str.call(obj) === "[object Array]"; - } - catch(e) { - return false; - } - }; +/** + * sort helper to sort array elements in ascending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ +function ascending(a, b) +{ + return a < b ? -1 : a > b ? 1 : 0; +} - module.exports = { - isArray: ArrayIsArray, - keys: ObjectKeys, - names: ObjectKeys, - defineProperty: ObjectDefineProperty, - getDescriptor: ObjectGetDescriptor, - freeze: ObjectFreeze, - getPrototypeOf: ObjectGetPrototypeOf, - isES5: isES5, - propertyIsWritable: function() { - return true; - } - }; +/** + * sort helper to sort array elements in descending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ +function descending(a, b) +{ + return -1 * ascending(a, b); } /***/ }), -/***/ 87096: +/***/ 9417: /***/ ((module) => { "use strict"; -module.exports = function(Promise, INTERNAL) { -var PromiseMap = Promise.map; - -Promise.prototype.filter = function (fn, options) { - return PromiseMap(this, fn, options, INTERNAL); -}; - -Promise.filter = function (promises, fn, options) { - return PromiseMap(promises, fn, options, INTERNAL); -}; -}; - - -/***/ }), - -/***/ 75523: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; +module.exports = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); -module.exports = function(Promise, tryConvertToPromise) { -var util = __nccwpck_require__(37180); -var CancellationError = Promise.CancellationError; -var errorObj = util.errorObj; + var r = range(a, b, str); -function PassThroughHandlerContext(promise, type, handler) { - this.promise = promise; - this.type = type; - this.handler = handler; - this.called = false; - this.cancelPromise = null; + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; } -PassThroughHandlerContext.prototype.isFinallyHandler = function() { - return this.type === 0; -}; - -function FinallyHandlerCancelReaction(finallyHandler) { - this.finallyHandler = finallyHandler; +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; } -FinallyHandlerCancelReaction.prototype._resultCancelled = function() { - checkCancel(this.finallyHandler); -}; +balanced.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; -function checkCancel(ctx, reason) { - if (ctx.cancelPromise != null) { - if (arguments.length > 1) { - ctx.cancelPromise._reject(reason); - } else { - ctx.cancelPromise._cancel(); - } - ctx.cancelPromise = null; - return true; - } - return false; -} + if (ai >= 0 && bi > 0) { + begs = []; + left = str.length; -function succeed() { - return finallyHandler.call(this, this.promise._target()._settledValue()); -} -function fail(reason) { - if (checkCancel(this, reason)) return; - errorObj.e = reason; - return errorObj; -} -function finallyHandler(reasonOrValue) { - var promise = this.promise; - var handler = this.handler; - - if (!this.called) { - this.called = true; - var ret = this.isFinallyHandler() - ? handler.call(promise._boundValue()) - : handler.call(promise._boundValue(), reasonOrValue); - if (ret !== undefined) { - promise._setReturnedNonUndefined(); - var maybePromise = tryConvertToPromise(ret, promise); - if (maybePromise instanceof Promise) { - if (this.cancelPromise != null) { - if (maybePromise._isCancelled()) { - var reason = - new CancellationError("late cancellation observer"); - promise._attachExtraTrace(reason); - errorObj.e = reason; - return errorObj; - } else if (maybePromise.isPending()) { - maybePromise._attachCancellationCallback( - new FinallyHandlerCancelReaction(this)); - } - } - return maybePromise._then( - succeed, fail, undefined, this, undefined); - } + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; } - } - - if (promise.isRejected()) { - checkCancel(this); - errorObj.e = reasonOrValue; - return errorObj; - } else { - checkCancel(this); - return reasonOrValue; - } -} -Promise.prototype._passThrough = function(handler, type, success, fail) { - if (typeof handler !== "function") return this.then(); - return this._then(success, - fail, - undefined, - new PassThroughHandlerContext(this, type, handler), - undefined); -}; + bi = str.indexOf(b, i + 1); + } -Promise.prototype.lastly = -Promise.prototype["finally"] = function (handler) { - return this._passThrough(handler, - 0, - finallyHandler, - finallyHandler); -}; + i = ai < bi && ai >= 0 ? ai : bi; + } -Promise.prototype.tap = function (handler) { - return this._passThrough(handler, 1, finallyHandler); -}; + if (begs.length) { + result = [ left, right ]; + } + } -return PassThroughHandlerContext; -}; + return result; +} /***/ }), -/***/ 85241: +/***/ 83682: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - -module.exports = function(Promise, - apiRejection, - INTERNAL, - tryConvertToPromise, - Proxyable, - debug) { -var errors = __nccwpck_require__(44581); -var TypeError = errors.TypeError; -var util = __nccwpck_require__(37180); -var errorObj = util.errorObj; -var tryCatch = util.tryCatch; -var yieldHandlers = []; - -function promiseFromYieldHandler(value, yieldHandlers, traceParent) { - for (var i = 0; i < yieldHandlers.length; ++i) { - traceParent._pushContext(); - var result = tryCatch(yieldHandlers[i])(value); - traceParent._popContext(); - if (result === errorObj) { - traceParent._pushContext(); - var ret = Promise.reject(errorObj.e); - traceParent._popContext(); - return ret; - } - var maybePromise = tryConvertToPromise(result, traceParent); - if (maybePromise instanceof Promise) return maybePromise; - } - return null; -} - -function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { - if (debug.cancellation()) { - var internal = new Promise(INTERNAL); - var _finallyPromise = this._finallyPromise = new Promise(INTERNAL); - this._promise = internal.lastly(function() { - return _finallyPromise; - }); - internal._captureStackTrace(); - internal._setOnCancel(this); - } else { - var promise = this._promise = new Promise(INTERNAL); - promise._captureStackTrace(); - } - this._stack = stack; - this._generatorFunction = generatorFunction; - this._receiver = receiver; - this._generator = undefined; - this._yieldHandlers = typeof yieldHandler === "function" - ? [yieldHandler].concat(yieldHandlers) - : yieldHandlers; - this._yieldedPromise = null; - this._cancellationPhase = false; -} -util.inherits(PromiseSpawn, Proxyable); - -PromiseSpawn.prototype._isResolved = function() { - return this._promise === null; -}; - -PromiseSpawn.prototype._cleanup = function() { - this._promise = this._generator = null; - if (debug.cancellation() && this._finallyPromise !== null) { - this._finallyPromise._fulfill(); - this._finallyPromise = null; - } -}; - -PromiseSpawn.prototype._promiseCancelled = function() { - if (this._isResolved()) return; - var implementsReturn = typeof this._generator["return"] !== "undefined"; - - var result; - if (!implementsReturn) { - var reason = new Promise.CancellationError( - "generator .return() sentinel"); - Promise.coroutine.returnSentinel = reason; - this._promise._attachExtraTrace(reason); - this._promise._pushContext(); - result = tryCatch(this._generator["throw"]).call(this._generator, - reason); - this._promise._popContext(); - } else { - this._promise._pushContext(); - result = tryCatch(this._generator["return"]).call(this._generator, - undefined); - this._promise._popContext(); - } - this._cancellationPhase = true; - this._yieldedPromise = null; - this._continue(result); -}; - -PromiseSpawn.prototype._promiseFulfilled = function(value) { - this._yieldedPromise = null; - this._promise._pushContext(); - var result = tryCatch(this._generator.next).call(this._generator, value); - this._promise._popContext(); - this._continue(result); -}; +var register = __nccwpck_require__(44670); +var addHook = __nccwpck_require__(5549); +var removeHook = __nccwpck_require__(6819); -PromiseSpawn.prototype._promiseRejected = function(reason) { - this._yieldedPromise = null; - this._promise._attachExtraTrace(reason); - this._promise._pushContext(); - var result = tryCatch(this._generator["throw"]) - .call(this._generator, reason); - this._promise._popContext(); - this._continue(result); -}; +// bind with array of arguments: https://stackoverflow.com/a/21792913 +var bind = Function.bind; +var bindable = bind.bind(bind); -PromiseSpawn.prototype._resultCancelled = function() { - if (this._yieldedPromise instanceof Promise) { - var promise = this._yieldedPromise; - this._yieldedPromise = null; - promise.cancel(); - } -}; +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); + }); +} -PromiseSpawn.prototype.promise = function () { - return this._promise; -}; +function HookSingular() { + var singularHookName = "h"; + var singularHookState = { + registry: {}, + }; + var singularHook = register.bind(null, singularHookState, singularHookName); + bindApi(singularHook, singularHookState, singularHookName); + return singularHook; +} -PromiseSpawn.prototype._run = function () { - this._generator = this._generatorFunction.call(this._receiver); - this._receiver = - this._generatorFunction = undefined; - this._promiseFulfilled(undefined); -}; +function HookCollection() { + var state = { + registry: {}, + }; -PromiseSpawn.prototype._continue = function (result) { - var promise = this._promise; - if (result === errorObj) { - this._cleanup(); - if (this._cancellationPhase) { - return promise.cancel(); - } else { - return promise._rejectCallback(result.e, false); - } - } + var hook = register.bind(null, state); + bindApi(hook, state); - var value = result.value; - if (result.done === true) { - this._cleanup(); - if (this._cancellationPhase) { - return promise.cancel(); - } else { - return promise._resolveCallback(value); - } - } else { - var maybePromise = tryConvertToPromise(value, this._promise); - if (!(maybePromise instanceof Promise)) { - maybePromise = - promiseFromYieldHandler(maybePromise, - this._yieldHandlers, - this._promise); - if (maybePromise === null) { - this._promiseRejected( - new TypeError( - "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) + - "From coroutine:\u000a" + - this._stack.split("\n").slice(1, -7).join("\n") - ) - ); - return; - } - } - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - this._yieldedPromise = maybePromise; - maybePromise._proxy(this, null); - } else if (((bitField & 33554432) !== 0)) { - Promise._async.invoke( - this._promiseFulfilled, this, maybePromise._value() - ); - } else if (((bitField & 16777216) !== 0)) { - Promise._async.invoke( - this._promiseRejected, this, maybePromise._reason() - ); - } else { - this._promiseCancelled(); - } - } -}; + return hook; +} -Promise.coroutine = function (generatorFunction, options) { - if (typeof generatorFunction !== "function") { - throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var yieldHandler = Object(options).yieldHandler; - var PromiseSpawn$ = PromiseSpawn; - var stack = new Error().stack; - return function () { - var generator = generatorFunction.apply(this, arguments); - var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, - stack); - var ret = spawn.promise(); - spawn._generator = generator; - spawn._promiseFulfilled(undefined); - return ret; - }; -}; +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(); +} -Promise.coroutine.addYieldHandler = function(fn) { - if (typeof fn !== "function") { - throw new TypeError("expecting a function but got " + util.classString(fn)); - } - yieldHandlers.push(fn); -}; +Hook.Singular = HookSingular.bind(); +Hook.Collection = HookCollection.bind(); -Promise.spawn = function (generatorFunction) { - debug.deprecated("Promise.spawn()", "Promise.coroutine()"); - if (typeof generatorFunction !== "function") { - return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var spawn = new PromiseSpawn(generatorFunction, this); - var ret = spawn.promise(); - spawn._run(Promise.spawn); - return ret; -}; -}; +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; /***/ }), -/***/ 28578: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 5549: +/***/ ((module) => { -"use strict"; +module.exports = addHook; -module.exports = -function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, - getDomain) { -var util = __nccwpck_require__(37180); -var canEvaluate = util.canEvaluate; -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -var reject; - -if (true) { -if (canEvaluate) { - var thenCallback = function(i) { - return new Function("value", "holder", " \n\ - 'use strict'; \n\ - holder.pIndex = value; \n\ - holder.checkFulfillment(this); \n\ - ".replace(/Index/g, i)); - }; +function addHook(state, kind, name, hook) { + var orig = hook; + if (!state.registry[name]) { + state.registry[name] = []; + } - var promiseSetter = function(i) { - return new Function("promise", "holder", " \n\ - 'use strict'; \n\ - holder.pIndex = promise; \n\ - ".replace(/Index/g, i)); + if (kind === "before") { + hook = function (method, options) { + return Promise.resolve() + .then(orig.bind(null, options)) + .then(method.bind(null, options)); }; + } - var generateHolderClass = function(total) { - var props = new Array(total); - for (var i = 0; i < props.length; ++i) { - props[i] = "this.p" + (i+1); - } - var assignment = props.join(" = ") + " = null;"; - var cancellationCode= "var promise;\n" + props.map(function(prop) { - return " \n\ - promise = " + prop + "; \n\ - if (promise instanceof Promise) { \n\ - promise.cancel(); \n\ - } \n\ - "; - }).join("\n"); - var passedArguments = props.join(", "); - var name = "Holder$" + total; - - - var code = "return function(tryCatch, errorObj, Promise, async) { \n\ - 'use strict'; \n\ - function [TheName](fn) { \n\ - [TheProperties] \n\ - this.fn = fn; \n\ - this.asyncNeeded = true; \n\ - this.now = 0; \n\ - } \n\ - \n\ - [TheName].prototype._callFunction = function(promise) { \n\ - promise._pushContext(); \n\ - var ret = tryCatch(this.fn)([ThePassedArguments]); \n\ - promise._popContext(); \n\ - if (ret === errorObj) { \n\ - promise._rejectCallback(ret.e, false); \n\ - } else { \n\ - promise._resolveCallback(ret); \n\ - } \n\ - }; \n\ - \n\ - [TheName].prototype.checkFulfillment = function(promise) { \n\ - var now = ++this.now; \n\ - if (now === [TheTotal]) { \n\ - if (this.asyncNeeded) { \n\ - async.invoke(this._callFunction, this, promise); \n\ - } else { \n\ - this._callFunction(promise); \n\ - } \n\ - \n\ - } \n\ - }; \n\ - \n\ - [TheName].prototype._resultCancelled = function() { \n\ - [CancellationCode] \n\ - }; \n\ - \n\ - return [TheName]; \n\ - }(tryCatch, errorObj, Promise, async); \n\ - "; - - code = code.replace(/\[TheName\]/g, name) - .replace(/\[TheTotal\]/g, total) - .replace(/\[ThePassedArguments\]/g, passedArguments) - .replace(/\[TheProperties\]/g, assignment) - .replace(/\[CancellationCode\]/g, cancellationCode); - - return new Function("tryCatch", "errorObj", "Promise", "async", code) - (tryCatch, errorObj, Promise, async); + 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; + }); }; + } - var holderClasses = []; - var thenCallbacks = []; - var promiseSetters = []; - - for (var i = 0; i < 8; ++i) { - holderClasses.push(generateHolderClass(i + 1)); - thenCallbacks.push(thenCallback(i + 1)); - promiseSetters.push(promiseSetter(i + 1)); - } - - reject = function (reason) { - this._reject(reason); + if (kind === "error") { + hook = function (method, options) { + return Promise.resolve() + .then(method.bind(null, options)) + .catch(function (error) { + return orig(error, options); + }); }; -}} - -Promise.join = function () { - var last = arguments.length - 1; - var fn; - if (last > 0 && typeof arguments[last] === "function") { - fn = arguments[last]; - if (true) { - if (last <= 8 && canEvaluate) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - var HolderClass = holderClasses[last - 1]; - var holder = new HolderClass(fn); - var callbacks = thenCallbacks; - - for (var i = 0; i < last; ++i) { - var maybePromise = tryConvertToPromise(arguments[i], ret); - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - maybePromise._then(callbacks[i], reject, - undefined, ret, holder); - promiseSetters[i](maybePromise, holder); - holder.asyncNeeded = false; - } else if (((bitField & 33554432) !== 0)) { - callbacks[i].call(ret, - maybePromise._value(), holder); - } else if (((bitField & 16777216) !== 0)) { - ret._reject(maybePromise._reason()); - } else { - ret._cancel(); - } - } else { - callbacks[i].call(ret, maybePromise, holder); - } - } - - if (!ret._isFateSealed()) { - if (holder.asyncNeeded) { - var domain = getDomain(); - if (domain !== null) { - holder.fn = util.domainBind(domain, holder.fn); - } - } - ret._setAsyncGuaranteed(); - ret._setOnCancel(holder); - } - return ret; - } - } - } - var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];}; - if (fn) args.pop(); - var ret = new PromiseArray(args).promise(); - return fn !== undefined ? ret.spread(fn) : ret; -}; + } -}; + state.registry[name].push({ + hook: hook, + orig: orig, + }); +} /***/ }), -/***/ 64652: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = function(Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL, - debug) { -var getDomain = Promise._getDomain; -var util = __nccwpck_require__(37180); -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -var async = Promise._async; - -function MappingPromiseArray(promises, fn, limit, _filter) { - this.constructor$(promises); - this._promise._captureStackTrace(); - var domain = getDomain(); - this._callback = domain === null ? fn : util.domainBind(domain, fn); - this._preservedValues = _filter === INTERNAL - ? new Array(this.length()) - : null; - this._limit = limit; - this._inFlight = 0; - this._queue = []; - async.invoke(this._asyncInit, this, undefined); -} -util.inherits(MappingPromiseArray, PromiseArray); +/***/ 44670: +/***/ ((module) => { -MappingPromiseArray.prototype._asyncInit = function() { - this._init$(undefined, -2); -}; +module.exports = register; -MappingPromiseArray.prototype._init = function () {}; +function register(state, name, method, options) { + if (typeof method !== "function") { + throw new Error("method for before hook must be a function"); + } -MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { - var values = this._values; - var length = this.length(); - var preservedValues = this._preservedValues; - var limit = this._limit; + if (!options) { + options = {}; + } - if (index < 0) { - index = (index * -1) - 1; - values[index] = value; - if (limit >= 1) { - this._inFlight--; - this._drainQueue(); - if (this._isResolved()) return true; - } - } else { - if (limit >= 1 && this._inFlight >= limit) { - values[index] = value; - this._queue.push(index); - return false; - } - if (preservedValues !== null) preservedValues[index] = value; - - var promise = this._promise; - var callback = this._callback; - var receiver = promise._boundValue(); - promise._pushContext(); - var ret = tryCatch(callback).call(receiver, value, index, length); - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, - promiseCreated, - preservedValues !== null ? "Promise.filter" : "Promise.map", - promise - ); - if (ret === errorObj) { - this._reject(ret.e); - return true; - } + if (Array.isArray(name)) { + return name.reverse().reduce(function (callback, name) { + return register.bind(null, state, name, callback, options); + }, method)(); + } - var maybePromise = tryConvertToPromise(ret, this._promise); - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - if (limit >= 1) this._inFlight++; - values[index] = maybePromise; - maybePromise._proxy(this, (index + 1) * -1); - return false; - } else if (((bitField & 33554432) !== 0)) { - ret = maybePromise._value(); - } else if (((bitField & 16777216) !== 0)) { - this._reject(maybePromise._reason()); - return true; - } else { - this._cancel(); - return true; - } - } - values[index] = ret; - } - var totalResolved = ++this._totalResolved; - if (totalResolved >= length) { - if (preservedValues !== null) { - this._filter(values, preservedValues); - } else { - this._resolve(values); - } - return true; + return Promise.resolve().then(function () { + if (!state.registry[name]) { + return method(options); } - return false; -}; -MappingPromiseArray.prototype._drainQueue = function () { - var queue = this._queue; - var limit = this._limit; - var values = this._values; - while (queue.length > 0 && this._inFlight < limit) { - if (this._isResolved()) return; - var index = queue.pop(); - this._promiseFulfilled(values[index], index); - } -}; + return state.registry[name].reduce(function (method, registered) { + return registered.hook.bind(null, method, options); + }, method)(); + }); +} -MappingPromiseArray.prototype._filter = function (booleans, values) { - var len = values.length; - var ret = new Array(len); - var j = 0; - for (var i = 0; i < len; ++i) { - if (booleans[i]) ret[j++] = values[i]; - } - ret.length = j; - this._resolve(ret); -}; -MappingPromiseArray.prototype.preservedValues = function () { - return this._preservedValues; -}; +/***/ }), -function map(promises, fn, options, _filter) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } +/***/ 6819: +/***/ ((module) => { - var limit = 0; - if (options !== undefined) { - if (typeof options === "object" && options !== null) { - if (typeof options.concurrency !== "number") { - return Promise.reject( - new TypeError("'concurrency' must be a number but it is " + - util.classString(options.concurrency))); - } - limit = options.concurrency; - } else { - return Promise.reject(new TypeError( - "options argument must be an object but it is " + - util.classString(options))); - } - } - limit = typeof limit === "number" && - isFinite(limit) && limit >= 1 ? limit : 0; - return new MappingPromiseArray(promises, fn, limit, _filter).promise(); -} +module.exports = removeHook; -Promise.prototype.map = function (fn, options) { - return map(this, fn, options, null); -}; +function removeHook(state, name, method) { + if (!state.registry[name]) { + return; + } -Promise.map = function (promises, fn, options, _filter) { - return map(promises, fn, options, _filter); -}; + var index = state.registry[name] + .map(function (registered) { + return registered.orig; + }) + .indexOf(method); + if (index === -1) { + return; + } -}; + state.registry[name].splice(index, 1); +} /***/ }), -/***/ 44503: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 66474: +/***/ ((module, exports, __nccwpck_require__) => { -"use strict"; - -module.exports = -function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { -var util = __nccwpck_require__(37180); -var tryCatch = util.tryCatch; - -Promise.method = function (fn) { - if (typeof fn !== "function") { - throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); - } - return function () { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._pushContext(); - var value = tryCatch(fn).apply(this, arguments); - var promiseCreated = ret._popContext(); - debug.checkForgottenReturns( - value, promiseCreated, "Promise.method", ret); - ret._resolveFromSyncValue(value); - return ret; - }; -}; +var Chainsaw = __nccwpck_require__(46533); +var EventEmitter = (__nccwpck_require__(82361).EventEmitter); +var Buffers = __nccwpck_require__(51590); +var Vars = __nccwpck_require__(13755); +var Stream = (__nccwpck_require__(12781).Stream); -Promise.attempt = Promise["try"] = function (fn) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._pushContext(); - var value; - if (arguments.length > 1) { - debug.deprecated("calling Promise.try with more than 1 argument"); - var arg = arguments[1]; - var ctx = arguments[2]; - value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) - : tryCatch(fn).call(ctx, arg); - } else { - value = tryCatch(fn)(); +exports = module.exports = function (bufOrEm, eventName) { + if (Buffer.isBuffer(bufOrEm)) { + return exports.parse(bufOrEm); } - var promiseCreated = ret._popContext(); - debug.checkForgottenReturns( - value, promiseCreated, "Promise.try", ret); - ret._resolveFromSyncValue(value); - return ret; + + var s = exports.stream(); + if (bufOrEm && bufOrEm.pipe) { + bufOrEm.pipe(s); + } + else if (bufOrEm) { + bufOrEm.on(eventName || 'data', function (buf) { + s.write(buf); + }); + + bufOrEm.on('end', function () { + s.end(); + }); + } + return s; }; -Promise.prototype._resolveFromSyncValue = function (value) { - if (value === util.errorObj) { - this._rejectCallback(value.e, false); - } else { - this._resolveCallback(value, true); +exports.stream = function (input) { + if (input) return exports.apply(null, arguments); + + var pending = null; + function getBytes (bytes, cb, skip) { + pending = { + bytes : bytes, + skip : skip, + cb : function (buf) { + pending = null; + cb(buf); + }, + }; + dispatch(); } + + var offset = null; + function dispatch () { + if (!pending) { + if (caughtEnd) done = true; + return; + } + if (typeof pending === 'function') { + pending(); + } + else { + var bytes = offset + pending.bytes; + + if (buffers.length >= bytes) { + var buf; + if (offset == null) { + buf = buffers.splice(0, bytes); + if (!pending.skip) { + buf = buf.slice(); + } + } + else { + if (!pending.skip) { + buf = buffers.slice(offset, bytes); + } + offset = bytes; + } + + if (pending.skip) { + pending.cb(); + } + else { + pending.cb(buf); + } + } + } + } + + function builder (saw) { + function next () { if (!done) saw.next() } + + var self = words(function (bytes, cb) { + return function (name) { + getBytes(bytes, function (buf) { + vars.set(name, cb(buf)); + next(); + }); + }; + }); + + self.tap = function (cb) { + saw.nest(cb, vars.store); + }; + + self.into = function (key, cb) { + if (!vars.get(key)) vars.set(key, {}); + var parent = vars; + vars = Vars(parent.get(key)); + + saw.nest(function () { + cb.apply(this, arguments); + this.tap(function () { + vars = parent; + }); + }, vars.store); + }; + + self.flush = function () { + vars.store = {}; + next(); + }; + + self.loop = function (cb) { + var end = false; + + saw.nest(false, function loop () { + this.vars = vars.store; + cb.call(this, function () { + end = true; + next(); + }, vars.store); + this.tap(function () { + if (end) saw.next() + else loop.call(this) + }.bind(this)); + }, vars.store); + }; + + self.buffer = function (name, bytes) { + if (typeof bytes === 'string') { + bytes = vars.get(bytes); + } + + getBytes(bytes, function (buf) { + vars.set(name, buf); + next(); + }); + }; + + self.skip = function (bytes) { + if (typeof bytes === 'string') { + bytes = vars.get(bytes); + } + + getBytes(bytes, function () { + next(); + }); + }; + + self.scan = function find (name, search) { + if (typeof search === 'string') { + search = new Buffer(search); + } + else if (!Buffer.isBuffer(search)) { + throw new Error('search must be a Buffer or a string'); + } + + var taken = 0; + pending = function () { + var pos = buffers.indexOf(search, offset + taken); + var i = pos-offset-taken; + if (pos !== -1) { + pending = null; + if (offset != null) { + vars.set( + name, + buffers.slice(offset, offset + taken + i) + ); + offset += taken + i + search.length; + } + else { + vars.set( + name, + buffers.slice(0, taken + i) + ); + buffers.splice(0, taken + i + search.length); + } + next(); + dispatch(); + } else { + i = Math.max(buffers.length - search.length - offset - taken, 0); + } + taken += i; + }; + dispatch(); + }; + + self.peek = function (cb) { + offset = 0; + saw.nest(function () { + cb.call(this, vars.store); + this.tap(function () { + offset = null; + }); + }); + }; + + return self; + }; + + var stream = Chainsaw.light(builder); + stream.writable = true; + + var buffers = Buffers(); + + stream.write = function (buf) { + buffers.push(buf); + dispatch(); + }; + + var vars = Vars(); + + var done = false, caughtEnd = false; + stream.end = function () { + caughtEnd = true; + }; + + stream.pipe = Stream.prototype.pipe; + Object.getOwnPropertyNames(EventEmitter.prototype).forEach(function (name) { + stream[name] = EventEmitter.prototype[name]; + }); + + return stream; }; -}; - - -/***/ }), -/***/ 80683: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; +exports.parse = function parse (buffer) { + var self = words(function (bytes, cb) { + return function (name) { + if (offset + bytes <= buffer.length) { + var buf = buffer.slice(offset, offset + bytes); + offset += bytes; + vars.set(name, cb(buf)); + } + else { + vars.set(name, null); + } + return self; + }; + }); + + var offset = 0; + var vars = Vars(); + self.vars = vars.store; + + self.tap = function (cb) { + cb.call(self, vars.store); + return self; + }; + + self.into = function (key, cb) { + if (!vars.get(key)) { + vars.set(key, {}); + } + var parent = vars; + vars = Vars(parent.get(key)); + cb.call(self, vars.store); + vars = parent; + return self; + }; + + self.loop = function (cb) { + var end = false; + var ender = function () { end = true }; + while (end === false) { + cb.call(self, ender, vars.store); + } + return self; + }; + + self.buffer = function (name, size) { + if (typeof size === 'string') { + size = vars.get(size); + } + var buf = buffer.slice(offset, Math.min(buffer.length, offset + size)); + offset += size; + vars.set(name, buf); + + return self; + }; + + self.skip = function (bytes) { + if (typeof bytes === 'string') { + bytes = vars.get(bytes); + } + offset += bytes; + + return self; + }; + + self.scan = function (name, search) { + if (typeof search === 'string') { + search = new Buffer(search); + } + else if (!Buffer.isBuffer(search)) { + throw new Error('search must be a Buffer or a string'); + } + vars.set(name, null); + + // simple but slow string search + for (var i = 0; i + offset <= buffer.length - search.length + 1; i++) { + for ( + var j = 0; + j < search.length && buffer[offset+i+j] === search[j]; + j++ + ); + if (j === search.length) break; + } + + vars.set(name, buffer.slice(offset, offset + i)); + offset += i + search.length; + return self; + }; + + self.peek = function (cb) { + var was = offset; + cb.call(self, vars.store); + offset = was; + return self; + }; + + self.flush = function () { + vars.store = {}; + return self; + }; + + self.eof = function () { + return offset >= buffer.length; + }; + + return self; +}; -var util = __nccwpck_require__(37180); -var maybeWrapAsError = util.maybeWrapAsError; -var errors = __nccwpck_require__(44581); -var OperationalError = errors.OperationalError; -var es5 = __nccwpck_require__(61713); +// convert byte strings to unsigned little endian numbers +function decodeLEu (bytes) { + var acc = 0; + for (var i = 0; i < bytes.length; i++) { + acc += Math.pow(256,i) * bytes[i]; + } + return acc; +} -function isUntypedError(obj) { - return obj instanceof Error && - es5.getPrototypeOf(obj) === Error.prototype; +// convert byte strings to unsigned big endian numbers +function decodeBEu (bytes) { + var acc = 0; + for (var i = 0; i < bytes.length; i++) { + acc += Math.pow(256, bytes.length - i - 1) * bytes[i]; + } + return acc; } -var rErrorKey = /^(?:name|message|stack|cause)$/; -function wrapAsOperationalError(obj) { - var ret; - if (isUntypedError(obj)) { - ret = new OperationalError(obj); - ret.name = obj.name; - ret.message = obj.message; - ret.stack = obj.stack; - var keys = es5.keys(obj); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (!rErrorKey.test(key)) { - ret[key] = obj[key]; - } - } - return ret; +// convert byte strings to signed big endian numbers +function decodeBEs (bytes) { + var val = decodeBEu(bytes); + if ((bytes[0] & 0x80) == 0x80) { + val -= Math.pow(256, bytes.length); } - util.markAsOriginatingFromRejection(obj); - return obj; + return val; } -function nodebackForPromise(promise, multiArgs) { - return function(err, value) { - if (promise === null) return; - if (err) { - var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); - promise._attachExtraTrace(wrapped); - promise._reject(wrapped); - } else if (!multiArgs) { - promise._fulfill(value); - } else { - var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}; - promise._fulfill(args); - } - promise = null; - }; +// convert byte strings to signed little endian numbers +function decodeLEs (bytes) { + var val = decodeLEu(bytes); + if ((bytes[bytes.length - 1] & 0x80) == 0x80) { + val -= Math.pow(256, bytes.length); + } + return val; } -module.exports = nodebackForPromise; +function words (decode) { + var self = {}; + + [ 1, 2, 4, 8 ].forEach(function (bytes) { + var bits = bytes * 8; + + self['word' + bits + 'le'] + = self['word' + bits + 'lu'] + = decode(bytes, decodeLEu); + + self['word' + bits + 'ls'] + = decode(bytes, decodeLEs); + + self['word' + bits + 'be'] + = self['word' + bits + 'bu'] + = decode(bytes, decodeBEu); + + self['word' + bits + 'bs'] + = decode(bytes, decodeBEs); + }); + + // word8be(n) == word8le(n) for all n + self.word8 = self.word8u = self.word8be; + self.word8s = self.word8bs; + + return self; +} /***/ }), -/***/ 2576: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; +/***/ 13755: +/***/ ((module) => { -module.exports = function(Promise) { -var util = __nccwpck_require__(37180); -var async = Promise._async; -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; - -function spreadAdapter(val, nodeback) { - var promise = this; - if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); - var ret = - tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val)); - if (ret === errorObj) { - async.throwLater(ret.e); - } -} - -function successAdapter(val, nodeback) { - var promise = this; - var receiver = promise._boundValue(); - var ret = val === undefined - ? tryCatch(nodeback).call(receiver, null) - : tryCatch(nodeback).call(receiver, null, val); - if (ret === errorObj) { - async.throwLater(ret.e); - } -} -function errorAdapter(reason, nodeback) { - var promise = this; - if (!reason) { - var newReason = new Error(reason + ""); - newReason.cause = reason; - reason = newReason; - } - var ret = tryCatch(nodeback).call(promise._boundValue(), reason); - if (ret === errorObj) { - async.throwLater(ret.e); - } -} - -Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback, - options) { - if (typeof nodeback == "function") { - var adapter = successAdapter; - if (options !== undefined && Object(options).spread) { - adapter = spreadAdapter; - } - this._then( - adapter, - errorAdapter, - undefined, - this, - nodeback - ); +module.exports = function (store) { + function getset (name, value) { + var node = vars.store; + var keys = name.split('.'); + keys.slice(0,-1).forEach(function (k) { + if (node[k] === undefined) node[k] = {}; + node = node[k] + }); + var key = keys[keys.length - 1]; + if (arguments.length == 1) { + return node[key]; + } + else { + return node[key] = value; + } } - return this; -}; + + var vars = { + get : function (name) { + return getset(name); + }, + set : function (name, value) { + return getset(name, value); + }, + store : store || {}, + }; + return vars; }; /***/ }), -/***/ 73807: +/***/ 23664: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -module.exports = function() { -var makeSelfResolutionError = function () { - return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a"); -}; -var reflectHandler = function() { - return new Promise.PromiseInspection(this._target()); -}; -var apiRejection = function(msg) { - return Promise.reject(new TypeError(msg)); -}; -function Proxyable() {} -var UNDEFINED_BINDING = {}; -var util = __nccwpck_require__(37180); - -var getDomain; -if (util.isNode) { - getDomain = function() { - var ret = process.domain; - if (ret === undefined) ret = null; - return ret; - }; -} else { - getDomain = function() { - return null; - }; -} -util.notEnumerableProp(Promise, "_getDomain", getDomain); - -var es5 = __nccwpck_require__(61713); -var Async = __nccwpck_require__(66812); -var async = new Async(); -es5.defineProperty(Promise, "_async", {value: async}); -var errors = __nccwpck_require__(44581); -var TypeError = Promise.TypeError = errors.TypeError; -Promise.RangeError = errors.RangeError; -var CancellationError = Promise.CancellationError = errors.CancellationError; -Promise.TimeoutError = errors.TimeoutError; -Promise.OperationalError = errors.OperationalError; -Promise.RejectionError = errors.OperationalError; -Promise.AggregateError = errors.AggregateError; -var INTERNAL = function(){}; -var APPLY = {}; -var NEXT_FILTER = {}; -var tryConvertToPromise = __nccwpck_require__(19400)(Promise, INTERNAL); -var PromiseArray = - __nccwpck_require__(86843)(Promise, INTERNAL, - tryConvertToPromise, apiRejection, Proxyable); -var Context = __nccwpck_require__(38518)(Promise); - /*jshint unused:false*/ -var createContext = Context.create; -var debug = __nccwpck_require__(30581)(Promise, Context); -var CapturedTrace = debug.CapturedTrace; -var PassThroughHandlerContext = - __nccwpck_require__(75523)(Promise, tryConvertToPromise); -var catchFilter = __nccwpck_require__(87855)(NEXT_FILTER); -var nodebackForPromise = __nccwpck_require__(80683); -var errorObj = util.errorObj; -var tryCatch = util.tryCatch; -function check(self, executor) { - if (typeof executor !== "function") { - throw new TypeError("expecting a function but got " + util.classString(executor)); - } - if (self.constructor !== Promise) { - throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } -} - -function Promise(executor) { - this._bitField = 0; - this._fulfillmentHandler0 = undefined; - this._rejectionHandler0 = undefined; - this._promise0 = undefined; - this._receiver0 = undefined; - if (executor !== INTERNAL) { - check(this, executor); - this._resolveFromExecutor(executor); - } - this._promiseCreated(); - this._fireEvent("promiseCreated", this); -} - -Promise.prototype.toString = function () { - return "[object Promise]"; -}; - -Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { - var len = arguments.length; - if (len > 1) { - var catchInstances = new Array(len - 1), - j = 0, i; - for (i = 0; i < len - 1; ++i) { - var item = arguments[i]; - if (util.isObject(item)) { - catchInstances[j++] = item; - } else { - return apiRejection("expecting an object but got " + - "A catch statement predicate " + util.classString(item)); - } - } - catchInstances.length = j; - fn = arguments[i]; - return this.then(undefined, catchFilter(catchInstances, fn, this)); - } - return this.then(undefined, fn); -}; -Promise.prototype.reflect = function () { - return this._then(reflectHandler, - reflectHandler, undefined, this, undefined); -}; +const { Buffer } = __nccwpck_require__(14300) +const symbol = Symbol.for('BufferList') -Promise.prototype.then = function (didFulfill, didReject) { - if (debug.warnings() && arguments.length > 0 && - typeof didFulfill !== "function" && - typeof didReject !== "function") { - var msg = ".then() only accepts functions but was passed: " + - util.classString(didFulfill); - if (arguments.length > 1) { - msg += ", " + util.classString(didReject); - } - this._warn(msg); - } - return this._then(didFulfill, didReject, undefined, undefined, undefined); -}; +function BufferList (buf) { + if (!(this instanceof BufferList)) { + return new BufferList(buf) + } -Promise.prototype.done = function (didFulfill, didReject) { - var promise = - this._then(didFulfill, didReject, undefined, undefined, undefined); - promise._setIsFinal(); -}; + BufferList._init.call(this, buf) +} -Promise.prototype.spread = function (fn) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - return this.all()._then(fn, undefined, undefined, APPLY, undefined); -}; +BufferList._init = function _init (buf) { + Object.defineProperty(this, symbol, { value: true }) -Promise.prototype.toJSON = function () { - var ret = { - isFulfilled: false, - isRejected: false, - fulfillmentValue: undefined, - rejectionReason: undefined - }; - if (this.isFulfilled()) { - ret.fulfillmentValue = this.value(); - ret.isFulfilled = true; - } else if (this.isRejected()) { - ret.rejectionReason = this.reason(); - ret.isRejected = true; - } - return ret; -}; + this._bufs = [] + this.length = 0 -Promise.prototype.all = function () { - if (arguments.length > 0) { - this._warn(".all() was passed arguments but it does not take any"); - } - return new PromiseArray(this).promise(); -}; + if (buf) { + this.append(buf) + } +} -Promise.prototype.error = function (fn) { - return this.caught(util.originatesFromRejection, fn); -}; +BufferList.prototype._new = function _new (buf) { + return new BufferList(buf) +} -Promise.getNewLibraryCopy = module.exports; +BufferList.prototype._offset = function _offset (offset) { + if (offset === 0) { + return [0, 0] + } -Promise.is = function (val) { - return val instanceof Promise; -}; + let tot = 0 -Promise.fromNode = Promise.fromCallback = function(fn) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs - : false; - var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); - if (result === errorObj) { - ret._rejectCallback(result.e, true); + for (let i = 0; i < this._bufs.length; i++) { + const _t = tot + this._bufs[i].length + if (offset < _t || i === this._bufs.length - 1) { + return [i, offset - tot] } - if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); - return ret; -}; + tot = _t + } +} -Promise.all = function (promises) { - return new PromiseArray(promises).promise(); -}; +BufferList.prototype._reverseOffset = function (blOffset) { + const bufferId = blOffset[0] + let offset = blOffset[1] -Promise.cast = function (obj) { - var ret = tryConvertToPromise(obj); - if (!(ret instanceof Promise)) { - ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._setFulfilled(); - ret._rejectionHandler0 = obj; - } - return ret; -}; + for (let i = 0; i < bufferId; i++) { + offset += this._bufs[i].length + } -Promise.resolve = Promise.fulfilled = Promise.cast; + return offset +} -Promise.reject = Promise.rejected = function (reason) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._rejectCallback(reason, true); - return ret; -}; +BufferList.prototype.get = function get (index) { + if (index > this.length || index < 0) { + return undefined + } -Promise.setScheduler = function(fn) { - if (typeof fn !== "function") { - throw new TypeError("expecting a function but got " + util.classString(fn)); - } - return async.setScheduler(fn); -}; + const offset = this._offset(index) -Promise.prototype._then = function ( - didFulfill, - didReject, - _, receiver, - internalData -) { - var haveInternalData = internalData !== undefined; - var promise = haveInternalData ? internalData : new Promise(INTERNAL); - var target = this._target(); - var bitField = target._bitField; - - if (!haveInternalData) { - promise._propagateFrom(this, 3); - promise._captureStackTrace(); - if (receiver === undefined && - ((this._bitField & 2097152) !== 0)) { - if (!((bitField & 50397184) === 0)) { - receiver = this._boundValue(); - } else { - receiver = target === this ? undefined : this._boundTo; - } - } - this._fireEvent("promiseChained", this, promise); - } + return this._bufs[offset[0]][offset[1]] +} - var domain = getDomain(); - if (!((bitField & 50397184) === 0)) { - var handler, value, settler = target._settlePromiseCtx; - if (((bitField & 33554432) !== 0)) { - value = target._rejectionHandler0; - handler = didFulfill; - } else if (((bitField & 16777216) !== 0)) { - value = target._fulfillmentHandler0; - handler = didReject; - target._unsetRejectionIsUnhandled(); - } else { - settler = target._settlePromiseLateCancellationObserver; - value = new CancellationError("late cancellation observer"); - target._attachExtraTrace(value); - handler = didReject; - } - - async.invoke(settler, target, { - handler: domain === null ? handler - : (typeof handler === "function" && - util.domainBind(domain, handler)), - promise: promise, - receiver: receiver, - value: value - }); - } else { - target._addCallbacks(didFulfill, didReject, promise, receiver, domain); - } +BufferList.prototype.slice = function slice (start, end) { + if (typeof start === 'number' && start < 0) { + start += this.length + } - return promise; -}; + if (typeof end === 'number' && end < 0) { + end += this.length + } -Promise.prototype._length = function () { - return this._bitField & 65535; -}; + return this.copy(null, 0, start, end) +} -Promise.prototype._isFateSealed = function () { - return (this._bitField & 117506048) !== 0; -}; +BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) { + if (typeof srcStart !== 'number' || srcStart < 0) { + srcStart = 0 + } -Promise.prototype._isFollowing = function () { - return (this._bitField & 67108864) === 67108864; -}; + if (typeof srcEnd !== 'number' || srcEnd > this.length) { + srcEnd = this.length + } -Promise.prototype._setLength = function (len) { - this._bitField = (this._bitField & -65536) | - (len & 65535); -}; + if (srcStart >= this.length) { + return dst || Buffer.alloc(0) + } -Promise.prototype._setFulfilled = function () { - this._bitField = this._bitField | 33554432; - this._fireEvent("promiseFulfilled", this); -}; + if (srcEnd <= 0) { + return dst || Buffer.alloc(0) + } -Promise.prototype._setRejected = function () { - this._bitField = this._bitField | 16777216; - this._fireEvent("promiseRejected", this); -}; + const copy = !!dst + const off = this._offset(srcStart) + const len = srcEnd - srcStart + let bytes = len + let bufoff = (copy && dstStart) || 0 + let start = off[1] -Promise.prototype._setFollowing = function () { - this._bitField = this._bitField | 67108864; - this._fireEvent("promiseResolved", this); -}; + // copy/slice everything + if (srcStart === 0 && srcEnd === this.length) { + if (!copy) { + // slice, but full concat if multiple buffers + return this._bufs.length === 1 + ? this._bufs[0] + : Buffer.concat(this._bufs, this.length) + } -Promise.prototype._setIsFinal = function () { - this._bitField = this._bitField | 4194304; -}; + // copy, need to copy individual buffers + for (let i = 0; i < this._bufs.length; i++) { + this._bufs[i].copy(dst, bufoff) + bufoff += this._bufs[i].length + } -Promise.prototype._isFinal = function () { - return (this._bitField & 4194304) > 0; -}; + return dst + } -Promise.prototype._unsetCancelled = function() { - this._bitField = this._bitField & (~65536); -}; + // easy, cheap case where it's a subset of one of the buffers + if (bytes <= this._bufs[off[0]].length - start) { + return copy + ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) + : this._bufs[off[0]].slice(start, start + bytes) + } -Promise.prototype._setCancelled = function() { - this._bitField = this._bitField | 65536; - this._fireEvent("promiseCancelled", this); -}; + if (!copy) { + // a slice, we need something to copy in to + dst = Buffer.allocUnsafe(len) + } -Promise.prototype._setWillBeCancelled = function() { - this._bitField = this._bitField | 8388608; -}; + for (let i = off[0]; i < this._bufs.length; i++) { + const l = this._bufs[i].length - start -Promise.prototype._setAsyncGuaranteed = function() { - if (async.hasCustomScheduler()) return; - this._bitField = this._bitField | 134217728; -}; + if (bytes > l) { + this._bufs[i].copy(dst, bufoff, start) + bufoff += l + } else { + this._bufs[i].copy(dst, bufoff, start, start + bytes) + bufoff += l + break + } -Promise.prototype._receiverAt = function (index) { - var ret = index === 0 ? this._receiver0 : this[ - index * 4 - 4 + 3]; - if (ret === UNDEFINED_BINDING) { - return undefined; - } else if (ret === undefined && this._isBound()) { - return this._boundValue(); + bytes -= l + + if (start) { + start = 0 } - return ret; -}; + } -Promise.prototype._promiseAt = function (index) { - return this[ - index * 4 - 4 + 2]; -}; + // safeguard so that we don't return uninitialized memory + if (dst.length > bufoff) return dst.slice(0, bufoff) -Promise.prototype._fulfillmentHandlerAt = function (index) { - return this[ - index * 4 - 4 + 0]; -}; + return dst +} -Promise.prototype._rejectionHandlerAt = function (index) { - return this[ - index * 4 - 4 + 1]; -}; +BufferList.prototype.shallowSlice = function shallowSlice (start, end) { + start = start || 0 + end = typeof end !== 'number' ? this.length : end -Promise.prototype._boundValue = function() {}; + if (start < 0) { + start += this.length + } -Promise.prototype._migrateCallback0 = function (follower) { - var bitField = follower._bitField; - var fulfill = follower._fulfillmentHandler0; - var reject = follower._rejectionHandler0; - var promise = follower._promise0; - var receiver = follower._receiverAt(0); - if (receiver === undefined) receiver = UNDEFINED_BINDING; - this._addCallbacks(fulfill, reject, promise, receiver, null); -}; + if (end < 0) { + end += this.length + } -Promise.prototype._migrateCallbackAt = function (follower, index) { - var fulfill = follower._fulfillmentHandlerAt(index); - var reject = follower._rejectionHandlerAt(index); - var promise = follower._promiseAt(index); - var receiver = follower._receiverAt(index); - if (receiver === undefined) receiver = UNDEFINED_BINDING; - this._addCallbacks(fulfill, reject, promise, receiver, null); -}; + if (start === end) { + return this._new() + } -Promise.prototype._addCallbacks = function ( - fulfill, - reject, - promise, - receiver, - domain -) { - var index = this._length(); + const startOffset = this._offset(start) + const endOffset = this._offset(end) + const buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1) - if (index >= 65535 - 4) { - index = 0; - this._setLength(0); - } + if (endOffset[1] === 0) { + buffers.pop() + } else { + buffers[buffers.length - 1] = buffers[buffers.length - 1].slice(0, endOffset[1]) + } - if (index === 0) { - this._promise0 = promise; - this._receiver0 = receiver; - if (typeof fulfill === "function") { - this._fulfillmentHandler0 = - domain === null ? fulfill : util.domainBind(domain, fulfill); - } - if (typeof reject === "function") { - this._rejectionHandler0 = - domain === null ? reject : util.domainBind(domain, reject); - } + if (startOffset[1] !== 0) { + buffers[0] = buffers[0].slice(startOffset[1]) + } + + return this._new(buffers) +} + +BufferList.prototype.toString = function toString (encoding, start, end) { + return this.slice(start, end).toString(encoding) +} + +BufferList.prototype.consume = function consume (bytes) { + // first, normalize the argument, in accordance with how Buffer does it + bytes = Math.trunc(bytes) + // do nothing if not a positive number + if (Number.isNaN(bytes) || bytes <= 0) return this + + while (this._bufs.length) { + if (bytes >= this._bufs[0].length) { + bytes -= this._bufs[0].length + this.length -= this._bufs[0].length + this._bufs.shift() } else { - var base = index * 4 - 4; - this[base + 2] = promise; - this[base + 3] = receiver; - if (typeof fulfill === "function") { - this[base + 0] = - domain === null ? fulfill : util.domainBind(domain, fulfill); - } - if (typeof reject === "function") { - this[base + 1] = - domain === null ? reject : util.domainBind(domain, reject); - } + this._bufs[0] = this._bufs[0].slice(bytes) + this.length -= bytes + break } - this._setLength(index + 1); - return index; -}; + } -Promise.prototype._proxy = function (proxyable, arg) { - this._addCallbacks(undefined, undefined, arg, proxyable, null); -}; + return this +} -Promise.prototype._resolveCallback = function(value, shouldBind) { - if (((this._bitField & 117506048) !== 0)) return; - if (value === this) - return this._rejectCallback(makeSelfResolutionError(), false); - var maybePromise = tryConvertToPromise(value, this); - if (!(maybePromise instanceof Promise)) return this._fulfill(value); +BufferList.prototype.duplicate = function duplicate () { + const copy = this._new() - if (shouldBind) this._propagateFrom(maybePromise, 2); + for (let i = 0; i < this._bufs.length; i++) { + copy.append(this._bufs[i]) + } - var promise = maybePromise._target(); + return copy +} - if (promise === this) { - this._reject(makeSelfResolutionError()); - return; - } +BufferList.prototype.append = function append (buf) { + if (buf == null) { + return this + } - var bitField = promise._bitField; - if (((bitField & 50397184) === 0)) { - var len = this._length(); - if (len > 0) promise._migrateCallback0(this); - for (var i = 1; i < len; ++i) { - promise._migrateCallbackAt(this, i); - } - this._setFollowing(); - this._setLength(0); - this._setFollowee(promise); - } else if (((bitField & 33554432) !== 0)) { - this._fulfill(promise._value()); - } else if (((bitField & 16777216) !== 0)) { - this._reject(promise._reason()); - } else { - var reason = new CancellationError("late cancellation observer"); - promise._attachExtraTrace(reason); - this._reject(reason); + if (buf.buffer) { + // append a view of the underlying ArrayBuffer + this._appendBuffer(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)) + } else if (Array.isArray(buf)) { + for (let i = 0; i < buf.length; i++) { + this.append(buf[i]) } -}; - -Promise.prototype._rejectCallback = -function(reason, synchronous, ignoreNonErrorWarnings) { - var trace = util.ensureErrorObject(reason); - var hasStack = trace === reason; - if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { - var message = "a promise was rejected with a non-error: " + - util.classString(reason); - this._warn(message, true); + } else if (this._isBufferList(buf)) { + // unwrap argument into individual BufferLists + for (let i = 0; i < buf._bufs.length; i++) { + this.append(buf._bufs[i]) + } + } else { + // coerce number arguments to strings, since Buffer(number) does + // uninitialized memory allocation + if (typeof buf === 'number') { + buf = buf.toString() } - this._attachExtraTrace(trace, synchronous ? hasStack : false); - this._reject(reason); -}; -Promise.prototype._resolveFromExecutor = function (executor) { - var promise = this; - this._captureStackTrace(); - this._pushContext(); - var synchronous = true; - var r = this._execute(executor, function(value) { - promise._resolveCallback(value); - }, function (reason) { - promise._rejectCallback(reason, synchronous); - }); - synchronous = false; - this._popContext(); + this._appendBuffer(Buffer.from(buf)) + } - if (r !== undefined) { - promise._rejectCallback(r, true); - } -}; + return this +} -Promise.prototype._settlePromiseFromHandler = function ( - handler, receiver, value, promise -) { - var bitField = promise._bitField; - if (((bitField & 65536) !== 0)) return; - promise._pushContext(); - var x; - if (receiver === APPLY) { - if (!value || typeof value.length !== "number") { - x = errorObj; - x.e = new TypeError("cannot .spread() a non-array: " + - util.classString(value)); - } else { - x = tryCatch(handler).apply(this._boundValue(), value); - } - } else { - x = tryCatch(handler).call(receiver, value); - } - var promiseCreated = promise._popContext(); - bitField = promise._bitField; - if (((bitField & 65536) !== 0)) return; +BufferList.prototype._appendBuffer = function appendBuffer (buf) { + this._bufs.push(buf) + this.length += buf.length +} - if (x === NEXT_FILTER) { - promise._reject(value); - } else if (x === errorObj) { - promise._rejectCallback(x.e, false); - } else { - debug.checkForgottenReturns(x, promiseCreated, "", promise, this); - promise._resolveCallback(x); - } -}; +BufferList.prototype.indexOf = function (search, offset, encoding) { + if (encoding === undefined && typeof offset === 'string') { + encoding = offset + offset = undefined + } -Promise.prototype._target = function() { - var ret = this; - while (ret._isFollowing()) ret = ret._followee(); - return ret; -}; + if (typeof search === 'function' || Array.isArray(search)) { + throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.') + } else if (typeof search === 'number') { + search = Buffer.from([search]) + } else if (typeof search === 'string') { + search = Buffer.from(search, encoding) + } else if (this._isBufferList(search)) { + search = search.slice() + } else if (Array.isArray(search.buffer)) { + search = Buffer.from(search.buffer, search.byteOffset, search.byteLength) + } else if (!Buffer.isBuffer(search)) { + search = Buffer.from(search) + } -Promise.prototype._followee = function() { - return this._rejectionHandler0; -}; + offset = Number(offset || 0) -Promise.prototype._setFollowee = function(promise) { - this._rejectionHandler0 = promise; -}; + if (isNaN(offset)) { + offset = 0 + } -Promise.prototype._settlePromise = function(promise, handler, receiver, value) { - var isPromise = promise instanceof Promise; - var bitField = this._bitField; - var asyncGuaranteed = ((bitField & 134217728) !== 0); - if (((bitField & 65536) !== 0)) { - if (isPromise) promise._invokeInternalOnCancel(); + if (offset < 0) { + offset = this.length + offset + } - if (receiver instanceof PassThroughHandlerContext && - receiver.isFinallyHandler()) { - receiver.cancelPromise = promise; - if (tryCatch(handler).call(receiver, value) === errorObj) { - promise._reject(errorObj.e); - } - } else if (handler === reflectHandler) { - promise._fulfill(reflectHandler.call(receiver)); - } else if (receiver instanceof Proxyable) { - receiver._promiseCancelled(promise); - } else if (isPromise || promise instanceof PromiseArray) { - promise._cancel(); - } else { - receiver.cancel(); - } - } else if (typeof handler === "function") { - if (!isPromise) { - handler.call(receiver, value, promise); - } else { - if (asyncGuaranteed) promise._setAsyncGuaranteed(); - this._settlePromiseFromHandler(handler, receiver, value, promise); - } - } else if (receiver instanceof Proxyable) { - if (!receiver._isResolved()) { - if (((bitField & 33554432) !== 0)) { - receiver._promiseFulfilled(value, promise); - } else { - receiver._promiseRejected(value, promise); - } - } - } else if (isPromise) { - if (asyncGuaranteed) promise._setAsyncGuaranteed(); - if (((bitField & 33554432) !== 0)) { - promise._fulfill(value); - } else { - promise._reject(value); - } - } -}; + if (offset < 0) { + offset = 0 + } -Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { - var handler = ctx.handler; - var promise = ctx.promise; - var receiver = ctx.receiver; - var value = ctx.value; - if (typeof handler === "function") { - if (!(promise instanceof Promise)) { - handler.call(receiver, value, promise); - } else { - this._settlePromiseFromHandler(handler, receiver, value, promise); - } - } else if (promise instanceof Promise) { - promise._reject(value); - } -}; + if (search.length === 0) { + return offset > this.length ? this.length : offset + } -Promise.prototype._settlePromiseCtx = function(ctx) { - this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); -}; + const blOffset = this._offset(offset) + let blIndex = blOffset[0] // index of which internal buffer we're working on + let buffOffset = blOffset[1] // offset of the internal buffer we're working on -Promise.prototype._settlePromise0 = function(handler, value, bitField) { - var promise = this._promise0; - var receiver = this._receiverAt(0); - this._promise0 = undefined; - this._receiver0 = undefined; - this._settlePromise(promise, handler, receiver, value); -}; + // scan over each buffer + for (; blIndex < this._bufs.length; blIndex++) { + const buff = this._bufs[blIndex] -Promise.prototype._clearCallbackDataAtIndex = function(index) { - var base = index * 4 - 4; - this[base + 2] = - this[base + 3] = - this[base + 0] = - this[base + 1] = undefined; -}; + while (buffOffset < buff.length) { + const availableWindow = buff.length - buffOffset -Promise.prototype._fulfill = function (value) { - var bitField = this._bitField; - if (((bitField & 117506048) >>> 16)) return; - if (value === this) { - var err = makeSelfResolutionError(); - this._attachExtraTrace(err); - return this._reject(err); - } - this._setFulfilled(); - this._rejectionHandler0 = value; + if (availableWindow >= search.length) { + const nativeSearchResult = buff.indexOf(search, buffOffset) - if ((bitField & 65535) > 0) { - if (((bitField & 134217728) !== 0)) { - this._settlePromises(); - } else { - async.settlePromises(this); + if (nativeSearchResult !== -1) { + return this._reverseOffset([blIndex, nativeSearchResult]) } - } -}; -Promise.prototype._reject = function (reason) { - var bitField = this._bitField; - if (((bitField & 117506048) >>> 16)) return; - this._setRejected(); - this._fulfillmentHandler0 = reason; + buffOffset = buff.length - search.length + 1 // end of native search window + } else { + const revOffset = this._reverseOffset([blIndex, buffOffset]) - if (this._isFinal()) { - return async.fatalError(reason, util.isNode); - } + if (this._match(revOffset, search)) { + return revOffset + } - if ((bitField & 65535) > 0) { - async.settlePromises(this); - } else { - this._ensurePossibleRejectionHandled(); + buffOffset++ + } } -}; -Promise.prototype._fulfillPromises = function (len, value) { - for (var i = 1; i < len; i++) { - var handler = this._fulfillmentHandlerAt(i); - var promise = this._promiseAt(i); - var receiver = this._receiverAt(i); - this._clearCallbackDataAtIndex(i); - this._settlePromise(promise, handler, receiver, value); - } -}; + buffOffset = 0 + } -Promise.prototype._rejectPromises = function (len, reason) { - for (var i = 1; i < len; i++) { - var handler = this._rejectionHandlerAt(i); - var promise = this._promiseAt(i); - var receiver = this._receiverAt(i); - this._clearCallbackDataAtIndex(i); - this._settlePromise(promise, handler, receiver, reason); - } -}; + return -1 +} -Promise.prototype._settlePromises = function () { - var bitField = this._bitField; - var len = (bitField & 65535); +BufferList.prototype._match = function (offset, search) { + if (this.length - offset < search.length) { + return false + } - if (len > 0) { - if (((bitField & 16842752) !== 0)) { - var reason = this._fulfillmentHandler0; - this._settlePromise0(this._rejectionHandler0, reason, bitField); - this._rejectPromises(len, reason); - } else { - var value = this._rejectionHandler0; - this._settlePromise0(this._fulfillmentHandler0, value, bitField); - this._fulfillPromises(len, value); - } - this._setLength(0); + for (let searchOffset = 0; searchOffset < search.length; searchOffset++) { + if (this.get(offset + searchOffset) !== search[searchOffset]) { + return false } - this._clearCancellationData(); -}; + } + return true +} -Promise.prototype._settledValue = function() { - var bitField = this._bitField; - if (((bitField & 33554432) !== 0)) { - return this._rejectionHandler0; - } else if (((bitField & 16777216) !== 0)) { - return this._fulfillmentHandler0; - } -}; +;(function () { + const methods = { + readDoubleBE: 8, + readDoubleLE: 8, + readFloatBE: 4, + readFloatLE: 4, + readInt32BE: 4, + readInt32LE: 4, + readUInt32BE: 4, + readUInt32LE: 4, + readInt16BE: 2, + readInt16LE: 2, + readUInt16BE: 2, + readUInt16LE: 2, + readInt8: 1, + readUInt8: 1, + readIntBE: null, + readIntLE: null, + readUIntBE: null, + readUIntLE: null + } -function deferResolve(v) {this.promise._resolveCallback(v);} -function deferReject(v) {this.promise._rejectCallback(v, false);} + for (const m in methods) { + (function (m) { + if (methods[m] === null) { + BufferList.prototype[m] = function (offset, byteLength) { + return this.slice(offset, offset + byteLength)[m](0, byteLength) + } + } else { + BufferList.prototype[m] = function (offset = 0) { + return this.slice(offset, offset + methods[m])[m](0) + } + } + }(m)) + } +}()) -Promise.defer = Promise.pending = function() { - debug.deprecated("Promise.defer", "new Promise"); - var promise = new Promise(INTERNAL); - return { - promise: promise, - resolve: deferResolve, - reject: deferReject - }; -}; +// Used internally by the class and also as an indicator of this object being +// a `BufferList`. It's not possible to use `instanceof BufferList` in a browser +// environment because there could be multiple different copies of the +// BufferList class and some `BufferList`s might be `BufferList`s. +BufferList.prototype._isBufferList = function _isBufferList (b) { + return b instanceof BufferList || BufferList.isBufferList(b) +} -util.notEnumerableProp(Promise, - "_makeSelfResolutionError", - makeSelfResolutionError); - -__nccwpck_require__(44503)(Promise, INTERNAL, tryConvertToPromise, apiRejection, - debug); -__nccwpck_require__(4999)(Promise, INTERNAL, tryConvertToPromise, debug); -__nccwpck_require__(27862)(Promise, PromiseArray, apiRejection, debug); -__nccwpck_require__(36037)(Promise); -__nccwpck_require__(35506)(Promise); -__nccwpck_require__(28578)( - Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain); -Promise.Promise = Promise; -Promise.version = "3.4.7"; -__nccwpck_require__(64652)(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); -__nccwpck_require__(89343)(Promise); -__nccwpck_require__(324)(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); -__nccwpck_require__(31433)(Promise, INTERNAL, debug); -__nccwpck_require__(85241)(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); -__nccwpck_require__(2576)(Promise); -__nccwpck_require__(16290)(Promise, INTERNAL); -__nccwpck_require__(6237)(Promise, PromiseArray, tryConvertToPromise, apiRejection); -__nccwpck_require__(9493)(Promise, INTERNAL, tryConvertToPromise, apiRejection); -__nccwpck_require__(44712)(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); -__nccwpck_require__(25625)(Promise, PromiseArray, debug); -__nccwpck_require__(85041)(Promise, PromiseArray, apiRejection); -__nccwpck_require__(87096)(Promise, INTERNAL); -__nccwpck_require__(56189)(Promise, INTERNAL); -__nccwpck_require__(67044)(Promise); - - util.toFastProperties(Promise); - util.toFastProperties(Promise.prototype); - function fillTypes(value) { - var p = new Promise(INTERNAL); - p._fulfillmentHandler0 = value; - p._rejectionHandler0 = value; - p._promise0 = value; - p._receiver0 = value; - } - // Complete slack tracking, opt out of field-type tracking and - // stabilize map - fillTypes({a: 1}); - fillTypes({b: 2}); - fillTypes({c: 3}); - fillTypes(1); - fillTypes(function(){}); - fillTypes(undefined); - fillTypes(false); - fillTypes(new Promise(INTERNAL)); - debug.setBounds(Async.firstLineError, util.lastLineError); - return Promise; +BufferList.isBufferList = function isBufferList (b) { + return b != null && b[symbol] +} -}; +module.exports = BufferList /***/ }), -/***/ 86843: +/***/ 20336: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -module.exports = function(Promise, INTERNAL, tryConvertToPromise, - apiRejection, Proxyable) { -var util = __nccwpck_require__(37180); -var isArray = util.isArray; - -function toResolutionValue(val) { - switch(val) { - case -2: return []; - case -3: return {}; - } -} - -function PromiseArray(values) { - var promise = this._promise = new Promise(INTERNAL); - if (values instanceof Promise) { - promise._propagateFrom(values, 3); - } - promise._setOnCancel(this); - this._values = values; - this._length = 0; - this._totalResolved = 0; - this._init(undefined, -2); -} -util.inherits(PromiseArray, Proxyable); -PromiseArray.prototype.length = function () { - return this._length; -}; +const DuplexStream = (__nccwpck_require__(51642).Duplex) +const inherits = __nccwpck_require__(44124) +const BufferList = __nccwpck_require__(23664) -PromiseArray.prototype.promise = function () { - return this._promise; -}; +function BufferListStream (callback) { + if (!(this instanceof BufferListStream)) { + return new BufferListStream(callback) + } -PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { - var values = tryConvertToPromise(this._values, this._promise); - if (values instanceof Promise) { - values = values._target(); - var bitField = values._bitField; - ; - this._values = values; + if (typeof callback === 'function') { + this._callback = callback - if (((bitField & 50397184) === 0)) { - this._promise._setAsyncGuaranteed(); - return values._then( - init, - this._reject, - undefined, - this, - resolveValueIfEmpty - ); - } else if (((bitField & 33554432) !== 0)) { - values = values._value(); - } else if (((bitField & 16777216) !== 0)) { - return this._reject(values._reason()); - } else { - return this._cancel(); - } - } - values = util.asArray(values); - if (values === null) { - var err = apiRejection( - "expecting an array or an iterable object but got " + util.classString(values)).reason(); - this._promise._rejectCallback(err, false); - return; - } + const piper = function piper (err) { + if (this._callback) { + this._callback(err) + this._callback = null + } + }.bind(this) - if (values.length === 0) { - if (resolveValueIfEmpty === -5) { - this._resolveEmptyArray(); - } - else { - this._resolve(toResolutionValue(resolveValueIfEmpty)); - } - return; - } - this._iterate(values); -}; + this.on('pipe', function onPipe (src) { + src.on('error', piper) + }) + this.on('unpipe', function onUnpipe (src) { + src.removeListener('error', piper) + }) -PromiseArray.prototype._iterate = function(values) { - var len = this.getActualLength(values.length); - this._length = len; - this._values = this.shouldCopyValues() ? new Array(len) : this._values; - var result = this._promise; - var isResolved = false; - var bitField = null; - for (var i = 0; i < len; ++i) { - var maybePromise = tryConvertToPromise(values[i], result); + callback = null + } - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - bitField = maybePromise._bitField; - } else { - bitField = null; - } + BufferList._init.call(this, callback) + DuplexStream.call(this) +} - if (isResolved) { - if (bitField !== null) { - maybePromise.suppressUnhandledRejections(); - } - } else if (bitField !== null) { - if (((bitField & 50397184) === 0)) { - maybePromise._proxy(this, i); - this._values[i] = maybePromise; - } else if (((bitField & 33554432) !== 0)) { - isResolved = this._promiseFulfilled(maybePromise._value(), i); - } else if (((bitField & 16777216) !== 0)) { - isResolved = this._promiseRejected(maybePromise._reason(), i); - } else { - isResolved = this._promiseCancelled(i); - } - } else { - isResolved = this._promiseFulfilled(maybePromise, i); - } - } - if (!isResolved) result._setAsyncGuaranteed(); -}; +inherits(BufferListStream, DuplexStream) +Object.assign(BufferListStream.prototype, BufferList.prototype) -PromiseArray.prototype._isResolved = function () { - return this._values === null; -}; +BufferListStream.prototype._new = function _new (callback) { + return new BufferListStream(callback) +} -PromiseArray.prototype._resolve = function (value) { - this._values = null; - this._promise._fulfill(value); -}; +BufferListStream.prototype._write = function _write (buf, encoding, callback) { + this._appendBuffer(buf) -PromiseArray.prototype._cancel = function() { - if (this._isResolved() || !this._promise._isCancellable()) return; - this._values = null; - this._promise._cancel(); -}; + if (typeof callback === 'function') { + callback() + } +} -PromiseArray.prototype._reject = function (reason) { - this._values = null; - this._promise._rejectCallback(reason, false); -}; +BufferListStream.prototype._read = function _read (size) { + if (!this.length) { + return this.push(null) + } -PromiseArray.prototype._promiseFulfilled = function (value, index) { - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - return true; - } - return false; -}; + size = Math.min(size, this.length) + this.push(this.slice(0, size)) + this.consume(size) +} -PromiseArray.prototype._promiseCancelled = function() { - this._cancel(); - return true; -}; +BufferListStream.prototype.end = function end (chunk) { + DuplexStream.prototype.end.call(this, chunk) -PromiseArray.prototype._promiseRejected = function (reason) { - this._totalResolved++; - this._reject(reason); - return true; -}; + if (this._callback) { + this._callback(null, this.slice()) + this._callback = null + } +} -PromiseArray.prototype._resultCancelled = function() { - if (this._isResolved()) return; - var values = this._values; - this._cancel(); - if (values instanceof Promise) { - values.cancel(); - } else { - for (var i = 0; i < values.length; ++i) { - if (values[i] instanceof Promise) { - values[i].cancel(); - } - } - } -}; +BufferListStream.prototype._destroy = function _destroy (err, cb) { + this._bufs.length = 0 + this.length = 0 + cb(err) +} -PromiseArray.prototype.shouldCopyValues = function () { - return true; -}; +BufferListStream.prototype._isBufferList = function _isBufferList (b) { + return b instanceof BufferListStream || b instanceof BufferList || BufferListStream.isBufferList(b) +} -PromiseArray.prototype.getActualLength = function (len) { - return len; -}; +BufferListStream.isBufferList = BufferList.isBufferList -return PromiseArray; -}; +module.exports = BufferListStream +module.exports.BufferListStream = BufferListStream +module.exports.BufferList = BufferList /***/ }), -/***/ 16290: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 11174: +/***/ (function(module) { -"use strict"; +/** + * This file contains the Bottleneck library (MIT), compiled to ES2017, and without Clustering support. + * https://github.com/SGrondin/bottleneck + */ +(function (global, factory) { + true ? module.exports = factory() : + 0; +}(this, (function () { 'use strict'; -module.exports = function(Promise, INTERNAL) { -var THIS = {}; -var util = __nccwpck_require__(37180); -var nodebackForPromise = __nccwpck_require__(80683); -var withAppended = util.withAppended; -var maybeWrapAsError = util.maybeWrapAsError; -var canEvaluate = util.canEvaluate; -var TypeError = (__nccwpck_require__(44581).TypeError); -var defaultSuffix = "Async"; -var defaultPromisified = {__isPromisified__: true}; -var noCopyProps = [ - "arity", "length", - "name", - "arguments", - "caller", - "callee", - "prototype", - "__isPromisified__" -]; -var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$"); + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; -var defaultFilter = function(name) { - return util.isIdentifier(name) && - name.charAt(0) !== "_" && - name !== "constructor"; -}; + function getCjsExportFromNamespace (n) { + return n && n['default'] || n; + } -function propsFilter(key) { - return !noCopyPropsPattern.test(key); -} + var load = function(received, defaults, onto = {}) { + var k, ref, v; + for (k in defaults) { + v = defaults[k]; + onto[k] = (ref = received[k]) != null ? ref : v; + } + return onto; + }; -function isPromisified(fn) { - try { - return fn.__isPromisified__ === true; - } - catch (e) { - return false; - } -} - -function hasPromisified(obj, key, suffix) { - var val = util.getDataPropertyOrDefault(obj, key + suffix, - defaultPromisified); - return val ? isPromisified(val) : false; -} -function checkValid(ret, suffix, suffixRegexp) { - for (var i = 0; i < ret.length; i += 2) { - var key = ret[i]; - if (suffixRegexp.test(key)) { - var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); - for (var j = 0; j < ret.length; j += 2) { - if (ret[j] === keyWithoutAsyncSuffix) { - throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a" - .replace("%s", suffix)); - } - } - } - } -} - -function promisifiableMethods(obj, suffix, suffixRegexp, filter) { - var keys = util.inheritedDataKeys(obj); - var ret = []; - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - var value = obj[key]; - var passesDefaultFilter = filter === defaultFilter - ? true : defaultFilter(key, value, obj); - if (typeof value === "function" && - !isPromisified(value) && - !hasPromisified(obj, key, suffix) && - filter(key, value, obj, passesDefaultFilter)) { - ret.push(key, value); - } - } - checkValid(ret, suffix, suffixRegexp); - return ret; -} - -var escapeIdentRegex = function(str) { - return str.replace(/([$])/, "\\$"); -}; - -var makeNodePromisifiedEval; -if (true) { -var switchCaseArgumentOrder = function(likelyArgumentCount) { - var ret = [likelyArgumentCount]; - var min = Math.max(0, likelyArgumentCount - 1 - 3); - for(var i = likelyArgumentCount - 1; i >= min; --i) { - ret.push(i); - } - for(var i = likelyArgumentCount + 1; i <= 3; ++i) { - ret.push(i); - } - return ret; -}; - -var argumentSequence = function(argumentCount) { - return util.filledRange(argumentCount, "_arg", ""); -}; - -var parameterDeclaration = function(parameterCount) { - return util.filledRange( - Math.max(parameterCount, 3), "_arg", ""); -}; - -var parameterCount = function(fn) { - if (typeof fn.length === "number") { - return Math.max(Math.min(fn.length, 1023 + 1), 0); - } - return 0; -}; - -makeNodePromisifiedEval = -function(callback, receiver, originalName, fn, _, multiArgs) { - var newParameterCount = Math.max(0, parameterCount(fn) - 1); - var argumentOrder = switchCaseArgumentOrder(newParameterCount); - var shouldProxyThis = typeof callback === "string" || receiver === THIS; - - function generateCallForArgumentCount(count) { - var args = argumentSequence(count).join(", "); - var comma = count > 0 ? ", " : ""; - var ret; - if (shouldProxyThis) { - ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; - } else { - ret = receiver === undefined - ? "ret = callback({{args}}, nodeback); break;\n" - : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; - } - return ret.replace("{{args}}", args).replace(", ", comma); - } - - function generateArgumentSwitchCase() { - var ret = ""; - for (var i = 0; i < argumentOrder.length; ++i) { - ret += "case " + argumentOrder[i] +":" + - generateCallForArgumentCount(argumentOrder[i]); - } - - ret += " \n\ - default: \n\ - var args = new Array(len + 1); \n\ - var i = 0; \n\ - for (var i = 0; i < len; ++i) { \n\ - args[i] = arguments[i]; \n\ - } \n\ - args[i] = nodeback; \n\ - [CodeForCall] \n\ - break; \n\ - ".replace("[CodeForCall]", (shouldProxyThis - ? "ret = callback.apply(this, args);\n" - : "ret = callback.apply(receiver, args);\n")); - return ret; - } - - var getFunctionCode = typeof callback === "string" - ? ("this != null ? this['"+callback+"'] : fn") - : "fn"; - var body = "'use strict'; \n\ - var ret = function (Parameters) { \n\ - 'use strict'; \n\ - var len = arguments.length; \n\ - var promise = new Promise(INTERNAL); \n\ - promise._captureStackTrace(); \n\ - var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\ - var ret; \n\ - var callback = tryCatch([GetFunctionCode]); \n\ - switch(len) { \n\ - [CodeForSwitchCase] \n\ - } \n\ - if (ret === errorObj) { \n\ - promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ - } \n\ - if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\ - return promise; \n\ - }; \n\ - notEnumerableProp(ret, '__isPromisified__', true); \n\ - return ret; \n\ - ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) - .replace("[GetFunctionCode]", getFunctionCode); - body = body.replace("Parameters", parameterDeclaration(newParameterCount)); - return new Function("Promise", - "fn", - "receiver", - "withAppended", - "maybeWrapAsError", - "nodebackForPromise", - "tryCatch", - "errorObj", - "notEnumerableProp", - "INTERNAL", - body)( - Promise, - fn, - receiver, - withAppended, - maybeWrapAsError, - nodebackForPromise, - util.tryCatch, - util.errorObj, - util.notEnumerableProp, - INTERNAL); -}; -} - -function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) { - var defaultThis = (function() {return this;})(); - var method = callback; - if (typeof method === "string") { - callback = fn; - } - function promisified() { - var _receiver = receiver; - if (receiver === THIS) _receiver = this; - var promise = new Promise(INTERNAL); - promise._captureStackTrace(); - var cb = typeof method === "string" && this !== defaultThis - ? this[method] : callback; - var fn = nodebackForPromise(promise, multiArgs); - try { - cb.apply(_receiver, withAppended(arguments, fn)); - } catch(e) { - promise._rejectCallback(maybeWrapAsError(e), true, true); - } - if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); - return promise; - } - util.notEnumerableProp(promisified, "__isPromisified__", true); - return promisified; -} + var overwrite = function(received, defaults, onto = {}) { + var k, v; + for (k in received) { + v = received[k]; + if (defaults[k] !== void 0) { + onto[k] = v; + } + } + return onto; + }; -var makeNodePromisified = canEvaluate - ? makeNodePromisifiedEval - : makeNodePromisifiedClosure; + var parser = { + load: load, + overwrite: overwrite + }; -function promisifyAll(obj, suffix, filter, promisifier, multiArgs) { - var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); - var methods = - promisifiableMethods(obj, suffix, suffixRegexp, filter); + var DLList; - for (var i = 0, len = methods.length; i < len; i+= 2) { - var key = methods[i]; - var fn = methods[i+1]; - var promisifiedKey = key + suffix; - if (promisifier === makeNodePromisified) { - obj[promisifiedKey] = - makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); - } else { - var promisified = promisifier(fn, function() { - return makeNodePromisified(key, THIS, key, - fn, suffix, multiArgs); - }); - util.notEnumerableProp(promisified, "__isPromisified__", true); - obj[promisifiedKey] = promisified; - } - } - util.toFastProperties(obj); - return obj; -} + DLList = class DLList { + constructor(incr, decr) { + this.incr = incr; + this.decr = decr; + this._first = null; + this._last = null; + this.length = 0; + } -function promisify(callback, receiver, multiArgs) { - return makeNodePromisified(callback, receiver, undefined, - callback, null, multiArgs); -} + push(value) { + var node; + this.length++; + if (typeof this.incr === "function") { + this.incr(); + } + node = { + value, + prev: this._last, + next: null + }; + if (this._last != null) { + this._last.next = node; + this._last = node; + } else { + this._first = this._last = node; + } + return void 0; + } -Promise.promisify = function (fn, options) { - if (typeof fn !== "function") { - throw new TypeError("expecting a function but got " + util.classString(fn)); - } - if (isPromisified(fn)) { - return fn; - } - options = Object(options); - var receiver = options.context === undefined ? THIS : options.context; - var multiArgs = !!options.multiArgs; - var ret = promisify(fn, receiver, multiArgs); - util.copyDescriptors(fn, ret, propsFilter); - return ret; -}; + shift() { + var value; + if (this._first == null) { + return; + } else { + this.length--; + if (typeof this.decr === "function") { + this.decr(); + } + } + value = this._first.value; + if ((this._first = this._first.next) != null) { + this._first.prev = null; + } else { + this._last = null; + } + return value; + } -Promise.promisifyAll = function (target, options) { - if (typeof target !== "function" && typeof target !== "object") { - throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - options = Object(options); - var multiArgs = !!options.multiArgs; - var suffix = options.suffix; - if (typeof suffix !== "string") suffix = defaultSuffix; - var filter = options.filter; - if (typeof filter !== "function") filter = defaultFilter; - var promisifier = options.promisifier; - if (typeof promisifier !== "function") promisifier = makeNodePromisified; + first() { + if (this._first != null) { + return this._first.value; + } + } - if (!util.isIdentifier(suffix)) { - throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } + getArray() { + var node, ref, results; + node = this._first; + results = []; + while (node != null) { + results.push((ref = node, node = node.next, ref.value)); + } + return results; + } - var keys = util.inheritedDataKeys(target); - for (var i = 0; i < keys.length; ++i) { - var value = target[keys[i]]; - if (keys[i] !== "constructor" && - util.isClass(value)) { - promisifyAll(value.prototype, suffix, filter, promisifier, - multiArgs); - promisifyAll(value, suffix, filter, promisifier, multiArgs); - } - } + forEachShift(cb) { + var node; + node = this.shift(); + while (node != null) { + (cb(node), node = this.shift()); + } + return void 0; + } - return promisifyAll(target, suffix, filter, promisifier, multiArgs); -}; -}; + debug() { + var node, ref, ref1, ref2, results; + node = this._first; + results = []; + while (node != null) { + results.push((ref = node, node = node.next, { + value: ref.value, + prev: (ref1 = ref.prev) != null ? ref1.value : void 0, + next: (ref2 = ref.next) != null ? ref2.value : void 0 + })); + } + return results; + } + }; + var DLList_1 = DLList; -/***/ }), + var Events; -/***/ 6237: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + Events = class Events { + constructor(instance) { + this.instance = instance; + this._events = {}; + if ((this.instance.on != null) || (this.instance.once != null) || (this.instance.removeAllListeners != null)) { + throw new Error("An Emitter already exists for this object"); + } + this.instance.on = (name, cb) => { + return this._addListener(name, "many", cb); + }; + this.instance.once = (name, cb) => { + return this._addListener(name, "once", cb); + }; + this.instance.removeAllListeners = (name = null) => { + if (name != null) { + return delete this._events[name]; + } else { + return this._events = {}; + } + }; + } -"use strict"; + _addListener(name, status, cb) { + var base; + if ((base = this._events)[name] == null) { + base[name] = []; + } + this._events[name].push({cb, status}); + return this.instance; + } -module.exports = function( - Promise, PromiseArray, tryConvertToPromise, apiRejection) { -var util = __nccwpck_require__(37180); -var isObject = util.isObject; -var es5 = __nccwpck_require__(61713); -var Es6Map; -if (typeof Map === "function") Es6Map = Map; + listenerCount(name) { + if (this._events[name] != null) { + return this._events[name].length; + } else { + return 0; + } + } -var mapToEntries = (function() { - var index = 0; - var size = 0; + async trigger(name, ...args) { + var e, promises; + try { + if (name !== "debug") { + this.trigger("debug", `Event triggered: ${name}`, args); + } + if (this._events[name] == null) { + return; + } + this._events[name] = this._events[name].filter(function(listener) { + return listener.status !== "none"; + }); + promises = this._events[name].map(async(listener) => { + var e, returned; + if (listener.status === "none") { + return; + } + if (listener.status === "once") { + listener.status = "none"; + } + try { + returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0; + if (typeof (returned != null ? returned.then : void 0) === "function") { + return (await returned); + } else { + return returned; + } + } catch (error) { + e = error; + { + this.trigger("error", e); + } + return null; + } + }); + return ((await Promise.all(promises))).find(function(x) { + return x != null; + }); + } catch (error) { + e = error; + { + this.trigger("error", e); + } + return null; + } + } - function extractEntry(value, key) { - this[index] = value; - this[index + size] = key; - index++; - } + }; - return function mapToEntries(map) { - size = map.size; - index = 0; - var ret = new Array(map.size * 2); - map.forEach(extractEntry, ret); - return ret; - }; -})(); + var Events_1 = Events; -var entriesToMap = function(entries) { - var ret = new Es6Map(); - var length = entries.length / 2 | 0; - for (var i = 0; i < length; ++i) { - var key = entries[length + i]; - var value = entries[i]; - ret.set(key, value); - } - return ret; -}; + var DLList$1, Events$1, Queues; -function PropertiesPromiseArray(obj) { - var isMap = false; - var entries; - if (Es6Map !== undefined && obj instanceof Es6Map) { - entries = mapToEntries(obj); - isMap = true; - } else { - var keys = es5.keys(obj); - var len = keys.length; - entries = new Array(len * 2); - for (var i = 0; i < len; ++i) { - var key = keys[i]; - entries[i] = obj[key]; - entries[i + len] = key; - } - } - this.constructor$(entries); - this._isMap = isMap; - this._init$(undefined, -3); -} -util.inherits(PropertiesPromiseArray, PromiseArray); - -PropertiesPromiseArray.prototype._init = function () {}; - -PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - var val; - if (this._isMap) { - val = entriesToMap(this._values); - } else { - val = {}; - var keyOffset = this.length(); - for (var i = 0, len = this.length(); i < len; ++i) { - val[this._values[i + keyOffset]] = this._values[i]; - } - } - this._resolve(val); - return true; - } - return false; -}; + DLList$1 = DLList_1; -PropertiesPromiseArray.prototype.shouldCopyValues = function () { - return false; -}; + Events$1 = Events_1; -PropertiesPromiseArray.prototype.getActualLength = function (len) { - return len >> 1; -}; + Queues = class Queues { + constructor(num_priorities) { + var i; + this.Events = new Events$1(this); + this._length = 0; + this._lists = (function() { + var j, ref, results; + results = []; + for (i = j = 1, ref = num_priorities; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) { + results.push(new DLList$1((() => { + return this.incr(); + }), (() => { + return this.decr(); + }))); + } + return results; + }).call(this); + } -function props(promises) { - var ret; - var castValue = tryConvertToPromise(promises); + incr() { + if (this._length++ === 0) { + return this.Events.trigger("leftzero"); + } + } - if (!isObject(castValue)) { - return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } else if (castValue instanceof Promise) { - ret = castValue._then( - Promise.props, undefined, undefined, undefined, undefined); - } else { - ret = new PropertiesPromiseArray(castValue).promise(); - } + decr() { + if (--this._length === 0) { + return this.Events.trigger("zero"); + } + } - if (castValue instanceof Promise) { - ret._propagateFrom(castValue, 2); - } - return ret; -} + push(job) { + return this._lists[job.options.priority].push(job); + } -Promise.prototype.props = function () { - return props(this); -}; + queued(priority) { + if (priority != null) { + return this._lists[priority].length; + } else { + return this._length; + } + } -Promise.props = function (promises) { - return props(promises); -}; -}; + shiftAll(fn) { + return this._lists.forEach(function(list) { + return list.forEachShift(fn); + }); + } + getFirst(arr = this._lists) { + var j, len, list; + for (j = 0, len = arr.length; j < len; j++) { + list = arr[j]; + if (list.length > 0) { + return list; + } + } + return []; + } -/***/ }), + shiftLastFrom(priority) { + return this.getFirst(this._lists.slice(priority).reverse()).shift(); + } -/***/ 36872: -/***/ ((module) => { + }; -"use strict"; + var Queues_1 = Queues; -function arrayMove(src, srcIndex, dst, dstIndex, len) { - for (var j = 0; j < len; ++j) { - dst[j + dstIndex] = src[j + srcIndex]; - src[j + srcIndex] = void 0; - } -} + var BottleneckError; -function Queue(capacity) { - this._capacity = capacity; - this._length = 0; - this._front = 0; -} + BottleneckError = class BottleneckError extends Error {}; -Queue.prototype._willBeOverCapacity = function (size) { - return this._capacity < size; -}; + var BottleneckError_1 = BottleneckError; -Queue.prototype._pushOne = function (arg) { - var length = this.length(); - this._checkCapacity(length + 1); - var i = (this._front + length) & (this._capacity - 1); - this[i] = arg; - this._length = length + 1; -}; + var BottleneckError$1, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser$1; -Queue.prototype.push = function (fn, receiver, arg) { - var length = this.length() + 3; - if (this._willBeOverCapacity(length)) { - this._pushOne(fn); - this._pushOne(receiver); - this._pushOne(arg); - return; - } - var j = this._front + length - 3; - this._checkCapacity(length); - var wrapMask = this._capacity - 1; - this[(j + 0) & wrapMask] = fn; - this[(j + 1) & wrapMask] = receiver; - this[(j + 2) & wrapMask] = arg; - this._length = length; -}; + NUM_PRIORITIES = 10; -Queue.prototype.shift = function () { - var front = this._front, - ret = this[front]; + DEFAULT_PRIORITY = 5; - this[front] = undefined; - this._front = (front + 1) & (this._capacity - 1); - this._length--; - return ret; -}; + parser$1 = parser; -Queue.prototype.length = function () { - return this._length; -}; + BottleneckError$1 = BottleneckError_1; -Queue.prototype._checkCapacity = function (size) { - if (this._capacity < size) { - this._resizeTo(this._capacity << 1); - } -}; + Job = class Job { + constructor(task, args, options, jobDefaults, rejectOnDrop, Events, _states, Promise) { + this.task = task; + this.args = args; + this.rejectOnDrop = rejectOnDrop; + this.Events = Events; + this._states = _states; + this.Promise = Promise; + this.options = parser$1.load(options, jobDefaults); + this.options.priority = this._sanitizePriority(this.options.priority); + if (this.options.id === jobDefaults.id) { + this.options.id = `${this.options.id}-${this._randomIndex()}`; + } + this.promise = new this.Promise((_resolve, _reject) => { + this._resolve = _resolve; + this._reject = _reject; + }); + this.retryCount = 0; + } -Queue.prototype._resizeTo = function (capacity) { - var oldCapacity = this._capacity; - this._capacity = capacity; - var front = this._front; - var length = this._length; - var moveItemsCount = (front + length) & (oldCapacity - 1); - arrayMove(this, 0, this, oldCapacity, moveItemsCount); -}; + _sanitizePriority(priority) { + var sProperty; + sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority; + if (sProperty < 0) { + return 0; + } else if (sProperty > NUM_PRIORITIES - 1) { + return NUM_PRIORITIES - 1; + } else { + return sProperty; + } + } -module.exports = Queue; + _randomIndex() { + return Math.random().toString(36).slice(2); + } + doDrop({error, message = "This job has been dropped by Bottleneck"} = {}) { + if (this._states.remove(this.options.id)) { + if (this.rejectOnDrop) { + this._reject(error != null ? error : new BottleneckError$1(message)); + } + this.Events.trigger("dropped", {args: this.args, options: this.options, task: this.task, promise: this.promise}); + return true; + } else { + return false; + } + } -/***/ }), + _assertStatus(expected) { + var status; + status = this._states.jobStatus(this.options.id); + if (!(status === expected || (expected === "DONE" && status === null))) { + throw new BottleneckError$1(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`); + } + } -/***/ 9493: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + doReceive() { + this._states.start(this.options.id); + return this.Events.trigger("received", {args: this.args, options: this.options}); + } -"use strict"; + doQueue(reachedHWM, blocked) { + this._assertStatus("RECEIVED"); + this._states.next(this.options.id); + return this.Events.trigger("queued", {args: this.args, options: this.options, reachedHWM, blocked}); + } -module.exports = function( - Promise, INTERNAL, tryConvertToPromise, apiRejection) { -var util = __nccwpck_require__(37180); + doRun() { + if (this.retryCount === 0) { + this._assertStatus("QUEUED"); + this._states.next(this.options.id); + } else { + this._assertStatus("EXECUTING"); + } + return this.Events.trigger("scheduled", {args: this.args, options: this.options}); + } -var raceLater = function (promise) { - return promise.then(function(array) { - return race(array, promise); - }); -}; + async doExecute(chained, clearGlobalState, run, free) { + var error, eventInfo, passed; + if (this.retryCount === 0) { + this._assertStatus("RUNNING"); + this._states.next(this.options.id); + } else { + this._assertStatus("EXECUTING"); + } + eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount}; + this.Events.trigger("executing", eventInfo); + try { + passed = (await (chained != null ? chained.schedule(this.options, this.task, ...this.args) : this.task(...this.args))); + if (clearGlobalState()) { + this.doDone(eventInfo); + await free(this.options, eventInfo); + this._assertStatus("DONE"); + return this._resolve(passed); + } + } catch (error1) { + error = error1; + return this._onFailure(error, eventInfo, clearGlobalState, run, free); + } + } -function race(promises, parent) { - var maybePromise = tryConvertToPromise(promises); + doExpire(clearGlobalState, run, free) { + var error, eventInfo; + if (this._states.jobStatus(this.options.id === "RUNNING")) { + this._states.next(this.options.id); + } + this._assertStatus("EXECUTING"); + eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount}; + error = new BottleneckError$1(`This job timed out after ${this.options.expiration} ms.`); + return this._onFailure(error, eventInfo, clearGlobalState, run, free); + } - if (maybePromise instanceof Promise) { - return raceLater(maybePromise); - } else { - promises = util.asArray(promises); - if (promises === null) - return apiRejection("expecting an array or an iterable object but got " + util.classString(promises)); - } + async _onFailure(error, eventInfo, clearGlobalState, run, free) { + var retry, retryAfter; + if (clearGlobalState()) { + retry = (await this.Events.trigger("failed", error, eventInfo)); + if (retry != null) { + retryAfter = ~~retry; + this.Events.trigger("retry", `Retrying ${this.options.id} after ${retryAfter} ms`, eventInfo); + this.retryCount++; + return run(retryAfter); + } else { + this.doDone(eventInfo); + await free(this.options, eventInfo); + this._assertStatus("DONE"); + return this._reject(error); + } + } + } - var ret = new Promise(INTERNAL); - if (parent !== undefined) { - ret._propagateFrom(parent, 3); - } - var fulfill = ret._fulfill; - var reject = ret._reject; - for (var i = 0, len = promises.length; i < len; ++i) { - var val = promises[i]; + doDone(eventInfo) { + this._assertStatus("EXECUTING"); + this._states.next(this.options.id); + return this.Events.trigger("done", eventInfo); + } - if (val === undefined && !(i in promises)) { - continue; - } + }; - Promise.cast(val)._then(fulfill, reject, undefined, ret, null); - } - return ret; -} + var Job_1 = Job; -Promise.race = function (promises) { - return race(promises, undefined); -}; + var BottleneckError$2, LocalDatastore, parser$2; -Promise.prototype.race = function () { - return race(this, undefined); -}; + parser$2 = parser; -}; + BottleneckError$2 = BottleneckError_1; + LocalDatastore = class LocalDatastore { + constructor(instance, storeOptions, storeInstanceOptions) { + this.instance = instance; + this.storeOptions = storeOptions; + this.clientId = this.instance._randomIndex(); + parser$2.load(storeInstanceOptions, storeInstanceOptions, this); + this._nextRequest = this._lastReservoirRefresh = this._lastReservoirIncrease = Date.now(); + this._running = 0; + this._done = 0; + this._unblockTime = 0; + this.ready = this.Promise.resolve(); + this.clients = {}; + this._startHeartbeat(); + } -/***/ }), - -/***/ 44712: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = function(Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL, - debug) { -var getDomain = Promise._getDomain; -var util = __nccwpck_require__(37180); -var tryCatch = util.tryCatch; - -function ReductionPromiseArray(promises, fn, initialValue, _each) { - this.constructor$(promises); - var domain = getDomain(); - this._fn = domain === null ? fn : util.domainBind(domain, fn); - if (initialValue !== undefined) { - initialValue = Promise.resolve(initialValue); - initialValue._attachCancellationCallback(this); - } - this._initialValue = initialValue; - this._currentCancellable = null; - if(_each === INTERNAL) { - this._eachValues = Array(this._length); - } else if (_each === 0) { - this._eachValues = null; - } else { - this._eachValues = undefined; - } - this._promise._captureStackTrace(); - this._init$(undefined, -5); -} -util.inherits(ReductionPromiseArray, PromiseArray); - -ReductionPromiseArray.prototype._gotAccum = function(accum) { - if (this._eachValues !== undefined && - this._eachValues !== null && - accum !== INTERNAL) { - this._eachValues.push(accum); - } -}; - -ReductionPromiseArray.prototype._eachComplete = function(value) { - if (this._eachValues !== null) { - this._eachValues.push(value); - } - return this._eachValues; -}; - -ReductionPromiseArray.prototype._init = function() {}; - -ReductionPromiseArray.prototype._resolveEmptyArray = function() { - this._resolve(this._eachValues !== undefined ? this._eachValues - : this._initialValue); -}; - -ReductionPromiseArray.prototype.shouldCopyValues = function () { - return false; -}; - -ReductionPromiseArray.prototype._resolve = function(value) { - this._promise._resolveCallback(value); - this._values = null; -}; - -ReductionPromiseArray.prototype._resultCancelled = function(sender) { - if (sender === this._initialValue) return this._cancel(); - if (this._isResolved()) return; - this._resultCancelled$(); - if (this._currentCancellable instanceof Promise) { - this._currentCancellable.cancel(); - } - if (this._initialValue instanceof Promise) { - this._initialValue.cancel(); - } -}; + _startHeartbeat() { + var base; + if ((this.heartbeat == null) && (((this.storeOptions.reservoirRefreshInterval != null) && (this.storeOptions.reservoirRefreshAmount != null)) || ((this.storeOptions.reservoirIncreaseInterval != null) && (this.storeOptions.reservoirIncreaseAmount != null)))) { + return typeof (base = (this.heartbeat = setInterval(() => { + var amount, incr, maximum, now, reservoir; + now = Date.now(); + if ((this.storeOptions.reservoirRefreshInterval != null) && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { + this._lastReservoirRefresh = now; + this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; + this.instance._drainAll(this.computeCapacity()); + } + if ((this.storeOptions.reservoirIncreaseInterval != null) && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) { + ({ + reservoirIncreaseAmount: amount, + reservoirIncreaseMaximum: maximum, + reservoir + } = this.storeOptions); + this._lastReservoirIncrease = now; + incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount; + if (incr > 0) { + this.storeOptions.reservoir += incr; + return this.instance._drainAll(this.computeCapacity()); + } + } + }, this.heartbeatInterval))).unref === "function" ? base.unref() : void 0; + } else { + return clearInterval(this.heartbeat); + } + } -ReductionPromiseArray.prototype._iterate = function (values) { - this._values = values; - var value; - var i; - var length = values.length; - if (this._initialValue !== undefined) { - value = this._initialValue; - i = 0; - } else { - value = Promise.resolve(values[0]); - i = 1; - } + async __publish__(message) { + await this.yieldLoop(); + return this.instance.Events.trigger("message", message.toString()); + } - this._currentCancellable = value; + async __disconnect__(flush) { + await this.yieldLoop(); + clearInterval(this.heartbeat); + return this.Promise.resolve(); + } - if (!value.isRejected()) { - for (; i < length; ++i) { - var ctx = { - accum: null, - value: values[i], - index: i, - length: length, - array: this - }; - value = value._then(gotAccum, undefined, undefined, ctx, undefined); - } - } + yieldLoop(t = 0) { + return new this.Promise(function(resolve, reject) { + return setTimeout(resolve, t); + }); + } - if (this._eachValues !== undefined) { - value = value - ._then(this._eachComplete, undefined, undefined, this, undefined); - } - value._then(completed, completed, undefined, value, this); -}; + computePenalty() { + var ref; + return (ref = this.storeOptions.penalty) != null ? ref : (15 * this.storeOptions.minTime) || 5000; + } -Promise.prototype.reduce = function (fn, initialValue) { - return reduce(this, fn, initialValue, null); -}; + async __updateSettings__(options) { + await this.yieldLoop(); + parser$2.overwrite(options, options, this.storeOptions); + this._startHeartbeat(); + this.instance._drainAll(this.computeCapacity()); + return true; + } -Promise.reduce = function (promises, fn, initialValue, _each) { - return reduce(promises, fn, initialValue, _each); -}; + async __running__() { + await this.yieldLoop(); + return this._running; + } -function completed(valueOrReason, array) { - if (this.isFulfilled()) { - array._resolve(valueOrReason); - } else { - array._reject(valueOrReason); - } -} + async __queued__() { + await this.yieldLoop(); + return this.instance.queued(); + } -function reduce(promises, fn, initialValue, _each) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var array = new ReductionPromiseArray(promises, fn, initialValue, _each); - return array.promise(); -} + async __done__() { + await this.yieldLoop(); + return this._done; + } -function gotAccum(accum) { - this.accum = accum; - this.array._gotAccum(accum); - var value = tryConvertToPromise(this.value, this.array._promise); - if (value instanceof Promise) { - this.array._currentCancellable = value; - return value._then(gotValue, undefined, undefined, this, undefined); - } else { - return gotValue.call(this, value); - } -} + async __groupCheck__(time) { + await this.yieldLoop(); + return (this._nextRequest + this.timeout) < time; + } -function gotValue(value) { - var array = this.array; - var promise = array._promise; - var fn = tryCatch(array._fn); - promise._pushContext(); - var ret; - if (array._eachValues !== undefined) { - ret = fn.call(promise._boundValue(), value, this.index, this.length); - } else { - ret = fn.call(promise._boundValue(), - this.accum, value, this.index, this.length); - } - if (ret instanceof Promise) { - array._currentCancellable = ret; - } - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, - promiseCreated, - array._eachValues !== undefined ? "Promise.each" : "Promise.reduce", - promise - ); - return ret; -} -}; + computeCapacity() { + var maxConcurrent, reservoir; + ({maxConcurrent, reservoir} = this.storeOptions); + if ((maxConcurrent != null) && (reservoir != null)) { + return Math.min(maxConcurrent - this._running, reservoir); + } else if (maxConcurrent != null) { + return maxConcurrent - this._running; + } else if (reservoir != null) { + return reservoir; + } else { + return null; + } + } + conditionsCheck(weight) { + var capacity; + capacity = this.computeCapacity(); + return (capacity == null) || weight <= capacity; + } -/***/ }), + async __incrementReservoir__(incr) { + var reservoir; + await this.yieldLoop(); + reservoir = this.storeOptions.reservoir += incr; + this.instance._drainAll(this.computeCapacity()); + return reservoir; + } -/***/ 73484: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + async __currentReservoir__() { + await this.yieldLoop(); + return this.storeOptions.reservoir; + } -"use strict"; + isBlocked(now) { + return this._unblockTime >= now; + } -var util = __nccwpck_require__(37180); -var schedule; -var noAsyncScheduler = function() { - throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); -}; -var NativePromise = util.getNativePromise(); -if (util.isNode && typeof MutationObserver === "undefined") { - var GlobalSetImmediate = global.setImmediate; - var ProcessNextTick = process.nextTick; - schedule = util.isRecentNode - ? function(fn) { GlobalSetImmediate.call(global, fn); } - : function(fn) { ProcessNextTick.call(process, fn); }; -} else if (typeof NativePromise === "function" && - typeof NativePromise.resolve === "function") { - var nativePromise = NativePromise.resolve(); - schedule = function(fn) { - nativePromise.then(fn); - }; -} else if ((typeof MutationObserver !== "undefined") && - !(typeof window !== "undefined" && - window.navigator && - (window.navigator.standalone || window.cordova))) { - schedule = (function() { - var div = document.createElement("div"); - var opts = {attributes: true}; - var toggleScheduled = false; - var div2 = document.createElement("div"); - var o2 = new MutationObserver(function() { - div.classList.toggle("foo"); - toggleScheduled = false; - }); - o2.observe(div2, opts); + check(weight, now) { + return this.conditionsCheck(weight) && (this._nextRequest - now) <= 0; + } - var scheduleToggle = function() { - if (toggleScheduled) return; - toggleScheduled = true; - div2.classList.toggle("foo"); - }; + async __check__(weight) { + var now; + await this.yieldLoop(); + now = Date.now(); + return this.check(weight, now); + } - return function schedule(fn) { - var o = new MutationObserver(function() { - o.disconnect(); - fn(); - }); - o.observe(div, opts); - scheduleToggle(); - }; - })(); -} else if (typeof setImmediate !== "undefined") { - schedule = function (fn) { - setImmediate(fn); - }; -} else if (typeof setTimeout !== "undefined") { - schedule = function (fn) { - setTimeout(fn, 0); - }; -} else { - schedule = noAsyncScheduler; -} -module.exports = schedule; + async __register__(index, weight, expiration) { + var now, wait; + await this.yieldLoop(); + now = Date.now(); + if (this.conditionsCheck(weight)) { + this._running += weight; + if (this.storeOptions.reservoir != null) { + this.storeOptions.reservoir -= weight; + } + wait = Math.max(this._nextRequest - now, 0); + this._nextRequest = now + wait + this.storeOptions.minTime; + return { + success: true, + wait, + reservoir: this.storeOptions.reservoir + }; + } else { + return { + success: false + }; + } + } + strategyIsBlock() { + return this.storeOptions.strategy === 3; + } -/***/ }), + async __submit__(queueLength, weight) { + var blocked, now, reachedHWM; + await this.yieldLoop(); + if ((this.storeOptions.maxConcurrent != null) && weight > this.storeOptions.maxConcurrent) { + throw new BottleneckError$2(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${this.storeOptions.maxConcurrent}`); + } + now = Date.now(); + reachedHWM = (this.storeOptions.highWater != null) && queueLength === this.storeOptions.highWater && !this.check(weight, now); + blocked = this.strategyIsBlock() && (reachedHWM || this.isBlocked(now)); + if (blocked) { + this._unblockTime = now + this.computePenalty(); + this._nextRequest = this._unblockTime + this.storeOptions.minTime; + this.instance._dropAllQueued(); + } + return { + reachedHWM, + blocked, + strategy: this.storeOptions.strategy + }; + } -/***/ 25625: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + async __free__(index, weight) { + await this.yieldLoop(); + this._running -= weight; + this._done += weight; + this.instance._drainAll(this.computeCapacity()); + return { + running: this._running + }; + } -"use strict"; + }; -module.exports = - function(Promise, PromiseArray, debug) { -var PromiseInspection = Promise.PromiseInspection; -var util = __nccwpck_require__(37180); + var LocalDatastore_1 = LocalDatastore; -function SettledPromiseArray(values) { - this.constructor$(values); -} -util.inherits(SettledPromiseArray, PromiseArray); + var BottleneckError$3, States; -SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { - this._values[index] = inspection; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - return true; - } - return false; -}; + BottleneckError$3 = BottleneckError_1; -SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { - var ret = new PromiseInspection(); - ret._bitField = 33554432; - ret._settledValueField = value; - return this._promiseResolved(index, ret); -}; -SettledPromiseArray.prototype._promiseRejected = function (reason, index) { - var ret = new PromiseInspection(); - ret._bitField = 16777216; - ret._settledValueField = reason; - return this._promiseResolved(index, ret); -}; + States = class States { + constructor(status1) { + this.status = status1; + this._jobs = {}; + this.counts = this.status.map(function() { + return 0; + }); + } -Promise.settle = function (promises) { - debug.deprecated(".settle()", ".reflect()"); - return new SettledPromiseArray(promises).promise(); -}; + next(id) { + var current, next; + current = this._jobs[id]; + next = current + 1; + if ((current != null) && next < this.status.length) { + this.counts[current]--; + this.counts[next]++; + return this._jobs[id]++; + } else if (current != null) { + this.counts[current]--; + return delete this._jobs[id]; + } + } -Promise.prototype.settle = function () { - return Promise.settle(this); -}; -}; + start(id) { + var initial; + initial = 0; + this._jobs[id] = initial; + return this.counts[initial]++; + } + remove(id) { + var current; + current = this._jobs[id]; + if (current != null) { + this.counts[current]--; + delete this._jobs[id]; + } + return current != null; + } -/***/ }), + jobStatus(id) { + var ref; + return (ref = this.status[this._jobs[id]]) != null ? ref : null; + } -/***/ 85041: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + statusJobs(status) { + var k, pos, ref, results, v; + if (status != null) { + pos = this.status.indexOf(status); + if (pos < 0) { + throw new BottleneckError$3(`status must be one of ${this.status.join(', ')}`); + } + ref = this._jobs; + results = []; + for (k in ref) { + v = ref[k]; + if (v === pos) { + results.push(k); + } + } + return results; + } else { + return Object.keys(this._jobs); + } + } -"use strict"; + statusCounts() { + return this.counts.reduce(((acc, v, i) => { + acc[this.status[i]] = v; + return acc; + }), {}); + } -module.exports = -function(Promise, PromiseArray, apiRejection) { -var util = __nccwpck_require__(37180); -var RangeError = (__nccwpck_require__(44581).RangeError); -var AggregateError = (__nccwpck_require__(44581).AggregateError); -var isArray = util.isArray; -var CANCELLATION = {}; + }; + var States_1 = States; -function SomePromiseArray(values) { - this.constructor$(values); - this._howMany = 0; - this._unwrap = false; - this._initialized = false; -} -util.inherits(SomePromiseArray, PromiseArray); + var DLList$2, Sync; -SomePromiseArray.prototype._init = function () { - if (!this._initialized) { - return; - } - if (this._howMany === 0) { - this._resolve([]); - return; - } - this._init$(undefined, -5); - var isArrayResolved = isArray(this._values); - if (!this._isResolved() && - isArrayResolved && - this._howMany > this._canPossiblyFulfill()) { - this._reject(this._getRangeError(this.length())); - } -}; + DLList$2 = DLList_1; -SomePromiseArray.prototype.init = function () { - this._initialized = true; - this._init(); -}; + Sync = class Sync { + constructor(name, Promise) { + this.schedule = this.schedule.bind(this); + this.name = name; + this.Promise = Promise; + this._running = 0; + this._queue = new DLList$2(); + } -SomePromiseArray.prototype.setUnwrap = function () { - this._unwrap = true; -}; + isEmpty() { + return this._queue.length === 0; + } -SomePromiseArray.prototype.howMany = function () { - return this._howMany; -}; + async _tryToRun() { + var args, cb, error, reject, resolve, returned, task; + if ((this._running < 1) && this._queue.length > 0) { + this._running++; + ({task, args, resolve, reject} = this._queue.shift()); + cb = (await (async function() { + try { + returned = (await task(...args)); + return function() { + return resolve(returned); + }; + } catch (error1) { + error = error1; + return function() { + return reject(error); + }; + } + })()); + this._running--; + this._tryToRun(); + return cb(); + } + } -SomePromiseArray.prototype.setHowMany = function (count) { - this._howMany = count; -}; + schedule(task, ...args) { + var promise, reject, resolve; + resolve = reject = null; + promise = new this.Promise(function(_resolve, _reject) { + resolve = _resolve; + return reject = _reject; + }); + this._queue.push({task, args, resolve, reject}); + this._tryToRun(); + return promise; + } -SomePromiseArray.prototype._promiseFulfilled = function (value) { - this._addFulfilled(value); - if (this._fulfilled() === this.howMany()) { - this._values.length = this.howMany(); - if (this.howMany() === 1 && this._unwrap) { - this._resolve(this._values[0]); - } else { - this._resolve(this._values); - } - return true; - } - return false; + }; -}; -SomePromiseArray.prototype._promiseRejected = function (reason) { - this._addRejected(reason); - return this._checkOutcome(); -}; + var Sync_1 = Sync; -SomePromiseArray.prototype._promiseCancelled = function () { - if (this._values instanceof Promise || this._values == null) { - return this._cancel(); - } - this._addRejected(CANCELLATION); - return this._checkOutcome(); -}; + var version = "2.19.5"; + var version$1 = { + version: version + }; -SomePromiseArray.prototype._checkOutcome = function() { - if (this.howMany() > this._canPossiblyFulfill()) { - var e = new AggregateError(); - for (var i = this.length(); i < this._values.length; ++i) { - if (this._values[i] !== CANCELLATION) { - e.push(this._values[i]); - } - } - if (e.length > 0) { - this._reject(e); - } else { - this._cancel(); - } - return true; - } - return false; -}; + var version$2 = /*#__PURE__*/Object.freeze({ + version: version, + default: version$1 + }); -SomePromiseArray.prototype._fulfilled = function () { - return this._totalResolved; -}; + var require$$2 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); -SomePromiseArray.prototype._rejected = function () { - return this._values.length - this.length(); -}; + var require$$3 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); -SomePromiseArray.prototype._addRejected = function (reason) { - this._values.push(reason); -}; + var require$$4 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); -SomePromiseArray.prototype._addFulfilled = function (value) { - this._values[this._totalResolved++] = value; -}; + var Events$2, Group, IORedisConnection$1, RedisConnection$1, Scripts$1, parser$3; -SomePromiseArray.prototype._canPossiblyFulfill = function () { - return this.length() - this._rejected(); -}; + parser$3 = parser; -SomePromiseArray.prototype._getRangeError = function (count) { - var message = "Input array must contain at least " + - this._howMany + " items but contains only " + count + " items"; - return new RangeError(message); -}; + Events$2 = Events_1; -SomePromiseArray.prototype._resolveEmptyArray = function () { - this._reject(this._getRangeError(0)); -}; + RedisConnection$1 = require$$2; -function some(promises, howMany) { - if ((howMany | 0) !== howMany || howMany < 0) { - return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var ret = new SomePromiseArray(promises); - var promise = ret.promise(); - ret.setHowMany(howMany); - ret.init(); - return promise; -} + IORedisConnection$1 = require$$3; -Promise.some = function (promises, howMany) { - return some(promises, howMany); -}; + Scripts$1 = require$$4; -Promise.prototype.some = function (howMany) { - return some(this, howMany); -}; + Group = (function() { + class Group { + constructor(limiterOptions = {}) { + this.deleteKey = this.deleteKey.bind(this); + this.limiterOptions = limiterOptions; + parser$3.load(this.limiterOptions, this.defaults, this); + this.Events = new Events$2(this); + this.instances = {}; + this.Bottleneck = Bottleneck_1; + this._startAutoCleanup(); + this.sharedConnection = this.connection != null; + if (this.connection == null) { + if (this.limiterOptions.datastore === "redis") { + this.connection = new RedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); + } else if (this.limiterOptions.datastore === "ioredis") { + this.connection = new IORedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); + } + } + } -Promise._SomePromiseArray = SomePromiseArray; -}; + key(key = "") { + var ref; + return (ref = this.instances[key]) != null ? ref : (() => { + var limiter; + limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, { + id: `${this.id}-${key}`, + timeout: this.timeout, + connection: this.connection + })); + this.Events.trigger("created", limiter, key); + return limiter; + })(); + } + async deleteKey(key = "") { + var deleted, instance; + instance = this.instances[key]; + if (this.connection) { + deleted = (await this.connection.__runCommand__(['del', ...Scripts$1.allKeys(`${this.id}-${key}`)])); + } + if (instance != null) { + delete this.instances[key]; + await instance.disconnect(); + } + return (instance != null) || deleted > 0; + } -/***/ }), + limiters() { + var k, ref, results, v; + ref = this.instances; + results = []; + for (k in ref) { + v = ref[k]; + results.push({ + key: k, + limiter: v + }); + } + return results; + } -/***/ 35506: -/***/ ((module) => { + keys() { + return Object.keys(this.instances); + } -"use strict"; + async clusterKeys() { + var cursor, end, found, i, k, keys, len, next, start; + if (this.connection == null) { + return this.Promise.resolve(this.keys()); + } + keys = []; + cursor = null; + start = `b_${this.id}-`.length; + end = "_settings".length; + while (cursor !== 0) { + [next, found] = (await this.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${this.id}-*_settings`, "count", 10000])); + cursor = ~~next; + for (i = 0, len = found.length; i < len; i++) { + k = found[i]; + keys.push(k.slice(start, -end)); + } + } + return keys; + } -module.exports = function(Promise) { -function PromiseInspection(promise) { - if (promise !== undefined) { - promise = promise._target(); - this._bitField = promise._bitField; - this._settledValueField = promise._isFateSealed() - ? promise._settledValue() : undefined; - } - else { - this._bitField = 0; - this._settledValueField = undefined; - } -} - -PromiseInspection.prototype._settledValue = function() { - return this._settledValueField; -}; + _startAutoCleanup() { + var base; + clearInterval(this.interval); + return typeof (base = (this.interval = setInterval(async() => { + var e, k, ref, results, time, v; + time = Date.now(); + ref = this.instances; + results = []; + for (k in ref) { + v = ref[k]; + try { + if ((await v._store.__groupCheck__(time))) { + results.push(this.deleteKey(k)); + } else { + results.push(void 0); + } + } catch (error) { + e = error; + results.push(v.Events.trigger("error", e)); + } + } + return results; + }, this.timeout / 2))).unref === "function" ? base.unref() : void 0; + } -var value = PromiseInspection.prototype.value = function () { - if (!this.isFulfilled()) { - throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - return this._settledValue(); -}; + updateSettings(options = {}) { + parser$3.overwrite(options, this.defaults, this); + parser$3.overwrite(options, options, this.limiterOptions); + if (options.timeout != null) { + return this._startAutoCleanup(); + } + } -var reason = PromiseInspection.prototype.error = -PromiseInspection.prototype.reason = function () { - if (!this.isRejected()) { - throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - return this._settledValue(); -}; + disconnect(flush = true) { + var ref; + if (!this.sharedConnection) { + return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; + } + } -var isFulfilled = PromiseInspection.prototype.isFulfilled = function() { - return (this._bitField & 33554432) !== 0; -}; + } + Group.prototype.defaults = { + timeout: 1000 * 60 * 5, + connection: null, + Promise: Promise, + id: "group-key" + }; -var isRejected = PromiseInspection.prototype.isRejected = function () { - return (this._bitField & 16777216) !== 0; -}; + return Group; -var isPending = PromiseInspection.prototype.isPending = function () { - return (this._bitField & 50397184) === 0; -}; + }).call(commonjsGlobal); -var isResolved = PromiseInspection.prototype.isResolved = function () { - return (this._bitField & 50331648) !== 0; -}; + var Group_1 = Group; -PromiseInspection.prototype.isCancelled = function() { - return (this._bitField & 8454144) !== 0; -}; + var Batcher, Events$3, parser$4; -Promise.prototype.__isCancelled = function() { - return (this._bitField & 65536) === 65536; -}; + parser$4 = parser; -Promise.prototype._isCancelled = function() { - return this._target().__isCancelled(); -}; + Events$3 = Events_1; -Promise.prototype.isCancelled = function() { - return (this._target()._bitField & 8454144) !== 0; -}; + Batcher = (function() { + class Batcher { + constructor(options = {}) { + this.options = options; + parser$4.load(this.options, this.defaults, this); + this.Events = new Events$3(this); + this._arr = []; + this._resetPromise(); + this._lastFlush = Date.now(); + } -Promise.prototype.isPending = function() { - return isPending.call(this._target()); -}; + _resetPromise() { + return this._promise = new this.Promise((res, rej) => { + return this._resolve = res; + }); + } -Promise.prototype.isRejected = function() { - return isRejected.call(this._target()); -}; + _flush() { + clearTimeout(this._timeout); + this._lastFlush = Date.now(); + this._resolve(); + this.Events.trigger("batch", this._arr); + this._arr = []; + return this._resetPromise(); + } -Promise.prototype.isFulfilled = function() { - return isFulfilled.call(this._target()); -}; + add(data) { + var ret; + this._arr.push(data); + ret = this._promise; + if (this._arr.length === this.maxSize) { + this._flush(); + } else if ((this.maxTime != null) && this._arr.length === 1) { + this._timeout = setTimeout(() => { + return this._flush(); + }, this.maxTime); + } + return ret; + } -Promise.prototype.isResolved = function() { - return isResolved.call(this._target()); -}; + } + Batcher.prototype.defaults = { + maxTime: null, + maxSize: null, + Promise: Promise + }; -Promise.prototype.value = function() { - return value.call(this._target()); -}; + return Batcher; -Promise.prototype.reason = function() { - var target = this._target(); - target._unsetRejectionIsUnhandled(); - return reason.call(target); -}; + }).call(commonjsGlobal); -Promise.prototype._value = function() { - return this._settledValue(); -}; + var Batcher_1 = Batcher; -Promise.prototype._reason = function() { - this._unsetRejectionIsUnhandled(); - return this._settledValue(); -}; + var require$$4$1 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); -Promise.PromiseInspection = PromiseInspection; -}; + var require$$8 = getCjsExportFromNamespace(version$2); + var Bottleneck, DEFAULT_PRIORITY$1, Events$4, Job$1, LocalDatastore$1, NUM_PRIORITIES$1, Queues$1, RedisDatastore$1, States$1, Sync$1, parser$5, + splice = [].splice; -/***/ }), + NUM_PRIORITIES$1 = 10; -/***/ 19400: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + DEFAULT_PRIORITY$1 = 5; -"use strict"; + parser$5 = parser; -module.exports = function(Promise, INTERNAL) { -var util = __nccwpck_require__(37180); -var errorObj = util.errorObj; -var isObject = util.isObject; - -function tryConvertToPromise(obj, context) { - if (isObject(obj)) { - if (obj instanceof Promise) return obj; - var then = getThen(obj); - if (then === errorObj) { - if (context) context._pushContext(); - var ret = Promise.reject(then.e); - if (context) context._popContext(); - return ret; - } else if (typeof then === "function") { - if (isAnyBluebirdPromise(obj)) { - var ret = new Promise(INTERNAL); - obj._then( - ret._fulfill, - ret._reject, - undefined, - ret, - null - ); - return ret; - } - return doThenable(obj, then, context); - } - } - return obj; -} + Queues$1 = Queues_1; -function doGetThen(obj) { - return obj.then; -} + Job$1 = Job_1; -function getThen(obj) { - try { - return doGetThen(obj); - } catch (e) { - errorObj.e = e; - return errorObj; - } -} + LocalDatastore$1 = LocalDatastore_1; -var hasProp = {}.hasOwnProperty; -function isAnyBluebirdPromise(obj) { - try { - return hasProp.call(obj, "_promise0"); - } catch (e) { - return false; - } -} + RedisDatastore$1 = require$$4$1; -function doThenable(x, then, context) { - var promise = new Promise(INTERNAL); - var ret = promise; - if (context) context._pushContext(); - promise._captureStackTrace(); - if (context) context._popContext(); - var synchronous = true; - var result = util.tryCatch(then).call(x, resolve, reject); - synchronous = false; + Events$4 = Events_1; - if (promise && result === errorObj) { - promise._rejectCallback(result.e, true, true); - promise = null; - } + States$1 = States_1; - function resolve(value) { - if (!promise) return; - promise._resolveCallback(value); - promise = null; - } + Sync$1 = Sync_1; - function reject(reason) { - if (!promise) return; - promise._rejectCallback(reason, synchronous, true); - promise = null; - } - return ret; -} + Bottleneck = (function() { + class Bottleneck { + constructor(options = {}, ...invalid) { + var storeInstanceOptions, storeOptions; + this._addToQueue = this._addToQueue.bind(this); + this._validateOptions(options, invalid); + parser$5.load(options, this.instanceDefaults, this); + this._queues = new Queues$1(NUM_PRIORITIES$1); + this._scheduled = {}; + this._states = new States$1(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : [])); + this._limiter = null; + this.Events = new Events$4(this); + this._submitLock = new Sync$1("submit", this.Promise); + this._registerLock = new Sync$1("register", this.Promise); + storeOptions = parser$5.load(options, this.storeDefaults, {}); + this._store = (function() { + if (this.datastore === "redis" || this.datastore === "ioredis" || (this.connection != null)) { + storeInstanceOptions = parser$5.load(options, this.redisStoreDefaults, {}); + return new RedisDatastore$1(this, storeOptions, storeInstanceOptions); + } else if (this.datastore === "local") { + storeInstanceOptions = parser$5.load(options, this.localStoreDefaults, {}); + return new LocalDatastore$1(this, storeOptions, storeInstanceOptions); + } else { + throw new Bottleneck.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`); + } + }).call(this); + this._queues.on("leftzero", () => { + var ref; + return (ref = this._store.heartbeat) != null ? typeof ref.ref === "function" ? ref.ref() : void 0 : void 0; + }); + this._queues.on("zero", () => { + var ref; + return (ref = this._store.heartbeat) != null ? typeof ref.unref === "function" ? ref.unref() : void 0 : void 0; + }); + } -return tryConvertToPromise; -}; + _validateOptions(options, invalid) { + if (!((options != null) && typeof options === "object" && invalid.length === 0)) { + throw new Bottleneck.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1."); + } + } + ready() { + return this._store.ready; + } -/***/ }), + clients() { + return this._store.clients; + } -/***/ 31433: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + channel() { + return `b_${this.id}`; + } -"use strict"; + channel_client() { + return `b_${this.id}_${this._store.clientId}`; + } -module.exports = function(Promise, INTERNAL, debug) { -var util = __nccwpck_require__(37180); -var TimeoutError = Promise.TimeoutError; + publish(message) { + return this._store.__publish__(message); + } -function HandleWrapper(handle) { - this.handle = handle; -} + disconnect(flush = true) { + return this._store.__disconnect__(flush); + } -HandleWrapper.prototype._resultCancelled = function() { - clearTimeout(this.handle); -}; + chain(_limiter) { + this._limiter = _limiter; + return this; + } -var afterValue = function(value) { return delay(+this).thenReturn(value); }; -var delay = Promise.delay = function (ms, value) { - var ret; - var handle; - if (value !== undefined) { - ret = Promise.resolve(value) - ._then(afterValue, null, null, ms, undefined); - if (debug.cancellation() && value instanceof Promise) { - ret._setOnCancel(value); - } - } else { - ret = new Promise(INTERNAL); - handle = setTimeout(function() { ret._fulfill(); }, +ms); - if (debug.cancellation()) { - ret._setOnCancel(new HandleWrapper(handle)); - } - ret._captureStackTrace(); - } - ret._setAsyncGuaranteed(); - return ret; -}; + queued(priority) { + return this._queues.queued(priority); + } -Promise.prototype.delay = function (ms) { - return delay(ms, this); -}; + clusterQueued() { + return this._store.__queued__(); + } -var afterTimeout = function (promise, message, parent) { - var err; - if (typeof message !== "string") { - if (message instanceof Error) { - err = message; - } else { - err = new TimeoutError("operation timed out"); - } - } else { - err = new TimeoutError(message); - } - util.markAsOriginatingFromRejection(err); - promise._attachExtraTrace(err); - promise._reject(err); + empty() { + return this.queued() === 0 && this._submitLock.isEmpty(); + } - if (parent != null) { - parent.cancel(); - } -}; + running() { + return this._store.__running__(); + } -function successClear(value) { - clearTimeout(this.handle); - return value; -} + done() { + return this._store.__done__(); + } -function failureClear(reason) { - clearTimeout(this.handle); - throw reason; -} + jobStatus(id) { + return this._states.jobStatus(id); + } -Promise.prototype.timeout = function (ms, message) { - ms = +ms; - var ret, parent; + jobs(status) { + return this._states.statusJobs(status); + } - var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() { - if (ret.isPending()) { - afterTimeout(ret, message, parent); - } - }, ms)); + counts() { + return this._states.statusCounts(); + } - if (debug.cancellation()) { - parent = this.then(); - ret = parent._then(successClear, failureClear, - undefined, handleWrapper, undefined); - ret._setOnCancel(handleWrapper); - } else { - ret = this._then(successClear, failureClear, - undefined, handleWrapper, undefined); - } + _randomIndex() { + return Math.random().toString(36).slice(2); + } - return ret; -}; + check(weight = 1) { + return this._store.__check__(weight); + } -}; + _clearGlobalState(index) { + if (this._scheduled[index] != null) { + clearTimeout(this._scheduled[index].expiration); + delete this._scheduled[index]; + return true; + } else { + return false; + } + } + async _free(index, job, options, eventInfo) { + var e, running; + try { + ({running} = (await this._store.__free__(index, options.weight))); + this.Events.trigger("debug", `Freed ${options.id}`, eventInfo); + if (running === 0 && this.empty()) { + return this.Events.trigger("idle"); + } + } catch (error1) { + e = error1; + return this.Events.trigger("error", e); + } + } -/***/ }), + _run(index, job, wait) { + var clearGlobalState, free, run; + job.doRun(); + clearGlobalState = this._clearGlobalState.bind(this, index); + run = this._run.bind(this, index, job); + free = this._free.bind(this, index, job); + return this._scheduled[index] = { + timeout: setTimeout(() => { + return job.doExecute(this._limiter, clearGlobalState, run, free); + }, wait), + expiration: job.options.expiration != null ? setTimeout(function() { + return job.doExpire(clearGlobalState, run, free); + }, wait + job.options.expiration) : void 0, + job: job + }; + } -/***/ 324: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + _drainOne(capacity) { + return this._registerLock.schedule(() => { + var args, index, next, options, queue; + if (this.queued() === 0) { + return this.Promise.resolve(null); + } + queue = this._queues.getFirst(); + ({options, args} = next = queue.first()); + if ((capacity != null) && options.weight > capacity) { + return this.Promise.resolve(null); + } + this.Events.trigger("debug", `Draining ${options.id}`, {args, options}); + index = this._randomIndex(); + return this._store.__register__(index, options.weight, options.expiration).then(({success, wait, reservoir}) => { + var empty; + this.Events.trigger("debug", `Drained ${options.id}`, {success, args, options}); + if (success) { + queue.shift(); + empty = this.empty(); + if (empty) { + this.Events.trigger("empty"); + } + if (reservoir === 0) { + this.Events.trigger("depleted", empty); + } + this._run(index, next, wait); + return this.Promise.resolve(options.weight); + } else { + return this.Promise.resolve(null); + } + }); + }); + } -"use strict"; + _drainAll(capacity, total = 0) { + return this._drainOne(capacity).then((drained) => { + var newCapacity; + if (drained != null) { + newCapacity = capacity != null ? capacity - drained : capacity; + return this._drainAll(newCapacity, total + drained); + } else { + return this.Promise.resolve(total); + } + }).catch((e) => { + return this.Events.trigger("error", e); + }); + } -module.exports = function (Promise, apiRejection, tryConvertToPromise, - createContext, INTERNAL, debug) { - var util = __nccwpck_require__(37180); - var TypeError = (__nccwpck_require__(44581).TypeError); - var inherits = (__nccwpck_require__(37180).inherits); - var errorObj = util.errorObj; - var tryCatch = util.tryCatch; - var NULL = {}; - - function thrower(e) { - setTimeout(function(){throw e;}, 0); - } - - function castPreservingDisposable(thenable) { - var maybePromise = tryConvertToPromise(thenable); - if (maybePromise !== thenable && - typeof thenable._isDisposable === "function" && - typeof thenable._getDisposer === "function" && - thenable._isDisposable()) { - maybePromise._setDisposable(thenable._getDisposer()); - } - return maybePromise; - } - function dispose(resources, inspection) { - var i = 0; - var len = resources.length; - var ret = new Promise(INTERNAL); - function iterator() { - if (i >= len) return ret._fulfill(); - var maybePromise = castPreservingDisposable(resources[i++]); - if (maybePromise instanceof Promise && - maybePromise._isDisposable()) { - try { - maybePromise = tryConvertToPromise( - maybePromise._getDisposer().tryDispose(inspection), - resources.promise); - } catch (e) { - return thrower(e); - } - if (maybePromise instanceof Promise) { - return maybePromise._then(iterator, thrower, - null, null, null); - } - } - iterator(); - } - iterator(); - return ret; - } + _dropAllQueued(message) { + return this._queues.shiftAll(function(job) { + return job.doDrop({message}); + }); + } - function Disposer(data, promise, context) { - this._data = data; - this._promise = promise; - this._context = context; - } + stop(options = {}) { + var done, waitForExecuting; + options = parser$5.load(options, this.stopDefaults); + waitForExecuting = (at) => { + var finished; + finished = () => { + var counts; + counts = this._states.counts; + return (counts[0] + counts[1] + counts[2] + counts[3]) === at; + }; + return new this.Promise((resolve, reject) => { + if (finished()) { + return resolve(); + } else { + return this.on("done", () => { + if (finished()) { + this.removeAllListeners("done"); + return resolve(); + } + }); + } + }); + }; + done = options.dropWaitingJobs ? (this._run = function(index, next) { + return next.doDrop({ + message: options.dropErrorMessage + }); + }, this._drainOne = () => { + return this.Promise.resolve(null); + }, this._registerLock.schedule(() => { + return this._submitLock.schedule(() => { + var k, ref, v; + ref = this._scheduled; + for (k in ref) { + v = ref[k]; + if (this.jobStatus(v.job.options.id) === "RUNNING") { + clearTimeout(v.timeout); + clearTimeout(v.expiration); + v.job.doDrop({ + message: options.dropErrorMessage + }); + } + } + this._dropAllQueued(options.dropErrorMessage); + return waitForExecuting(0); + }); + })) : this.schedule({ + priority: NUM_PRIORITIES$1 - 1, + weight: 0 + }, () => { + return waitForExecuting(1); + }); + this._receive = function(job) { + return job._reject(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)); + }; + this.stop = () => { + return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called")); + }; + return done; + } - Disposer.prototype.data = function () { - return this._data; - }; + async _addToQueue(job) { + var args, blocked, error, options, reachedHWM, shifted, strategy; + ({args, options} = job); + try { + ({reachedHWM, blocked, strategy} = (await this._store.__submit__(this.queued(), options.weight))); + } catch (error1) { + error = error1; + this.Events.trigger("debug", `Could not queue ${options.id}`, {args, options, error}); + job.doDrop({error}); + return false; + } + if (blocked) { + job.doDrop(); + return true; + } else if (reachedHWM) { + shifted = strategy === Bottleneck.prototype.strategy.LEAK ? this._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? this._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0; + if (shifted != null) { + shifted.doDrop(); + } + if ((shifted == null) || strategy === Bottleneck.prototype.strategy.OVERFLOW) { + if (shifted == null) { + job.doDrop(); + } + return reachedHWM; + } + } + job.doQueue(reachedHWM, blocked); + this._queues.push(job); + await this._drainAll(); + return reachedHWM; + } - Disposer.prototype.promise = function () { - return this._promise; - }; + _receive(job) { + if (this._states.jobStatus(job.options.id) != null) { + job._reject(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`)); + return false; + } else { + job.doReceive(); + return this._submitLock.schedule(this._addToQueue, job); + } + } - Disposer.prototype.resource = function () { - if (this.promise().isFulfilled()) { - return this.promise().value(); - } - return NULL; - }; + submit(...args) { + var cb, fn, job, options, ref, ref1, task; + if (typeof args[0] === "function") { + ref = args, [fn, ...args] = ref, [cb] = splice.call(args, -1); + options = parser$5.load({}, this.jobDefaults); + } else { + ref1 = args, [options, fn, ...args] = ref1, [cb] = splice.call(args, -1); + options = parser$5.load(options, this.jobDefaults); + } + task = (...args) => { + return new this.Promise(function(resolve, reject) { + return fn(...args, function(...args) { + return (args[0] != null ? reject : resolve)(args); + }); + }); + }; + job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); + job.promise.then(function(args) { + return typeof cb === "function" ? cb(...args) : void 0; + }).catch(function(args) { + if (Array.isArray(args)) { + return typeof cb === "function" ? cb(...args) : void 0; + } else { + return typeof cb === "function" ? cb(args) : void 0; + } + }); + return this._receive(job); + } - Disposer.prototype.tryDispose = function(inspection) { - var resource = this.resource(); - var context = this._context; - if (context !== undefined) context._pushContext(); - var ret = resource !== NULL - ? this.doDispose(resource, inspection) : null; - if (context !== undefined) context._popContext(); - this._promise._unsetDisposable(); - this._data = null; - return ret; - }; - - Disposer.isDisposer = function (d) { - return (d != null && - typeof d.resource === "function" && - typeof d.tryDispose === "function"); - }; + schedule(...args) { + var job, options, task; + if (typeof args[0] === "function") { + [task, ...args] = args; + options = {}; + } else { + [options, task, ...args] = args; + } + job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); + this._receive(job); + return job.promise; + } - function FunctionDisposer(fn, promise, context) { - this.constructor$(fn, promise, context); - } - inherits(FunctionDisposer, Disposer); + wrap(fn) { + var schedule, wrapped; + schedule = this.schedule.bind(this); + wrapped = function(...args) { + return schedule(fn.bind(this), ...args); + }; + wrapped.withOptions = function(options, ...args) { + return schedule(options, fn, ...args); + }; + return wrapped; + } - FunctionDisposer.prototype.doDispose = function (resource, inspection) { - var fn = this.data(); - return fn.call(resource, resource, inspection); - }; + async updateSettings(options = {}) { + await this._store.__updateSettings__(parser$5.overwrite(options, this.storeDefaults)); + parser$5.overwrite(options, this.instanceDefaults, this); + return this; + } - function maybeUnwrapDisposer(value) { - if (Disposer.isDisposer(value)) { - this.resources[this.index]._setDisposable(value); - return value.promise(); - } - return value; - } + currentReservoir() { + return this._store.__currentReservoir__(); + } - function ResourceList(length) { - this.length = length; - this.promise = null; - this[length-1] = null; - } + incrementReservoir(incr = 0) { + return this._store.__incrementReservoir__(incr); + } - ResourceList.prototype._resultCancelled = function() { - var len = this.length; - for (var i = 0; i < len; ++i) { - var item = this[i]; - if (item instanceof Promise) { - item.cancel(); - } - } - }; + } + Bottleneck.default = Bottleneck; - Promise.using = function () { - var len = arguments.length; - if (len < 2) return apiRejection( - "you must pass at least 2 arguments to Promise.using"); - var fn = arguments[len - 1]; - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var input; - var spreadArgs = true; - if (len === 2 && Array.isArray(arguments[0])) { - input = arguments[0]; - len = input.length; - spreadArgs = false; - } else { - input = arguments; - len--; - } - var resources = new ResourceList(len); - for (var i = 0; i < len; ++i) { - var resource = input[i]; - if (Disposer.isDisposer(resource)) { - var disposer = resource; - resource = resource.promise(); - resource._setDisposable(disposer); - } else { - var maybePromise = tryConvertToPromise(resource); - if (maybePromise instanceof Promise) { - resource = - maybePromise._then(maybeUnwrapDisposer, null, null, { - resources: resources, - index: i - }, undefined); - } - } - resources[i] = resource; - } + Bottleneck.Events = Events$4; - var reflectedResources = new Array(resources.length); - for (var i = 0; i < reflectedResources.length; ++i) { - reflectedResources[i] = Promise.resolve(resources[i]).reflect(); - } + Bottleneck.version = Bottleneck.prototype.version = require$$8.version; - var resultPromise = Promise.all(reflectedResources) - .then(function(inspections) { - for (var i = 0; i < inspections.length; ++i) { - var inspection = inspections[i]; - if (inspection.isRejected()) { - errorObj.e = inspection.error(); - return errorObj; - } else if (!inspection.isFulfilled()) { - resultPromise.cancel(); - return; - } - inspections[i] = inspection.value(); - } - promise._pushContext(); + Bottleneck.strategy = Bottleneck.prototype.strategy = { + LEAK: 1, + OVERFLOW: 2, + OVERFLOW_PRIORITY: 4, + BLOCK: 3 + }; - fn = tryCatch(fn); - var ret = spreadArgs - ? fn.apply(undefined, inspections) : fn(inspections); - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, promiseCreated, "Promise.using", promise); - return ret; - }); + Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = BottleneckError_1; - var promise = resultPromise.lastly(function() { - var inspection = new Promise.PromiseInspection(resultPromise); - return dispose(resources, inspection); - }); - resources.promise = promise; - promise._setOnCancel(resources); - return promise; - }; + Bottleneck.Group = Bottleneck.prototype.Group = Group_1; - Promise.prototype._setDisposable = function (disposer) { - this._bitField = this._bitField | 131072; - this._disposer = disposer; - }; + Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = require$$2; - Promise.prototype._isDisposable = function () { - return (this._bitField & 131072) > 0; - }; + Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = require$$3; - Promise.prototype._getDisposer = function () { - return this._disposer; - }; + Bottleneck.Batcher = Bottleneck.prototype.Batcher = Batcher_1; - Promise.prototype._unsetDisposable = function () { - this._bitField = this._bitField & (~131072); - this._disposer = undefined; - }; + Bottleneck.prototype.jobDefaults = { + priority: DEFAULT_PRIORITY$1, + weight: 1, + expiration: null, + id: "" + }; - Promise.prototype.disposer = function (fn) { - if (typeof fn === "function") { - return new FunctionDisposer(fn, this, createContext()); - } - throw new TypeError(); - }; + Bottleneck.prototype.storeDefaults = { + maxConcurrent: null, + minTime: 0, + highWater: null, + strategy: Bottleneck.prototype.strategy.LEAK, + penalty: null, + reservoir: null, + reservoirRefreshInterval: null, + reservoirRefreshAmount: null, + reservoirIncreaseInterval: null, + reservoirIncreaseAmount: null, + reservoirIncreaseMaximum: null + }; -}; + Bottleneck.prototype.localStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 250 + }; + Bottleneck.prototype.redisStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 5000, + clientTimeout: 10000, + Redis: null, + clientOptions: {}, + clusterNodes: null, + clearDatastore: false, + connection: null + }; -/***/ }), + Bottleneck.prototype.instanceDefaults = { + datastore: "local", + connection: null, + id: "", + rejectOnDrop: true, + trackDoneStatus: false, + Promise: Promise + }; -/***/ 37180: -/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { + Bottleneck.prototype.stopDefaults = { + enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", + dropWaitingJobs: true, + dropErrorMessage: "This limiter has been stopped." + }; -"use strict"; + return Bottleneck; -var es5 = __nccwpck_require__(61713); -var canEvaluate = typeof navigator == "undefined"; + }).call(commonjsGlobal); -var errorObj = {e: {}}; -var tryCatchTarget; -var globalObject = typeof self !== "undefined" ? self : - typeof window !== "undefined" ? window : - typeof global !== "undefined" ? global : - this !== undefined ? this : null; + var Bottleneck_1 = Bottleneck; -function tryCatcher() { - try { - var target = tryCatchTarget; - tryCatchTarget = null; - return target.apply(this, arguments); - } catch (e) { - errorObj.e = e; - return errorObj; - } -} -function tryCatch(fn) { - tryCatchTarget = fn; - return tryCatcher; -} + var lib = Bottleneck_1; -var inherits = function(Child, Parent) { - var hasProp = {}.hasOwnProperty; + return lib; - function T() { - this.constructor = Child; - this.constructor$ = Parent; - for (var propertyName in Parent.prototype) { - if (hasProp.call(Parent.prototype, propertyName) && - propertyName.charAt(propertyName.length-1) !== "$" - ) { - this[propertyName + "$"] = Parent.prototype[propertyName]; - } - } - } - T.prototype = Parent.prototype; - Child.prototype = new T(); - return Child.prototype; -}; +}))); -function isPrimitive(val) { - return val == null || val === true || val === false || - typeof val === "string" || typeof val === "number"; +/***/ }), -} +/***/ 33717: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function isObject(value) { - return typeof value === "function" || - typeof value === "object" && value !== null; -} +var concatMap = __nccwpck_require__(86891); +var balanced = __nccwpck_require__(9417); -function maybeWrapAsError(maybeError) { - if (!isPrimitive(maybeError)) return maybeError; +module.exports = expandTop; - return new Error(safeToString(maybeError)); -} +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; -function withAppended(target, appendee) { - var len = target.length; - var ret = new Array(len + 1); - var i; - for (i = 0; i < len; ++i) { - ret[i] = target[i]; - } - ret[i] = appendee; - return ret; +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); } -function getDataPropertyOrDefault(obj, key, defaultValue) { - if (es5.isES5) { - var desc = Object.getOwnPropertyDescriptor(obj, key); - - if (desc != null) { - return desc.get == null && desc.set == null - ? desc.value - : defaultValue; - } - } else { - return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; - } +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); } -function notEnumerableProp(obj, name, value) { - if (isPrimitive(obj)) return obj; - var descriptor = { - value: value, - configurable: true, - enumerable: false, - writable: true - }; - es5.defineProperty(obj, name, descriptor); - return obj; +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); } -function thrower(r) { - throw r; -} -var inheritedDataKeys = (function() { - var excludedPrototypes = [ - Array.prototype, - Object.prototype, - Function.prototype - ]; +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; - var isExcludedProto = function(val) { - for (var i = 0; i < excludedPrototypes.length; ++i) { - if (excludedPrototypes[i] === val) { - return true; - } - } - return false; - }; + var parts = []; + var m = balanced('{', '}', str); - if (es5.isES5) { - var getKeys = Object.getOwnPropertyNames; - return function(obj) { - var ret = []; - var visitedKeys = Object.create(null); - while (obj != null && !isExcludedProto(obj)) { - var keys; - try { - keys = getKeys(obj); - } catch (e) { - return ret; - } - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (visitedKeys[key]) continue; - visitedKeys[key] = true; - var desc = Object.getOwnPropertyDescriptor(obj, key); - if (desc != null && desc.get == null && desc.set == null) { - ret.push(key); - } - } - obj = es5.getPrototypeOf(obj); - } - return ret; - }; - } else { - var hasProp = {}.hasOwnProperty; - return function(obj) { - if (isExcludedProto(obj)) return []; - var ret = []; - - /*jshint forin:false */ - enumeration: for (var key in obj) { - if (hasProp.call(obj, key)) { - ret.push(key); - } else { - for (var i = 0; i < excludedPrototypes.length; ++i) { - if (hasProp.call(excludedPrototypes[i], key)) { - continue enumeration; - } - } - ret.push(key); - } - } - return ret; - }; - } + if (!m) + return str.split(','); -})(); + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); -var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; -function isClass(fn) { - try { - if (typeof fn === "function") { - var keys = es5.names(fn.prototype); + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } - var hasMethods = es5.isES5 && keys.length > 1; - var hasMethodsOtherThanConstructor = keys.length > 0 && - !(keys.length === 1 && keys[0] === "constructor"); - var hasThisAssignmentAndStaticMethods = - thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; + parts.push.apply(parts, p); - if (hasMethods || hasMethodsOtherThanConstructor || - hasThisAssignmentAndStaticMethods) { - return true; - } - } - return false; - } catch (e) { - return false; - } + return parts; } -function toFastProperties(obj) { - /*jshint -W027,-W055,-W031*/ - function FakeConstructor() {} - FakeConstructor.prototype = obj; - var l = 8; - while (l--) new FakeConstructor(); - return obj; - eval(obj); -} +function expandTop(str) { + if (!str) + return []; -var rident = /^[a-z$_][a-z$_0-9]*$/i; -function isIdentifier(str) { - return rident.test(str); -} + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } -function filledRange(count, prefix, suffix) { - var ret = new Array(count); - for(var i = 0; i < count; ++i) { - ret[i] = prefix + i + suffix; - } - return ret; + return expand(escapeBraces(str), true).map(unescapeBraces); } -function safeToString(obj) { - try { - return obj + ""; - } catch (e) { - return "[no string representation]"; - } +function identity(e) { + return e; } -function isError(obj) { - return obj !== null && - typeof obj === "object" && - typeof obj.message === "string" && - typeof obj.name === "string"; +function embrace(str) { + return '{' + str + '}'; } - -function markAsOriginatingFromRejection(e) { - try { - notEnumerableProp(e, "isOperational", true); - } - catch(ignore) {} +function isPadded(el) { + return /^-?0\d/.test(el); } -function originatesFromRejection(e) { - if (e == null) return false; - return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || - e["isOperational"] === true); +function lte(i, y) { + return i <= y; } - -function canAttachTrace(obj) { - return isError(obj) && es5.propertyIsWritable(obj, "stack"); +function gte(i, y) { + return i >= y; } -var ensureErrorObject = (function() { - if (!("stack" in new Error())) { - return function(value) { - if (canAttachTrace(value)) return value; - try {throw new Error(safeToString(value));} - catch(err) {return err;} - }; - } else { - return function(value) { - if (canAttachTrace(value)) return value; - return new Error(safeToString(value)); - }; - } -})(); +function expand(str, isTop) { + var expansions = []; -function classString(obj) { - return {}.toString.call(obj); -} + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; -function copyDescriptors(from, to, filter) { - var keys = es5.names(from); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (filter(key)) { - try { - es5.defineProperty(to, key, es5.getDescriptor(from, key)); - } catch (ignore) {} - } + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); } -} + return [str]; + } -var asArray = function(v) { - if (es5.isArray(v)) { - return v; + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } } - return null; -}; + } -if (typeof Symbol !== "undefined" && Symbol.iterator) { - var ArrayFrom = typeof Array.from === "function" ? function(v) { - return Array.from(v); - } : function(v) { - var ret = []; - var it = v[Symbol.iterator](); - var itResult; - while (!((itResult = it.next()).done)) { - ret.push(itResult.value); - } - return ret; - }; + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. - asArray = function(v) { - if (es5.isArray(v)) { - return v; - } else if (v != null && typeof v[Symbol.iterator] === "function") { - return ArrayFrom(v); - } - return null; - }; -} + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; -var isNode = typeof process !== "undefined" && - classString(process).toLowerCase() === "[object process]"; + var N; -var hasEnvVariables = typeof process !== "undefined" && - typeof process.env !== "undefined"; + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); -function env(key) { - return hasEnvVariables ? process.env[key] : undefined; -} + N = []; -function getNativePromise() { - if (typeof Promise === "function") { - try { - var promise = new Promise(function(){}); - if ({}.toString.call(promise) === "[object Promise]") { - return Promise; - } - } catch (e) {} - } -} - -function domainBind(self, cb) { - return self.bind(cb); -} - -var ret = { - isClass: isClass, - isIdentifier: isIdentifier, - inheritedDataKeys: inheritedDataKeys, - getDataPropertyOrDefault: getDataPropertyOrDefault, - thrower: thrower, - isArray: es5.isArray, - asArray: asArray, - notEnumerableProp: notEnumerableProp, - isPrimitive: isPrimitive, - isObject: isObject, - isError: isError, - canEvaluate: canEvaluate, - errorObj: errorObj, - tryCatch: tryCatch, - inherits: inherits, - withAppended: withAppended, - maybeWrapAsError: maybeWrapAsError, - toFastProperties: toFastProperties, - filledRange: filledRange, - toString: safeToString, - canAttachTrace: canAttachTrace, - ensureErrorObject: ensureErrorObject, - originatesFromRejection: originatesFromRejection, - markAsOriginatingFromRejection: markAsOriginatingFromRejection, - classString: classString, - copyDescriptors: copyDescriptors, - hasDevTools: typeof chrome !== "undefined" && chrome && - typeof chrome.loadTimes === "function", - isNode: isNode, - hasEnvVariables: hasEnvVariables, - env: env, - global: globalObject, - getNativePromise: getNativePromise, - domainBind: domainBind -}; -ret.isRecentNode = ret.isNode && (function() { - var version = process.versions.node.split(".").map(Number); - return (version[0] === 0 && version[1] > 10) || (version[0] > 0); -})(); + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el, false) }); + } + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } -if (ret.isNode) ret.toFastProperties(process); + return expansions; +} -try {throw new Error(); } catch (e) {ret.lastLineError = e;} -module.exports = ret; /***/ }), -/***/ 90058: -/***/ (function(module) { - -/** - * This file contains the Bottleneck library (MIT), compiled to ES2017, and without Clustering support. - * https://github.com/SGrondin/bottleneck - */ -(function (global, factory) { - true ? module.exports = factory() : - 0; -}(this, (function () { 'use strict'; +/***/ 84794: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; +var Buffer = (__nccwpck_require__(14300).Buffer); - function getCjsExportFromNamespace (n) { - return n && n['default'] || n; - } +var CRC_TABLE = [ + 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, + 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, + 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, + 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, + 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, + 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, + 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, + 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, + 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, + 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, + 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, + 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, + 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, + 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, + 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, + 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, + 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, + 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, + 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, + 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, + 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, + 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, + 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, + 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, + 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, + 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, + 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, + 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, + 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, + 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, + 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, + 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, + 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, + 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, + 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, + 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, + 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, + 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, + 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, + 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, + 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, + 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, + 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, + 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, + 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, + 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, + 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, + 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, + 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, + 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, + 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, + 0x2d02ef8d +]; - var load = function(received, defaults, onto = {}) { - var k, ref, v; - for (k in defaults) { - v = defaults[k]; - onto[k] = (ref = received[k]) != null ? ref : v; - } - return onto; - }; +if (typeof Int32Array !== 'undefined') { + CRC_TABLE = new Int32Array(CRC_TABLE); +} - var overwrite = function(received, defaults, onto = {}) { - var k, v; - for (k in received) { - v = received[k]; - if (defaults[k] !== void 0) { - onto[k] = v; - } - } - return onto; - }; +function ensureBuffer(input) { + if (Buffer.isBuffer(input)) { + return input; + } - var parser = { - load: load, - overwrite: overwrite - }; + var hasNewBufferAPI = + typeof Buffer.alloc === "function" && + typeof Buffer.from === "function"; - var DLList; + if (typeof input === "number") { + return hasNewBufferAPI ? Buffer.alloc(input) : new Buffer(input); + } + else if (typeof input === "string") { + return hasNewBufferAPI ? Buffer.from(input) : new Buffer(input); + } + else { + throw new Error("input must be buffer, number, or string, received " + + typeof input); + } +} - DLList = class DLList { - constructor(incr, decr) { - this.incr = incr; - this.decr = decr; - this._first = null; - this._last = null; - this.length = 0; - } +function bufferizeInt(num) { + var tmp = ensureBuffer(4); + tmp.writeInt32BE(num, 0); + return tmp; +} - push(value) { - var node; - this.length++; - if (typeof this.incr === "function") { - this.incr(); - } - node = { - value, - prev: this._last, - next: null - }; - if (this._last != null) { - this._last.next = node; - this._last = node; - } else { - this._first = this._last = node; - } - return void 0; - } - - shift() { - var value; - if (this._first == null) { - return; - } else { - this.length--; - if (typeof this.decr === "function") { - this.decr(); - } - } - value = this._first.value; - if ((this._first = this._first.next) != null) { - this._first.prev = null; - } else { - this._last = null; - } - return value; - } +function _crc32(buf, previous) { + buf = ensureBuffer(buf); + if (Buffer.isBuffer(previous)) { + previous = previous.readUInt32BE(0); + } + var crc = ~~previous ^ -1; + for (var n = 0; n < buf.length; n++) { + crc = CRC_TABLE[(crc ^ buf[n]) & 0xff] ^ (crc >>> 8); + } + return (crc ^ -1); +} - first() { - if (this._first != null) { - return this._first.value; - } - } +function crc32() { + return bufferizeInt(_crc32.apply(null, arguments)); +} +crc32.signed = function () { + return _crc32.apply(null, arguments); +}; +crc32.unsigned = function () { + return _crc32.apply(null, arguments) >>> 0; +}; - getArray() { - var node, ref, results; - node = this._first; - results = []; - while (node != null) { - results.push((ref = node, node = node.next, ref.value)); - } - return results; - } +module.exports = crc32; - forEachShift(cb) { - var node; - node = this.shift(); - while (node != null) { - (cb(node), node = this.shift()); - } - return void 0; - } - debug() { - var node, ref, ref1, ref2, results; - node = this._first; - results = []; - while (node != null) { - results.push((ref = node, node = node.next, { - value: ref.value, - prev: (ref1 = ref.prev) != null ? ref1.value : void 0, - next: (ref2 = ref.next) != null ? ref2.value : void 0 - })); - } - return results; - } +/***/ }), - }; +/***/ 51590: +/***/ ((module) => { - var DLList_1 = DLList; +module.exports = Buffers; - var Events; +function Buffers (bufs) { + if (!(this instanceof Buffers)) return new Buffers(bufs); + this.buffers = bufs || []; + this.length = this.buffers.reduce(function (size, buf) { + return size + buf.length + }, 0); +} - Events = class Events { - constructor(instance) { - this.instance = instance; - this._events = {}; - if ((this.instance.on != null) || (this.instance.once != null) || (this.instance.removeAllListeners != null)) { - throw new Error("An Emitter already exists for this object"); - } - this.instance.on = (name, cb) => { - return this._addListener(name, "many", cb); - }; - this.instance.once = (name, cb) => { - return this._addListener(name, "once", cb); - }; - this.instance.removeAllListeners = (name = null) => { - if (name != null) { - return delete this._events[name]; - } else { - return this._events = {}; - } - }; - } +Buffers.prototype.push = function () { + for (var i = 0; i < arguments.length; i++) { + if (!Buffer.isBuffer(arguments[i])) { + throw new TypeError('Tried to push a non-buffer'); + } + } + + for (var i = 0; i < arguments.length; i++) { + var buf = arguments[i]; + this.buffers.push(buf); + this.length += buf.length; + } + return this.length; +}; - _addListener(name, status, cb) { - var base; - if ((base = this._events)[name] == null) { - base[name] = []; - } - this._events[name].push({cb, status}); - return this.instance; - } +Buffers.prototype.unshift = function () { + for (var i = 0; i < arguments.length; i++) { + if (!Buffer.isBuffer(arguments[i])) { + throw new TypeError('Tried to unshift a non-buffer'); + } + } + + for (var i = 0; i < arguments.length; i++) { + var buf = arguments[i]; + this.buffers.unshift(buf); + this.length += buf.length; + } + return this.length; +}; - listenerCount(name) { - if (this._events[name] != null) { - return this._events[name].length; - } else { - return 0; - } - } +Buffers.prototype.copy = function (dst, dStart, start, end) { + return this.slice(start, end).copy(dst, dStart, 0, end - start); +}; - async trigger(name, ...args) { - var e, promises; - try { - if (name !== "debug") { - this.trigger("debug", `Event triggered: ${name}`, args); - } - if (this._events[name] == null) { - return; - } - this._events[name] = this._events[name].filter(function(listener) { - return listener.status !== "none"; - }); - promises = this._events[name].map(async(listener) => { - var e, returned; - if (listener.status === "none") { - return; - } - if (listener.status === "once") { - listener.status = "none"; - } - try { - returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0; - if (typeof (returned != null ? returned.then : void 0) === "function") { - return (await returned); - } else { - return returned; - } - } catch (error) { - e = error; - { - this.trigger("error", e); - } - return null; - } - }); - return ((await Promise.all(promises))).find(function(x) { - return x != null; - }); - } catch (error) { - e = error; - { - this.trigger("error", e); - } - return null; - } - } +Buffers.prototype.splice = function (i, howMany) { + var buffers = this.buffers; + var index = i >= 0 ? i : this.length - i; + var reps = [].slice.call(arguments, 2); + + if (howMany === undefined) { + howMany = this.length - index; + } + else if (howMany > this.length - index) { + howMany = this.length - index; + } + + for (var i = 0; i < reps.length; i++) { + this.length += reps[i].length; + } + + var removed = new Buffers(); + var bytes = 0; + + var startBytes = 0; + for ( + var ii = 0; + ii < buffers.length && startBytes + buffers[ii].length < index; + ii ++ + ) { startBytes += buffers[ii].length } + + if (index - startBytes > 0) { + var start = index - startBytes; + + if (start + howMany < buffers[ii].length) { + removed.push(buffers[ii].slice(start, start + howMany)); + + var orig = buffers[ii]; + //var buf = new Buffer(orig.length - howMany); + var buf0 = new Buffer(start); + for (var i = 0; i < start; i++) { + buf0[i] = orig[i]; + } + + var buf1 = new Buffer(orig.length - start - howMany); + for (var i = start + howMany; i < orig.length; i++) { + buf1[ i - howMany - start ] = orig[i] + } + + if (reps.length > 0) { + var reps_ = reps.slice(); + reps_.unshift(buf0); + reps_.push(buf1); + buffers.splice.apply(buffers, [ ii, 1 ].concat(reps_)); + ii += reps_.length; + reps = []; + } + else { + buffers.splice(ii, 1, buf0, buf1); + //buffers[ii] = buf; + ii += 2; + } + } + else { + removed.push(buffers[ii].slice(start)); + buffers[ii] = buffers[ii].slice(0, start); + ii ++; + } + } + + if (reps.length > 0) { + buffers.splice.apply(buffers, [ ii, 0 ].concat(reps)); + ii += reps.length; + } + + while (removed.length < howMany) { + var buf = buffers[ii]; + var len = buf.length; + var take = Math.min(len, howMany - removed.length); + + if (take === len) { + removed.push(buf); + buffers.splice(ii, 1); + } + else { + removed.push(buf.slice(0, take)); + buffers[ii] = buffers[ii].slice(take); + } + } + + this.length -= removed.length; + + return removed; +}; + +Buffers.prototype.slice = function (i, j) { + var buffers = this.buffers; + if (j === undefined) j = this.length; + if (i === undefined) i = 0; + + if (j > this.length) j = this.length; + + var startBytes = 0; + for ( + var si = 0; + si < buffers.length && startBytes + buffers[si].length <= i; + si ++ + ) { startBytes += buffers[si].length } + + var target = new Buffer(j - i); + + var ti = 0; + for (var ii = si; ti < j - i && ii < buffers.length; ii++) { + var len = buffers[ii].length; + + var start = ti === 0 ? i - startBytes : 0; + var end = ti + len >= j - i + ? Math.min(start + (j - i) - ti, len) + : len + ; + + buffers[ii].copy(target, ti, start, end); + ti += end - start; + } + + return target; +}; - }; +Buffers.prototype.pos = function (i) { + if (i < 0 || i >= this.length) throw new Error('oob'); + var l = i, bi = 0, bu = null; + for (;;) { + bu = this.buffers[bi]; + if (l < bu.length) { + return {buf: bi, offset: l}; + } else { + l -= bu.length; + } + bi++; + } +}; - var Events_1 = Events; +Buffers.prototype.get = function get (i) { + var pos = this.pos(i); - var DLList$1, Events$1, Queues; + return this.buffers[pos.buf].get(pos.offset); +}; - DLList$1 = DLList_1; +Buffers.prototype.set = function set (i, b) { + var pos = this.pos(i); - Events$1 = Events_1; + return this.buffers[pos.buf].set(pos.offset, b); +}; - Queues = class Queues { - constructor(num_priorities) { - var i; - this.Events = new Events$1(this); - this._length = 0; - this._lists = (function() { - var j, ref, results; - results = []; - for (i = j = 1, ref = num_priorities; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) { - results.push(new DLList$1((() => { - return this.incr(); - }), (() => { - return this.decr(); - }))); - } - return results; - }).call(this); - } +Buffers.prototype.indexOf = function (needle, offset) { + if ("string" === typeof needle) { + needle = new Buffer(needle); + } else if (needle instanceof Buffer) { + // already a buffer + } else { + throw new Error('Invalid type for a search string'); + } - incr() { - if (this._length++ === 0) { - return this.Events.trigger("leftzero"); - } - } + if (!needle.length) { + return 0; + } - decr() { - if (--this._length === 0) { - return this.Events.trigger("zero"); - } - } + if (!this.length) { + return -1; + } - push(job) { - return this._lists[job.options.priority].push(job); - } + var i = 0, j = 0, match = 0, mstart, pos = 0; - queued(priority) { - if (priority != null) { - return this._lists[priority].length; - } else { - return this._length; - } - } + // start search from a particular point in the virtual buffer + if (offset) { + var p = this.pos(offset); + i = p.buf; + j = p.offset; + pos = offset; + } - shiftAll(fn) { - return this._lists.forEach(function(list) { - return list.forEachShift(fn); - }); - } + // for each character in virtual buffer + for (;;) { + while (j >= this.buffers[i].length) { + j = 0; + i++; - getFirst(arr = this._lists) { - var j, len, list; - for (j = 0, len = arr.length; j < len; j++) { - list = arr[j]; - if (list.length > 0) { - return list; - } - } - return []; - } + if (i >= this.buffers.length) { + // search string not found + return -1; + } + } - shiftLastFrom(priority) { - return this.getFirst(this._lists.slice(priority).reverse()).shift(); - } + var char = this.buffers[i][j]; - }; + if (char == needle[match]) { + // keep track where match started + if (match == 0) { + mstart = { + i: i, + j: j, + pos: pos + }; + } + match++; + if (match == needle.length) { + // full match + return mstart.pos; + } + } else if (match != 0) { + // a partial match ended, go back to match starting position + // this will continue the search at the next character + i = mstart.i; + j = mstart.j; + pos = mstart.pos; + match = 0; + } - var Queues_1 = Queues; + j++; + pos++; + } +}; - var BottleneckError; +Buffers.prototype.toBuffer = function() { + return this.slice(); +} - BottleneckError = class BottleneckError extends Error {}; +Buffers.prototype.toString = function(encoding, start, end) { + return this.slice(start, end).toString(encoding); +} - var BottleneckError_1 = BottleneckError; - var BottleneckError$1, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser$1; +/***/ }), - NUM_PRIORITIES = 10; +/***/ 46533: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - DEFAULT_PRIORITY = 5; +var Traverse = __nccwpck_require__(8588); +var EventEmitter = (__nccwpck_require__(82361).EventEmitter); - parser$1 = parser; +module.exports = Chainsaw; +function Chainsaw (builder) { + var saw = Chainsaw.saw(builder, {}); + var r = builder.call(saw.handlers, saw); + if (r !== undefined) saw.handlers = r; + saw.record(); + return saw.chain(); +}; - BottleneckError$1 = BottleneckError_1; +Chainsaw.light = function ChainsawLight (builder) { + var saw = Chainsaw.saw(builder, {}); + var r = builder.call(saw.handlers, saw); + if (r !== undefined) saw.handlers = r; + return saw.chain(); +}; - Job = class Job { - constructor(task, args, options, jobDefaults, rejectOnDrop, Events, _states, Promise) { - this.task = task; - this.args = args; - this.rejectOnDrop = rejectOnDrop; - this.Events = Events; - this._states = _states; - this.Promise = Promise; - this.options = parser$1.load(options, jobDefaults); - this.options.priority = this._sanitizePriority(this.options.priority); - if (this.options.id === jobDefaults.id) { - this.options.id = `${this.options.id}-${this._randomIndex()}`; - } - this.promise = new this.Promise((_resolve, _reject) => { - this._resolve = _resolve; - this._reject = _reject; - }); - this.retryCount = 0; - } +Chainsaw.saw = function (builder, handlers) { + var saw = new EventEmitter; + saw.handlers = handlers; + saw.actions = []; - _sanitizePriority(priority) { - var sProperty; - sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority; - if (sProperty < 0) { - return 0; - } else if (sProperty > NUM_PRIORITIES - 1) { - return NUM_PRIORITIES - 1; - } else { - return sProperty; - } - } + saw.chain = function () { + var ch = Traverse(saw.handlers).map(function (node) { + if (this.isRoot) return node; + var ps = this.path; - _randomIndex() { - return Math.random().toString(36).slice(2); - } + if (typeof node === 'function') { + this.update(function () { + saw.actions.push({ + path : ps, + args : [].slice.call(arguments) + }); + return ch; + }); + } + }); - doDrop({error, message = "This job has been dropped by Bottleneck"} = {}) { - if (this._states.remove(this.options.id)) { - if (this.rejectOnDrop) { - this._reject(error != null ? error : new BottleneckError$1(message)); - } - this.Events.trigger("dropped", {args: this.args, options: this.options, task: this.task, promise: this.promise}); - return true; - } else { - return false; - } - } + process.nextTick(function () { + saw.emit('begin'); + saw.next(); + }); - _assertStatus(expected) { - var status; - status = this._states.jobStatus(this.options.id); - if (!(status === expected || (expected === "DONE" && status === null))) { - throw new BottleneckError$1(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`); - } - } + return ch; + }; - doReceive() { - this._states.start(this.options.id); - return this.Events.trigger("received", {args: this.args, options: this.options}); - } + saw.pop = function () { + return saw.actions.shift(); + }; - doQueue(reachedHWM, blocked) { - this._assertStatus("RECEIVED"); - this._states.next(this.options.id); - return this.Events.trigger("queued", {args: this.args, options: this.options, reachedHWM, blocked}); - } + saw.next = function () { + var action = saw.pop(); - doRun() { - if (this.retryCount === 0) { - this._assertStatus("QUEUED"); - this._states.next(this.options.id); - } else { - this._assertStatus("EXECUTING"); - } - return this.Events.trigger("scheduled", {args: this.args, options: this.options}); - } + if (!action) { + saw.emit('end'); + } + else if (!action.trap) { + var node = saw.handlers; + action.path.forEach(function (key) { node = node[key] }); + node.apply(saw.handlers, action.args); + } + }; - async doExecute(chained, clearGlobalState, run, free) { - var error, eventInfo, passed; - if (this.retryCount === 0) { - this._assertStatus("RUNNING"); - this._states.next(this.options.id); - } else { - this._assertStatus("EXECUTING"); - } - eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount}; - this.Events.trigger("executing", eventInfo); - try { - passed = (await (chained != null ? chained.schedule(this.options, this.task, ...this.args) : this.task(...this.args))); - if (clearGlobalState()) { - this.doDone(eventInfo); - await free(this.options, eventInfo); - this._assertStatus("DONE"); - return this._resolve(passed); - } - } catch (error1) { - error = error1; - return this._onFailure(error, eventInfo, clearGlobalState, run, free); - } - } + saw.nest = function (cb) { + var args = [].slice.call(arguments, 1); + var autonext = true; - doExpire(clearGlobalState, run, free) { - var error, eventInfo; - if (this._states.jobStatus(this.options.id === "RUNNING")) { - this._states.next(this.options.id); - } - this._assertStatus("EXECUTING"); - eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount}; - error = new BottleneckError$1(`This job timed out after ${this.options.expiration} ms.`); - return this._onFailure(error, eventInfo, clearGlobalState, run, free); - } + if (typeof cb === 'boolean') { + var autonext = cb; + cb = args.shift(); + } - async _onFailure(error, eventInfo, clearGlobalState, run, free) { - var retry, retryAfter; - if (clearGlobalState()) { - retry = (await this.Events.trigger("failed", error, eventInfo)); - if (retry != null) { - retryAfter = ~~retry; - this.Events.trigger("retry", `Retrying ${this.options.id} after ${retryAfter} ms`, eventInfo); - this.retryCount++; - return run(retryAfter); - } else { - this.doDone(eventInfo); - await free(this.options, eventInfo); - this._assertStatus("DONE"); - return this._reject(error); - } - } - } + var s = Chainsaw.saw(builder, {}); + var r = builder.call(s.handlers, s); - doDone(eventInfo) { - this._assertStatus("EXECUTING"); - this._states.next(this.options.id); - return this.Events.trigger("done", eventInfo); - } + if (r !== undefined) s.handlers = r; - }; + // If we are recording... + if ("undefined" !== typeof saw.step) { + // ... our children should, too + s.record(); + } - var Job_1 = Job; + cb.apply(s.chain(), args); + if (autonext !== false) s.on('end', saw.next); + }; - var BottleneckError$2, LocalDatastore, parser$2; + saw.record = function () { + upgradeChainsaw(saw); + }; - parser$2 = parser; + ['trap', 'down', 'jump'].forEach(function (method) { + saw[method] = function () { + throw new Error("To use the trap, down and jump features, please "+ + "call record() first to start recording actions."); + }; + }); - BottleneckError$2 = BottleneckError_1; + return saw; +}; - LocalDatastore = class LocalDatastore { - constructor(instance, storeOptions, storeInstanceOptions) { - this.instance = instance; - this.storeOptions = storeOptions; - this.clientId = this.instance._randomIndex(); - parser$2.load(storeInstanceOptions, storeInstanceOptions, this); - this._nextRequest = this._lastReservoirRefresh = this._lastReservoirIncrease = Date.now(); - this._running = 0; - this._done = 0; - this._unblockTime = 0; - this.ready = this.Promise.resolve(); - this.clients = {}; - this._startHeartbeat(); - } +function upgradeChainsaw(saw) { + saw.step = 0; - _startHeartbeat() { - var base; - if ((this.heartbeat == null) && (((this.storeOptions.reservoirRefreshInterval != null) && (this.storeOptions.reservoirRefreshAmount != null)) || ((this.storeOptions.reservoirIncreaseInterval != null) && (this.storeOptions.reservoirIncreaseAmount != null)))) { - return typeof (base = (this.heartbeat = setInterval(() => { - var amount, incr, maximum, now, reservoir; - now = Date.now(); - if ((this.storeOptions.reservoirRefreshInterval != null) && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { - this._lastReservoirRefresh = now; - this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; - this.instance._drainAll(this.computeCapacity()); - } - if ((this.storeOptions.reservoirIncreaseInterval != null) && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) { - ({ - reservoirIncreaseAmount: amount, - reservoirIncreaseMaximum: maximum, - reservoir - } = this.storeOptions); - this._lastReservoirIncrease = now; - incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount; - if (incr > 0) { - this.storeOptions.reservoir += incr; - return this.instance._drainAll(this.computeCapacity()); - } - } - }, this.heartbeatInterval))).unref === "function" ? base.unref() : void 0; - } else { - return clearInterval(this.heartbeat); - } - } + // override pop + saw.pop = function () { + return saw.actions[saw.step++]; + }; - async __publish__(message) { - await this.yieldLoop(); - return this.instance.Events.trigger("message", message.toString()); - } + saw.trap = function (name, cb) { + var ps = Array.isArray(name) ? name : [name]; + saw.actions.push({ + path : ps, + step : saw.step, + cb : cb, + trap : true + }); + }; - async __disconnect__(flush) { - await this.yieldLoop(); - clearInterval(this.heartbeat); - return this.Promise.resolve(); - } + saw.down = function (name) { + var ps = (Array.isArray(name) ? name : [name]).join('/'); + var i = saw.actions.slice(saw.step).map(function (x) { + if (x.trap && x.step <= saw.step) return false; + return x.path.join('/') == ps; + }).indexOf(true); - yieldLoop(t = 0) { - return new this.Promise(function(resolve, reject) { - return setTimeout(resolve, t); - }); - } + if (i >= 0) saw.step += i; + else saw.step = saw.actions.length; - computePenalty() { - var ref; - return (ref = this.storeOptions.penalty) != null ? ref : (15 * this.storeOptions.minTime) || 5000; - } + var act = saw.actions[saw.step - 1]; + if (act && act.trap) { + // It's a trap! + saw.step = act.step; + act.cb(); + } + else saw.next(); + }; - async __updateSettings__(options) { - await this.yieldLoop(); - parser$2.overwrite(options, options, this.storeOptions); - this._startHeartbeat(); - this.instance._drainAll(this.computeCapacity()); - return true; - } + saw.jump = function (step) { + saw.step = step; + saw.next(); + }; +}; - async __running__() { - await this.yieldLoop(); - return this._running; - } - async __queued__() { - await this.yieldLoop(); - return this.instance.queued(); - } +/***/ }), - async __done__() { - await this.yieldLoop(); - return this._done; - } +/***/ 85443: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - async __groupCheck__(time) { - await this.yieldLoop(); - return (this._nextRequest + this.timeout) < time; - } +var util = __nccwpck_require__(73837); +var Stream = (__nccwpck_require__(12781).Stream); +var DelayedStream = __nccwpck_require__(18611); - computeCapacity() { - var maxConcurrent, reservoir; - ({maxConcurrent, reservoir} = this.storeOptions); - if ((maxConcurrent != null) && (reservoir != null)) { - return Math.min(maxConcurrent - this._running, reservoir); - } else if (maxConcurrent != null) { - return maxConcurrent - this._running; - } else if (reservoir != null) { - return reservoir; - } else { - return null; - } - } +module.exports = CombinedStream; +function CombinedStream() { + this.writable = false; + this.readable = true; + this.dataSize = 0; + this.maxDataSize = 2 * 1024 * 1024; + this.pauseStreams = true; - conditionsCheck(weight) { - var capacity; - capacity = this.computeCapacity(); - return (capacity == null) || weight <= capacity; - } + this._released = false; + this._streams = []; + this._currentStream = null; + this._insideLoop = false; + this._pendingNext = false; +} +util.inherits(CombinedStream, Stream); - async __incrementReservoir__(incr) { - var reservoir; - await this.yieldLoop(); - reservoir = this.storeOptions.reservoir += incr; - this.instance._drainAll(this.computeCapacity()); - return reservoir; - } +CombinedStream.create = function(options) { + var combinedStream = new this(); - async __currentReservoir__() { - await this.yieldLoop(); - return this.storeOptions.reservoir; - } + options = options || {}; + for (var option in options) { + combinedStream[option] = options[option]; + } - isBlocked(now) { - return this._unblockTime >= now; - } + return combinedStream; +}; - check(weight, now) { - return this.conditionsCheck(weight) && (this._nextRequest - now) <= 0; - } +CombinedStream.isStreamLike = function(stream) { + return (typeof stream !== 'function') + && (typeof stream !== 'string') + && (typeof stream !== 'boolean') + && (typeof stream !== 'number') + && (!Buffer.isBuffer(stream)); +}; - async __check__(weight) { - var now; - await this.yieldLoop(); - now = Date.now(); - return this.check(weight, now); - } +CombinedStream.prototype.append = function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); - async __register__(index, weight, expiration) { - var now, wait; - await this.yieldLoop(); - now = Date.now(); - if (this.conditionsCheck(weight)) { - this._running += weight; - if (this.storeOptions.reservoir != null) { - this.storeOptions.reservoir -= weight; - } - wait = Math.max(this._nextRequest - now, 0); - this._nextRequest = now + wait + this.storeOptions.minTime; - return { - success: true, - wait, - reservoir: this.storeOptions.reservoir - }; - } else { - return { - success: false - }; - } - } + if (isStreamLike) { + if (!(stream instanceof DelayedStream)) { + var newStream = DelayedStream.create(stream, { + maxDataSize: Infinity, + pauseStream: this.pauseStreams, + }); + stream.on('data', this._checkDataSize.bind(this)); + stream = newStream; + } - strategyIsBlock() { - return this.storeOptions.strategy === 3; - } + this._handleErrors(stream); - async __submit__(queueLength, weight) { - var blocked, now, reachedHWM; - await this.yieldLoop(); - if ((this.storeOptions.maxConcurrent != null) && weight > this.storeOptions.maxConcurrent) { - throw new BottleneckError$2(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${this.storeOptions.maxConcurrent}`); - } - now = Date.now(); - reachedHWM = (this.storeOptions.highWater != null) && queueLength === this.storeOptions.highWater && !this.check(weight, now); - blocked = this.strategyIsBlock() && (reachedHWM || this.isBlocked(now)); - if (blocked) { - this._unblockTime = now + this.computePenalty(); - this._nextRequest = this._unblockTime + this.storeOptions.minTime; - this.instance._dropAllQueued(); - } - return { - reachedHWM, - blocked, - strategy: this.storeOptions.strategy - }; - } + if (this.pauseStreams) { + stream.pause(); + } + } - async __free__(index, weight) { - await this.yieldLoop(); - this._running -= weight; - this._done += weight; - this.instance._drainAll(this.computeCapacity()); - return { - running: this._running - }; - } + this._streams.push(stream); + return this; +}; - }; +CombinedStream.prototype.pipe = function(dest, options) { + Stream.prototype.pipe.call(this, dest, options); + this.resume(); + return dest; +}; - var LocalDatastore_1 = LocalDatastore; +CombinedStream.prototype._getNext = function() { + this._currentStream = null; - var BottleneckError$3, States; + if (this._insideLoop) { + this._pendingNext = true; + return; // defer call + } - BottleneckError$3 = BottleneckError_1; + this._insideLoop = true; + try { + do { + this._pendingNext = false; + this._realGetNext(); + } while (this._pendingNext); + } finally { + this._insideLoop = false; + } +}; - States = class States { - constructor(status1) { - this.status = status1; - this._jobs = {}; - this.counts = this.status.map(function() { - return 0; - }); - } +CombinedStream.prototype._realGetNext = function() { + var stream = this._streams.shift(); - next(id) { - var current, next; - current = this._jobs[id]; - next = current + 1; - if ((current != null) && next < this.status.length) { - this.counts[current]--; - this.counts[next]++; - return this._jobs[id]++; - } else if (current != null) { - this.counts[current]--; - return delete this._jobs[id]; - } - } - start(id) { - var initial; - initial = 0; - this._jobs[id] = initial; - return this.counts[initial]++; - } - - remove(id) { - var current; - current = this._jobs[id]; - if (current != null) { - this.counts[current]--; - delete this._jobs[id]; - } - return current != null; - } + if (typeof stream == 'undefined') { + this.end(); + return; + } - jobStatus(id) { - var ref; - return (ref = this.status[this._jobs[id]]) != null ? ref : null; - } + if (typeof stream !== 'function') { + this._pipeNext(stream); + return; + } - statusJobs(status) { - var k, pos, ref, results, v; - if (status != null) { - pos = this.status.indexOf(status); - if (pos < 0) { - throw new BottleneckError$3(`status must be one of ${this.status.join(', ')}`); - } - ref = this._jobs; - results = []; - for (k in ref) { - v = ref[k]; - if (v === pos) { - results.push(k); - } - } - return results; - } else { - return Object.keys(this._jobs); - } - } + var getStream = stream; + getStream(function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('data', this._checkDataSize.bind(this)); + this._handleErrors(stream); + } - statusCounts() { - return this.counts.reduce(((acc, v, i) => { - acc[this.status[i]] = v; - return acc; - }), {}); - } + this._pipeNext(stream); + }.bind(this)); +}; - }; +CombinedStream.prototype._pipeNext = function(stream) { + this._currentStream = stream; - var States_1 = States; + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('end', this._getNext.bind(this)); + stream.pipe(this, {end: false}); + return; + } - var DLList$2, Sync; + var value = stream; + this.write(value); + this._getNext(); +}; - DLList$2 = DLList_1; +CombinedStream.prototype._handleErrors = function(stream) { + var self = this; + stream.on('error', function(err) { + self._emitError(err); + }); +}; - Sync = class Sync { - constructor(name, Promise) { - this.schedule = this.schedule.bind(this); - this.name = name; - this.Promise = Promise; - this._running = 0; - this._queue = new DLList$2(); - } +CombinedStream.prototype.write = function(data) { + this.emit('data', data); +}; - isEmpty() { - return this._queue.length === 0; - } +CombinedStream.prototype.pause = function() { + if (!this.pauseStreams) { + return; + } - async _tryToRun() { - var args, cb, error, reject, resolve, returned, task; - if ((this._running < 1) && this._queue.length > 0) { - this._running++; - ({task, args, resolve, reject} = this._queue.shift()); - cb = (await (async function() { - try { - returned = (await task(...args)); - return function() { - return resolve(returned); - }; - } catch (error1) { - error = error1; - return function() { - return reject(error); - }; - } - })()); - this._running--; - this._tryToRun(); - return cb(); - } - } + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); + this.emit('pause'); +}; - schedule(task, ...args) { - var promise, reject, resolve; - resolve = reject = null; - promise = new this.Promise(function(_resolve, _reject) { - resolve = _resolve; - return reject = _reject; - }); - this._queue.push({task, args, resolve, reject}); - this._tryToRun(); - return promise; - } +CombinedStream.prototype.resume = function() { + if (!this._released) { + this._released = true; + this.writable = true; + this._getNext(); + } - }; + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); + this.emit('resume'); +}; - var Sync_1 = Sync; +CombinedStream.prototype.end = function() { + this._reset(); + this.emit('end'); +}; - var version = "2.19.5"; - var version$1 = { - version: version - }; +CombinedStream.prototype.destroy = function() { + this._reset(); + this.emit('close'); +}; - var version$2 = /*#__PURE__*/Object.freeze({ - version: version, - default: version$1 - }); +CombinedStream.prototype._reset = function() { + this.writable = false; + this._streams = []; + this._currentStream = null; +}; - var require$$2 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); +CombinedStream.prototype._checkDataSize = function() { + this._updateDataSize(); + if (this.dataSize <= this.maxDataSize) { + return; + } - var require$$3 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; + this._emitError(new Error(message)); +}; - var require$$4 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); +CombinedStream.prototype._updateDataSize = function() { + this.dataSize = 0; - var Events$2, Group, IORedisConnection$1, RedisConnection$1, Scripts$1, parser$3; + var self = this; + this._streams.forEach(function(stream) { + if (!stream.dataSize) { + return; + } - parser$3 = parser; + self.dataSize += stream.dataSize; + }); - Events$2 = Events_1; + if (this._currentStream && this._currentStream.dataSize) { + this.dataSize += this._currentStream.dataSize; + } +}; - RedisConnection$1 = require$$2; +CombinedStream.prototype._emitError = function(err) { + this._reset(); + this.emit('error', err); +}; - IORedisConnection$1 = require$$3; - Scripts$1 = require$$4; +/***/ }), - Group = (function() { - class Group { - constructor(limiterOptions = {}) { - this.deleteKey = this.deleteKey.bind(this); - this.limiterOptions = limiterOptions; - parser$3.load(this.limiterOptions, this.defaults, this); - this.Events = new Events$2(this); - this.instances = {}; - this.Bottleneck = Bottleneck_1; - this._startAutoCleanup(); - this.sharedConnection = this.connection != null; - if (this.connection == null) { - if (this.limiterOptions.datastore === "redis") { - this.connection = new RedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); - } else if (this.limiterOptions.datastore === "ioredis") { - this.connection = new IORedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); - } - } - } +/***/ 92240: +/***/ ((module) => { - key(key = "") { - var ref; - return (ref = this.instances[key]) != null ? ref : (() => { - var limiter; - limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, { - id: `${this.id}-${key}`, - timeout: this.timeout, - connection: this.connection - })); - this.Events.trigger("created", limiter, key); - return limiter; - })(); - } +/** + * node-compress-commons + * + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT + */ +var ArchiveEntry = module.exports = function() {}; - async deleteKey(key = "") { - var deleted, instance; - instance = this.instances[key]; - if (this.connection) { - deleted = (await this.connection.__runCommand__(['del', ...Scripts$1.allKeys(`${this.id}-${key}`)])); - } - if (instance != null) { - delete this.instances[key]; - await instance.disconnect(); - } - return (instance != null) || deleted > 0; - } +ArchiveEntry.prototype.getName = function() {}; - limiters() { - var k, ref, results, v; - ref = this.instances; - results = []; - for (k in ref) { - v = ref[k]; - results.push({ - key: k, - limiter: v - }); - } - return results; - } +ArchiveEntry.prototype.getSize = function() {}; - keys() { - return Object.keys(this.instances); - } +ArchiveEntry.prototype.getLastModifiedDate = function() {}; - async clusterKeys() { - var cursor, end, found, i, k, keys, len, next, start; - if (this.connection == null) { - return this.Promise.resolve(this.keys()); - } - keys = []; - cursor = null; - start = `b_${this.id}-`.length; - end = "_settings".length; - while (cursor !== 0) { - [next, found] = (await this.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${this.id}-*_settings`, "count", 10000])); - cursor = ~~next; - for (i = 0, len = found.length; i < len; i++) { - k = found[i]; - keys.push(k.slice(start, -end)); - } - } - return keys; - } +ArchiveEntry.prototype.isDirectory = function() {}; - _startAutoCleanup() { - var base; - clearInterval(this.interval); - return typeof (base = (this.interval = setInterval(async() => { - var e, k, ref, results, time, v; - time = Date.now(); - ref = this.instances; - results = []; - for (k in ref) { - v = ref[k]; - try { - if ((await v._store.__groupCheck__(time))) { - results.push(this.deleteKey(k)); - } else { - results.push(void 0); - } - } catch (error) { - e = error; - results.push(v.Events.trigger("error", e)); - } - } - return results; - }, this.timeout / 2))).unref === "function" ? base.unref() : void 0; - } +/***/ }), - updateSettings(options = {}) { - parser$3.overwrite(options, this.defaults, this); - parser$3.overwrite(options, options, this.limiterOptions); - if (options.timeout != null) { - return this._startAutoCleanup(); - } - } +/***/ 36728: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - disconnect(flush = true) { - var ref; - if (!this.sharedConnection) { - return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; - } - } +/** + * node-compress-commons + * + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT + */ +var inherits = (__nccwpck_require__(73837).inherits); +var Transform = (__nccwpck_require__(51642).Transform); - } - Group.prototype.defaults = { - timeout: 1000 * 60 * 5, - connection: null, - Promise: Promise, - id: "group-key" - }; +var ArchiveEntry = __nccwpck_require__(92240); +var util = __nccwpck_require__(95208); - return Group; +var ArchiveOutputStream = module.exports = function(options) { + if (!(this instanceof ArchiveOutputStream)) { + return new ArchiveOutputStream(options); + } - }).call(commonjsGlobal); + Transform.call(this, options); - var Group_1 = Group; + this.offset = 0; + this._archive = { + finish: false, + finished: false, + processing: false + }; +}; - var Batcher, Events$3, parser$4; +inherits(ArchiveOutputStream, Transform); - parser$4 = parser; +ArchiveOutputStream.prototype._appendBuffer = function(zae, source, callback) { + // scaffold only +}; - Events$3 = Events_1; +ArchiveOutputStream.prototype._appendStream = function(zae, source, callback) { + // scaffold only +}; - Batcher = (function() { - class Batcher { - constructor(options = {}) { - this.options = options; - parser$4.load(this.options, this.defaults, this); - this.Events = new Events$3(this); - this._arr = []; - this._resetPromise(); - this._lastFlush = Date.now(); - } +ArchiveOutputStream.prototype._emitErrorCallback = function(err) { + if (err) { + this.emit('error', err); + } +}; - _resetPromise() { - return this._promise = new this.Promise((res, rej) => { - return this._resolve = res; - }); - } +ArchiveOutputStream.prototype._finish = function(ae) { + // scaffold only +}; - _flush() { - clearTimeout(this._timeout); - this._lastFlush = Date.now(); - this._resolve(); - this.Events.trigger("batch", this._arr); - this._arr = []; - return this._resetPromise(); - } +ArchiveOutputStream.prototype._normalizeEntry = function(ae) { + // scaffold only +}; - add(data) { - var ret; - this._arr.push(data); - ret = this._promise; - if (this._arr.length === this.maxSize) { - this._flush(); - } else if ((this.maxTime != null) && this._arr.length === 1) { - this._timeout = setTimeout(() => { - return this._flush(); - }, this.maxTime); - } - return ret; - } +ArchiveOutputStream.prototype._transform = function(chunk, encoding, callback) { + callback(null, chunk); +}; - } - Batcher.prototype.defaults = { - maxTime: null, - maxSize: null, - Promise: Promise - }; +ArchiveOutputStream.prototype.entry = function(ae, source, callback) { + source = source || null; - return Batcher; + if (typeof callback !== 'function') { + callback = this._emitErrorCallback.bind(this); + } - }).call(commonjsGlobal); + if (!(ae instanceof ArchiveEntry)) { + callback(new Error('not a valid instance of ArchiveEntry')); + return; + } - var Batcher_1 = Batcher; + if (this._archive.finish || this._archive.finished) { + callback(new Error('unacceptable entry after finish')); + return; + } - var require$$4$1 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); + if (this._archive.processing) { + callback(new Error('already processing an entry')); + return; + } - var require$$8 = getCjsExportFromNamespace(version$2); + this._archive.processing = true; + this._normalizeEntry(ae); + this._entry = ae; - var Bottleneck, DEFAULT_PRIORITY$1, Events$4, Job$1, LocalDatastore$1, NUM_PRIORITIES$1, Queues$1, RedisDatastore$1, States$1, Sync$1, parser$5, - splice = [].splice; + source = util.normalizeInputSource(source); - NUM_PRIORITIES$1 = 10; + if (Buffer.isBuffer(source)) { + this._appendBuffer(ae, source, callback); + } else if (util.isStream(source)) { + this._appendStream(ae, source, callback); + } else { + this._archive.processing = false; + callback(new Error('input source must be valid Stream or Buffer instance')); + return; + } - DEFAULT_PRIORITY$1 = 5; + return this; +}; - parser$5 = parser; +ArchiveOutputStream.prototype.finish = function() { + if (this._archive.processing) { + this._archive.finish = true; + return; + } - Queues$1 = Queues_1; + this._finish(); +}; - Job$1 = Job_1; +ArchiveOutputStream.prototype.getBytesWritten = function() { + return this.offset; +}; - LocalDatastore$1 = LocalDatastore_1; +ArchiveOutputStream.prototype.write = function(chunk, cb) { + if (chunk) { + this.offset += chunk.length; + } - RedisDatastore$1 = require$$4$1; + return Transform.prototype.write.call(this, chunk, cb); +}; - Events$4 = Events_1; +/***/ }), - States$1 = States_1; +/***/ 11704: +/***/ ((module) => { - Sync$1 = Sync_1; +/** + * node-compress-commons + * + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT + */ +module.exports = { + WORD: 4, + DWORD: 8, + EMPTY: Buffer.alloc(0), - Bottleneck = (function() { - class Bottleneck { - constructor(options = {}, ...invalid) { - var storeInstanceOptions, storeOptions; - this._addToQueue = this._addToQueue.bind(this); - this._validateOptions(options, invalid); - parser$5.load(options, this.instanceDefaults, this); - this._queues = new Queues$1(NUM_PRIORITIES$1); - this._scheduled = {}; - this._states = new States$1(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : [])); - this._limiter = null; - this.Events = new Events$4(this); - this._submitLock = new Sync$1("submit", this.Promise); - this._registerLock = new Sync$1("register", this.Promise); - storeOptions = parser$5.load(options, this.storeDefaults, {}); - this._store = (function() { - if (this.datastore === "redis" || this.datastore === "ioredis" || (this.connection != null)) { - storeInstanceOptions = parser$5.load(options, this.redisStoreDefaults, {}); - return new RedisDatastore$1(this, storeOptions, storeInstanceOptions); - } else if (this.datastore === "local") { - storeInstanceOptions = parser$5.load(options, this.localStoreDefaults, {}); - return new LocalDatastore$1(this, storeOptions, storeInstanceOptions); - } else { - throw new Bottleneck.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`); - } - }).call(this); - this._queues.on("leftzero", () => { - var ref; - return (ref = this._store.heartbeat) != null ? typeof ref.ref === "function" ? ref.ref() : void 0 : void 0; - }); - this._queues.on("zero", () => { - var ref; - return (ref = this._store.heartbeat) != null ? typeof ref.unref === "function" ? ref.unref() : void 0 : void 0; - }); - } - - _validateOptions(options, invalid) { - if (!((options != null) && typeof options === "object" && invalid.length === 0)) { - throw new Bottleneck.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1."); - } - } - - ready() { - return this._store.ready; - } + SHORT: 2, + SHORT_MASK: 0xffff, + SHORT_SHIFT: 16, + SHORT_ZERO: Buffer.from(Array(2)), + LONG: 4, + LONG_ZERO: Buffer.from(Array(4)), - clients() { - return this._store.clients; - } + MIN_VERSION_INITIAL: 10, + MIN_VERSION_DATA_DESCRIPTOR: 20, + MIN_VERSION_ZIP64: 45, + VERSION_MADEBY: 45, - channel() { - return `b_${this.id}`; - } + METHOD_STORED: 0, + METHOD_DEFLATED: 8, - channel_client() { - return `b_${this.id}_${this._store.clientId}`; - } + PLATFORM_UNIX: 3, + PLATFORM_FAT: 0, - publish(message) { - return this._store.__publish__(message); - } + SIG_LFH: 0x04034b50, + SIG_DD: 0x08074b50, + SIG_CFH: 0x02014b50, + SIG_EOCD: 0x06054b50, + SIG_ZIP64_EOCD: 0x06064B50, + SIG_ZIP64_EOCD_LOC: 0x07064B50, - disconnect(flush = true) { - return this._store.__disconnect__(flush); - } + ZIP64_MAGIC_SHORT: 0xffff, + ZIP64_MAGIC: 0xffffffff, + ZIP64_EXTRA_ID: 0x0001, - chain(_limiter) { - this._limiter = _limiter; - return this; - } + ZLIB_NO_COMPRESSION: 0, + ZLIB_BEST_SPEED: 1, + ZLIB_BEST_COMPRESSION: 9, + ZLIB_DEFAULT_COMPRESSION: -1, - queued(priority) { - return this._queues.queued(priority); - } + MODE_MASK: 0xFFF, + DEFAULT_FILE_MODE: 33188, // 010644 = -rw-r--r-- = S_IFREG | S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH + DEFAULT_DIR_MODE: 16877, // 040755 = drwxr-xr-x = S_IFDIR | S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH - clusterQueued() { - return this._store.__queued__(); - } + EXT_FILE_ATTR_DIR: 1106051088, // 010173200020 = drwxr-xr-x = (((S_IFDIR | 0755) << 16) | S_DOS_D) + EXT_FILE_ATTR_FILE: 2175008800, // 020151000040 = -rw-r--r-- = (((S_IFREG | 0644) << 16) | S_DOS_A) >>> 0 - empty() { - return this.queued() === 0 && this._submitLock.isEmpty(); - } + // Unix file types + S_IFMT: 61440, // 0170000 type of file mask + S_IFIFO: 4096, // 010000 named pipe (fifo) + S_IFCHR: 8192, // 020000 character special + S_IFDIR: 16384, // 040000 directory + S_IFBLK: 24576, // 060000 block special + S_IFREG: 32768, // 0100000 regular + S_IFLNK: 40960, // 0120000 symbolic link + S_IFSOCK: 49152, // 0140000 socket - running() { - return this._store.__running__(); - } + // DOS file type flags + S_DOS_A: 32, // 040 Archive + S_DOS_D: 16, // 020 Directory + S_DOS_V: 8, // 010 Volume + S_DOS_S: 4, // 04 System + S_DOS_H: 2, // 02 Hidden + S_DOS_R: 1 // 01 Read Only +}; - done() { - return this._store.__done__(); - } - jobStatus(id) { - return this._states.jobStatus(id); - } +/***/ }), - jobs(status) { - return this._states.statusJobs(status); - } +/***/ 63229: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - counts() { - return this._states.statusCounts(); - } +/** + * node-compress-commons + * + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT + */ +var zipUtil = __nccwpck_require__(68682); - _randomIndex() { - return Math.random().toString(36).slice(2); - } +var DATA_DESCRIPTOR_FLAG = 1 << 3; +var ENCRYPTION_FLAG = 1 << 0; +var NUMBER_OF_SHANNON_FANO_TREES_FLAG = 1 << 2; +var SLIDING_DICTIONARY_SIZE_FLAG = 1 << 1; +var STRONG_ENCRYPTION_FLAG = 1 << 6; +var UFT8_NAMES_FLAG = 1 << 11; - check(weight = 1) { - return this._store.__check__(weight); - } +var GeneralPurposeBit = module.exports = function() { + if (!(this instanceof GeneralPurposeBit)) { + return new GeneralPurposeBit(); + } - _clearGlobalState(index) { - if (this._scheduled[index] != null) { - clearTimeout(this._scheduled[index].expiration); - delete this._scheduled[index]; - return true; - } else { - return false; - } - } + this.descriptor = false; + this.encryption = false; + this.utf8 = false; + this.numberOfShannonFanoTrees = 0; + this.strongEncryption = false; + this.slidingDictionarySize = 0; - async _free(index, job, options, eventInfo) { - var e, running; - try { - ({running} = (await this._store.__free__(index, options.weight))); - this.Events.trigger("debug", `Freed ${options.id}`, eventInfo); - if (running === 0 && this.empty()) { - return this.Events.trigger("idle"); - } - } catch (error1) { - e = error1; - return this.Events.trigger("error", e); - } - } + return this; +}; - _run(index, job, wait) { - var clearGlobalState, free, run; - job.doRun(); - clearGlobalState = this._clearGlobalState.bind(this, index); - run = this._run.bind(this, index, job); - free = this._free.bind(this, index, job); - return this._scheduled[index] = { - timeout: setTimeout(() => { - return job.doExecute(this._limiter, clearGlobalState, run, free); - }, wait), - expiration: job.options.expiration != null ? setTimeout(function() { - return job.doExpire(clearGlobalState, run, free); - }, wait + job.options.expiration) : void 0, - job: job - }; - } +GeneralPurposeBit.prototype.encode = function() { + return zipUtil.getShortBytes( + (this.descriptor ? DATA_DESCRIPTOR_FLAG : 0) | + (this.utf8 ? UFT8_NAMES_FLAG : 0) | + (this.encryption ? ENCRYPTION_FLAG : 0) | + (this.strongEncryption ? STRONG_ENCRYPTION_FLAG : 0) + ); +}; - _drainOne(capacity) { - return this._registerLock.schedule(() => { - var args, index, next, options, queue; - if (this.queued() === 0) { - return this.Promise.resolve(null); - } - queue = this._queues.getFirst(); - ({options, args} = next = queue.first()); - if ((capacity != null) && options.weight > capacity) { - return this.Promise.resolve(null); - } - this.Events.trigger("debug", `Draining ${options.id}`, {args, options}); - index = this._randomIndex(); - return this._store.__register__(index, options.weight, options.expiration).then(({success, wait, reservoir}) => { - var empty; - this.Events.trigger("debug", `Drained ${options.id}`, {success, args, options}); - if (success) { - queue.shift(); - empty = this.empty(); - if (empty) { - this.Events.trigger("empty"); - } - if (reservoir === 0) { - this.Events.trigger("depleted", empty); - } - this._run(index, next, wait); - return this.Promise.resolve(options.weight); - } else { - return this.Promise.resolve(null); - } - }); - }); - } +GeneralPurposeBit.prototype.parse = function(buf, offset) { + var flag = zipUtil.getShortBytesValue(buf, offset); + var gbp = new GeneralPurposeBit(); - _drainAll(capacity, total = 0) { - return this._drainOne(capacity).then((drained) => { - var newCapacity; - if (drained != null) { - newCapacity = capacity != null ? capacity - drained : capacity; - return this._drainAll(newCapacity, total + drained); - } else { - return this.Promise.resolve(total); - } - }).catch((e) => { - return this.Events.trigger("error", e); - }); - } + gbp.useDataDescriptor((flag & DATA_DESCRIPTOR_FLAG) !== 0); + gbp.useUTF8ForNames((flag & UFT8_NAMES_FLAG) !== 0); + gbp.useStrongEncryption((flag & STRONG_ENCRYPTION_FLAG) !== 0); + gbp.useEncryption((flag & ENCRYPTION_FLAG) !== 0); + gbp.setSlidingDictionarySize((flag & SLIDING_DICTIONARY_SIZE_FLAG) !== 0 ? 8192 : 4096); + gbp.setNumberOfShannonFanoTrees((flag & NUMBER_OF_SHANNON_FANO_TREES_FLAG) !== 0 ? 3 : 2); - _dropAllQueued(message) { - return this._queues.shiftAll(function(job) { - return job.doDrop({message}); - }); - } + return gbp; +}; - stop(options = {}) { - var done, waitForExecuting; - options = parser$5.load(options, this.stopDefaults); - waitForExecuting = (at) => { - var finished; - finished = () => { - var counts; - counts = this._states.counts; - return (counts[0] + counts[1] + counts[2] + counts[3]) === at; - }; - return new this.Promise((resolve, reject) => { - if (finished()) { - return resolve(); - } else { - return this.on("done", () => { - if (finished()) { - this.removeAllListeners("done"); - return resolve(); - } - }); - } - }); - }; - done = options.dropWaitingJobs ? (this._run = function(index, next) { - return next.doDrop({ - message: options.dropErrorMessage - }); - }, this._drainOne = () => { - return this.Promise.resolve(null); - }, this._registerLock.schedule(() => { - return this._submitLock.schedule(() => { - var k, ref, v; - ref = this._scheduled; - for (k in ref) { - v = ref[k]; - if (this.jobStatus(v.job.options.id) === "RUNNING") { - clearTimeout(v.timeout); - clearTimeout(v.expiration); - v.job.doDrop({ - message: options.dropErrorMessage - }); - } - } - this._dropAllQueued(options.dropErrorMessage); - return waitForExecuting(0); - }); - })) : this.schedule({ - priority: NUM_PRIORITIES$1 - 1, - weight: 0 - }, () => { - return waitForExecuting(1); - }); - this._receive = function(job) { - return job._reject(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)); - }; - this.stop = () => { - return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called")); - }; - return done; - } +GeneralPurposeBit.prototype.setNumberOfShannonFanoTrees = function(n) { + this.numberOfShannonFanoTrees = n; +}; - async _addToQueue(job) { - var args, blocked, error, options, reachedHWM, shifted, strategy; - ({args, options} = job); - try { - ({reachedHWM, blocked, strategy} = (await this._store.__submit__(this.queued(), options.weight))); - } catch (error1) { - error = error1; - this.Events.trigger("debug", `Could not queue ${options.id}`, {args, options, error}); - job.doDrop({error}); - return false; - } - if (blocked) { - job.doDrop(); - return true; - } else if (reachedHWM) { - shifted = strategy === Bottleneck.prototype.strategy.LEAK ? this._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? this._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0; - if (shifted != null) { - shifted.doDrop(); - } - if ((shifted == null) || strategy === Bottleneck.prototype.strategy.OVERFLOW) { - if (shifted == null) { - job.doDrop(); - } - return reachedHWM; - } - } - job.doQueue(reachedHWM, blocked); - this._queues.push(job); - await this._drainAll(); - return reachedHWM; - } +GeneralPurposeBit.prototype.getNumberOfShannonFanoTrees = function() { + return this.numberOfShannonFanoTrees; +}; - _receive(job) { - if (this._states.jobStatus(job.options.id) != null) { - job._reject(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`)); - return false; - } else { - job.doReceive(); - return this._submitLock.schedule(this._addToQueue, job); - } - } +GeneralPurposeBit.prototype.setSlidingDictionarySize = function(n) { + this.slidingDictionarySize = n; +}; - submit(...args) { - var cb, fn, job, options, ref, ref1, task; - if (typeof args[0] === "function") { - ref = args, [fn, ...args] = ref, [cb] = splice.call(args, -1); - options = parser$5.load({}, this.jobDefaults); - } else { - ref1 = args, [options, fn, ...args] = ref1, [cb] = splice.call(args, -1); - options = parser$5.load(options, this.jobDefaults); - } - task = (...args) => { - return new this.Promise(function(resolve, reject) { - return fn(...args, function(...args) { - return (args[0] != null ? reject : resolve)(args); - }); - }); - }; - job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); - job.promise.then(function(args) { - return typeof cb === "function" ? cb(...args) : void 0; - }).catch(function(args) { - if (Array.isArray(args)) { - return typeof cb === "function" ? cb(...args) : void 0; - } else { - return typeof cb === "function" ? cb(args) : void 0; - } - }); - return this._receive(job); - } +GeneralPurposeBit.prototype.getSlidingDictionarySize = function() { + return this.slidingDictionarySize; +}; - schedule(...args) { - var job, options, task; - if (typeof args[0] === "function") { - [task, ...args] = args; - options = {}; - } else { - [options, task, ...args] = args; - } - job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); - this._receive(job); - return job.promise; - } +GeneralPurposeBit.prototype.useDataDescriptor = function(b) { + this.descriptor = b; +}; - wrap(fn) { - var schedule, wrapped; - schedule = this.schedule.bind(this); - wrapped = function(...args) { - return schedule(fn.bind(this), ...args); - }; - wrapped.withOptions = function(options, ...args) { - return schedule(options, fn, ...args); - }; - return wrapped; - } +GeneralPurposeBit.prototype.usesDataDescriptor = function() { + return this.descriptor; +}; - async updateSettings(options = {}) { - await this._store.__updateSettings__(parser$5.overwrite(options, this.storeDefaults)); - parser$5.overwrite(options, this.instanceDefaults, this); - return this; - } +GeneralPurposeBit.prototype.useEncryption = function(b) { + this.encryption = b; +}; - currentReservoir() { - return this._store.__currentReservoir__(); - } +GeneralPurposeBit.prototype.usesEncryption = function() { + return this.encryption; +}; - incrementReservoir(incr = 0) { - return this._store.__incrementReservoir__(incr); - } +GeneralPurposeBit.prototype.useStrongEncryption = function(b) { + this.strongEncryption = b; +}; - } - Bottleneck.default = Bottleneck; +GeneralPurposeBit.prototype.usesStrongEncryption = function() { + return this.strongEncryption; +}; - Bottleneck.Events = Events$4; +GeneralPurposeBit.prototype.useUTF8ForNames = function(b) { + this.utf8 = b; +}; - Bottleneck.version = Bottleneck.prototype.version = require$$8.version; +GeneralPurposeBit.prototype.usesUTF8ForNames = function() { + return this.utf8; +}; - Bottleneck.strategy = Bottleneck.prototype.strategy = { - LEAK: 1, - OVERFLOW: 2, - OVERFLOW_PRIORITY: 4, - BLOCK: 3 - }; +/***/ }), - Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = BottleneckError_1; +/***/ 70713: +/***/ ((module) => { - Bottleneck.Group = Bottleneck.prototype.Group = Group_1; +/** + * node-compress-commons + * + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT + */ +module.exports = { + /** + * Bits used for permissions (and sticky bit) + */ + PERM_MASK: 4095, // 07777 - Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = require$$2; + /** + * Bits used to indicate the filesystem object type. + */ + FILE_TYPE_FLAG: 61440, // 0170000 - Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = require$$3; + /** + * Indicates symbolic links. + */ + LINK_FLAG: 40960, // 0120000 - Bottleneck.Batcher = Bottleneck.prototype.Batcher = Batcher_1; + /** + * Indicates plain files. + */ + FILE_FLAG: 32768, // 0100000 - Bottleneck.prototype.jobDefaults = { - priority: DEFAULT_PRIORITY$1, - weight: 1, - expiration: null, - id: "" - }; + /** + * Indicates directories. + */ + DIR_FLAG: 16384, // 040000 - Bottleneck.prototype.storeDefaults = { - maxConcurrent: null, - minTime: 0, - highWater: null, - strategy: Bottleneck.prototype.strategy.LEAK, - penalty: null, - reservoir: null, - reservoirRefreshInterval: null, - reservoirRefreshAmount: null, - reservoirIncreaseInterval: null, - reservoirIncreaseAmount: null, - reservoirIncreaseMaximum: null - }; + // ---------------------------------------------------------- + // somewhat arbitrary choices that are quite common for shared + // installations + // ----------------------------------------------------------- - Bottleneck.prototype.localStoreDefaults = { - Promise: Promise, - timeout: null, - heartbeatInterval: 250 - }; + /** + * Default permissions for symbolic links. + */ + DEFAULT_LINK_PERM: 511, // 0777 - Bottleneck.prototype.redisStoreDefaults = { - Promise: Promise, - timeout: null, - heartbeatInterval: 5000, - clientTimeout: 10000, - Redis: null, - clientOptions: {}, - clusterNodes: null, - clearDatastore: false, - connection: null - }; + /** + * Default permissions for directories. + */ + DEFAULT_DIR_PERM: 493, // 0755 - Bottleneck.prototype.instanceDefaults = { - datastore: "local", - connection: null, - id: "", - rejectOnDrop: true, - trackDoneStatus: false, - Promise: Promise - }; + /** + * Default permissions for plain files. + */ + DEFAULT_FILE_PERM: 420 // 0644 +}; - Bottleneck.prototype.stopDefaults = { - enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", - dropWaitingJobs: true, - dropErrorMessage: "This limiter has been stopped." - }; +/***/ }), - return Bottleneck; +/***/ 68682: +/***/ ((module) => { - }).call(commonjsGlobal); +/** + * node-compress-commons + * + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT + */ +var util = module.exports = {}; - var Bottleneck_1 = Bottleneck; +util.dateToDos = function(d, forceLocalTime) { + forceLocalTime = forceLocalTime || false; - var lib = Bottleneck_1; + var year = forceLocalTime ? d.getFullYear() : d.getUTCFullYear(); - return lib; + if (year < 1980) { + return 2162688; // 1980-1-1 00:00:00 + } else if (year >= 2044) { + return 2141175677; // 2043-12-31 23:59:58 + } -}))); + var val = { + year: year, + month: forceLocalTime ? d.getMonth() : d.getUTCMonth(), + date: forceLocalTime ? d.getDate() : d.getUTCDate(), + hours: forceLocalTime ? d.getHours() : d.getUTCHours(), + minutes: forceLocalTime ? d.getMinutes() : d.getUTCMinutes(), + seconds: forceLocalTime ? d.getSeconds() : d.getUTCSeconds() + }; + return ((val.year - 1980) << 25) | ((val.month + 1) << 21) | (val.date << 16) | + (val.hours << 11) | (val.minutes << 5) | (val.seconds / 2); +}; -/***/ }), +util.dosToDate = function(dos) { + return new Date(((dos >> 25) & 0x7f) + 1980, ((dos >> 21) & 0x0f) - 1, (dos >> 16) & 0x1f, (dos >> 11) & 0x1f, (dos >> 5) & 0x3f, (dos & 0x1f) << 1); +}; -/***/ 84859: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +util.fromDosTime = function(buf) { + return util.dosToDate(buf.readUInt32LE(0)); +}; -var concatMap = __nccwpck_require__(42360); -var balanced = __nccwpck_require__(89948); +util.getEightBytes = function(v) { + var buf = Buffer.alloc(8); + buf.writeUInt32LE(v % 0x0100000000, 0); + buf.writeUInt32LE((v / 0x0100000000) | 0, 4); -module.exports = expandTop; + return buf; +}; -var escSlash = '\0SLASH'+Math.random()+'\0'; -var escOpen = '\0OPEN'+Math.random()+'\0'; -var escClose = '\0CLOSE'+Math.random()+'\0'; -var escComma = '\0COMMA'+Math.random()+'\0'; -var escPeriod = '\0PERIOD'+Math.random()+'\0'; +util.getShortBytes = function(v) { + var buf = Buffer.alloc(2); + buf.writeUInt16LE((v & 0xFFFF) >>> 0, 0); -function numeric(str) { - return parseInt(str, 10) == str - ? parseInt(str, 10) - : str.charCodeAt(0); -} + return buf; +}; -function escapeBraces(str) { - return str.split('\\\\').join(escSlash) - .split('\\{').join(escOpen) - .split('\\}').join(escClose) - .split('\\,').join(escComma) - .split('\\.').join(escPeriod); -} +util.getShortBytesValue = function(buf, offset) { + return buf.readUInt16LE(offset); +}; -function unescapeBraces(str) { - return str.split(escSlash).join('\\') - .split(escOpen).join('{') - .split(escClose).join('}') - .split(escComma).join(',') - .split(escPeriod).join('.'); -} +util.getLongBytes = function(v) { + var buf = Buffer.alloc(4); + buf.writeUInt32LE((v & 0xFFFFFFFF) >>> 0, 0); + return buf; +}; -// Basically just str.split(","), but handling cases -// where we have nested braced sections, which should be -// treated as individual members, like {a,{b,c},d} -function parseCommaParts(str) { - if (!str) - return ['']; +util.getLongBytesValue = function(buf, offset) { + return buf.readUInt32LE(offset); +}; - var parts = []; - var m = balanced('{', '}', str); +util.toDosTime = function(d) { + return util.getLongBytes(util.dateToDos(d)); +}; - if (!m) - return str.split(','); +/***/ }), - var pre = m.pre; - var body = m.body; - var post = m.post; - var p = pre.split(','); +/***/ 3179: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - p[p.length-1] += '{' + body + '}'; - var postParts = parseCommaParts(post); - if (post.length) { - p[p.length-1] += postParts.shift(); - p.push.apply(p, postParts); +/** + * node-compress-commons + * + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT + */ +var inherits = (__nccwpck_require__(73837).inherits); +var normalizePath = __nccwpck_require__(55388); + +var ArchiveEntry = __nccwpck_require__(92240); +var GeneralPurposeBit = __nccwpck_require__(63229); +var UnixStat = __nccwpck_require__(70713); + +var constants = __nccwpck_require__(11704); +var zipUtil = __nccwpck_require__(68682); + +var ZipArchiveEntry = module.exports = function(name) { + if (!(this instanceof ZipArchiveEntry)) { + return new ZipArchiveEntry(name); } - parts.push.apply(parts, p); + ArchiveEntry.call(this); - return parts; -} + this.platform = constants.PLATFORM_FAT; + this.method = -1; -function expandTop(str) { - if (!str) - return []; + this.name = null; + this.size = 0; + this.csize = 0; + this.gpb = new GeneralPurposeBit(); + this.crc = 0; + this.time = -1; - // I don't know why Bash 4.3 does this, but it does. - // Anything starting with {} will have the first two bytes preserved - // but *only* at the top level, so {},a}b will not expand to anything, - // but a{},b}c will be expanded to [a}c,abc]. - // One could argue that this is a bug in Bash, but since the goal of - // this module is to match Bash's rules, we escape a leading {} - if (str.substr(0, 2) === '{}') { - str = '\\{\\}' + str.substr(2); + this.minver = constants.MIN_VERSION_INITIAL; + this.mode = -1; + this.extra = null; + this.exattr = 0; + this.inattr = 0; + this.comment = null; + + if (name) { + this.setName(name); } +}; - return expand(escapeBraces(str), true).map(unescapeBraces); -} +inherits(ZipArchiveEntry, ArchiveEntry); -function identity(e) { - return e; -} +/** + * Returns the extra fields related to the entry. + * + * @returns {Buffer} + */ +ZipArchiveEntry.prototype.getCentralDirectoryExtra = function() { + return this.getExtra(); +}; -function embrace(str) { - return '{' + str + '}'; -} -function isPadded(el) { - return /^-?0\d/.test(el); -} +/** + * Returns the comment set for the entry. + * + * @returns {string} + */ +ZipArchiveEntry.prototype.getComment = function() { + return this.comment !== null ? this.comment : ''; +}; -function lte(i, y) { - return i <= y; -} -function gte(i, y) { - return i >= y; -} +/** + * Returns the compressed size of the entry. + * + * @returns {number} + */ +ZipArchiveEntry.prototype.getCompressedSize = function() { + return this.csize; +}; -function expand(str, isTop) { - var expansions = []; +/** + * Returns the CRC32 digest for the entry. + * + * @returns {number} + */ +ZipArchiveEntry.prototype.getCrc = function() { + return this.crc; +}; - var m = balanced('{', '}', str); - if (!m || /\$$/.test(m.pre)) return [str]; +/** + * Returns the external file attributes for the entry. + * + * @returns {number} + */ +ZipArchiveEntry.prototype.getExternalAttributes = function() { + return this.exattr; +}; - var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); - var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); - var isSequence = isNumericSequence || isAlphaSequence; - var isOptions = m.body.indexOf(',') >= 0; - if (!isSequence && !isOptions) { - // {a},b} - if (m.post.match(/,.*\}/)) { - str = m.pre + '{' + m.body + escClose + m.post; - return expand(str); - } - return [str]; - } +/** + * Returns the extra fields related to the entry. + * + * @returns {Buffer} + */ +ZipArchiveEntry.prototype.getExtra = function() { + return this.extra !== null ? this.extra : constants.EMPTY; +}; - var n; - if (isSequence) { - n = m.body.split(/\.\./); - } else { - n = parseCommaParts(m.body); - if (n.length === 1) { - // x{{a,b}}y ==> x{a}y x{b}y - n = expand(n[0], false).map(embrace); - if (n.length === 1) { - var post = m.post.length - ? expand(m.post, false) - : ['']; - return post.map(function(p) { - return m.pre + n[0] + p; - }); - } - } - } +/** + * Returns the general purpose bits related to the entry. + * + * @returns {GeneralPurposeBit} + */ +ZipArchiveEntry.prototype.getGeneralPurposeBit = function() { + return this.gpb; +}; - // at this point, n is the parts, and we know it's not a comma set - // with a single entry. +/** + * Returns the internal file attributes for the entry. + * + * @returns {number} + */ +ZipArchiveEntry.prototype.getInternalAttributes = function() { + return this.inattr; +}; - // no need to expand pre, since it is guaranteed to be free of brace-sets - var pre = m.pre; - var post = m.post.length - ? expand(m.post, false) - : ['']; +/** + * Returns the last modified date of the entry. + * + * @returns {number} + */ +ZipArchiveEntry.prototype.getLastModifiedDate = function() { + return this.getTime(); +}; - var N; +/** + * Returns the extra fields related to the entry. + * + * @returns {Buffer} + */ +ZipArchiveEntry.prototype.getLocalFileDataExtra = function() { + return this.getExtra(); +}; - if (isSequence) { - var x = numeric(n[0]); - var y = numeric(n[1]); - var width = Math.max(n[0].length, n[1].length) - var incr = n.length == 3 - ? Math.abs(numeric(n[2])) - : 1; - var test = lte; - var reverse = y < x; - if (reverse) { - incr *= -1; - test = gte; - } - var pad = n.some(isPadded); +/** + * Returns the compression method used on the entry. + * + * @returns {number} + */ +ZipArchiveEntry.prototype.getMethod = function() { + return this.method; +}; - N = []; +/** + * Returns the filename of the entry. + * + * @returns {string} + */ +ZipArchiveEntry.prototype.getName = function() { + return this.name; +}; - for (var i = x; test(i, y); i += incr) { - var c; - if (isAlphaSequence) { - c = String.fromCharCode(i); - if (c === '\\') - c = ''; - } else { - c = String(i); - if (pad) { - var need = width - c.length; - if (need > 0) { - var z = new Array(need + 1).join('0'); - if (i < 0) - c = '-' + z + c.slice(1); - else - c = z + c; - } - } - } - N.push(c); - } - } else { - N = concatMap(n, function(el) { return expand(el, false) }); - } +/** + * Returns the platform on which the entry was made. + * + * @returns {number} + */ +ZipArchiveEntry.prototype.getPlatform = function() { + return this.platform; +}; - for (var j = 0; j < N.length; j++) { - for (var k = 0; k < post.length; k++) { - var expansion = pre + N[j] + post[k]; - if (!isTop || isSequence || expansion) - expansions.push(expansion); - } - } +/** + * Returns the size of the entry. + * + * @returns {number} + */ +ZipArchiveEntry.prototype.getSize = function() { + return this.size; +}; - return expansions; -} +/** + * Returns a date object representing the last modified date of the entry. + * + * @returns {number|Date} + */ +ZipArchiveEntry.prototype.getTime = function() { + return this.time !== -1 ? zipUtil.dosToDate(this.time) : -1; +}; +/** + * Returns the DOS timestamp for the entry. + * + * @returns {number} + */ +ZipArchiveEntry.prototype.getTimeDos = function() { + return this.time !== -1 ? this.time : 0; +}; +/** + * Returns the UNIX file permissions for the entry. + * + * @returns {number} + */ +ZipArchiveEntry.prototype.getUnixMode = function() { + return this.platform !== constants.PLATFORM_UNIX ? 0 : ((this.getExternalAttributes() >> constants.SHORT_SHIFT) & constants.SHORT_MASK); +}; -/***/ }), +/** + * Returns the version of ZIP needed to extract the entry. + * + * @returns {number} + */ +ZipArchiveEntry.prototype.getVersionNeededToExtract = function() { + return this.minver; +}; -/***/ 6075: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Sets the comment of the entry. + * + * @param comment + */ +ZipArchiveEntry.prototype.setComment = function(comment) { + if (Buffer.byteLength(comment) !== comment.length) { + this.getGeneralPurposeBit().useUTF8ForNames(true); + } -var Buffer = (__nccwpck_require__(14300).Buffer); + this.comment = comment; +}; -var CRC_TABLE = [ - 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, - 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, - 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, - 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, - 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, - 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, - 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, - 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, - 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, - 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, - 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, - 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, - 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, - 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, - 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, - 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, - 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, - 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, - 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, - 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, - 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, - 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, - 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, - 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, - 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, - 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, - 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, - 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, - 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, - 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, - 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, - 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, - 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, - 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, - 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, - 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, - 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, - 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, - 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, - 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, - 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, - 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, - 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, - 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, - 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, - 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, - 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, - 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, - 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, - 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, - 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, - 0x2d02ef8d -]; +/** + * Sets the compressed size of the entry. + * + * @param size + */ +ZipArchiveEntry.prototype.setCompressedSize = function(size) { + if (size < 0) { + throw new Error('invalid entry compressed size'); + } -if (typeof Int32Array !== 'undefined') { - CRC_TABLE = new Int32Array(CRC_TABLE); -} + this.csize = size; +}; -function ensureBuffer(input) { - if (Buffer.isBuffer(input)) { - return input; +/** + * Sets the checksum of the entry. + * + * @param crc + */ +ZipArchiveEntry.prototype.setCrc = function(crc) { + if (crc < 0) { + throw new Error('invalid entry crc32'); } - var hasNewBufferAPI = - typeof Buffer.alloc === "function" && - typeof Buffer.from === "function"; + this.crc = crc; +}; - if (typeof input === "number") { - return hasNewBufferAPI ? Buffer.alloc(input) : new Buffer(input); +/** + * Sets the external file attributes of the entry. + * + * @param attr + */ +ZipArchiveEntry.prototype.setExternalAttributes = function(attr) { + this.exattr = attr >>> 0; +}; + +/** + * Sets the extra fields related to the entry. + * + * @param extra + */ +ZipArchiveEntry.prototype.setExtra = function(extra) { + this.extra = extra; +}; + +/** + * Sets the general purpose bits related to the entry. + * + * @param gpb + */ +ZipArchiveEntry.prototype.setGeneralPurposeBit = function(gpb) { + if (!(gpb instanceof GeneralPurposeBit)) { + throw new Error('invalid entry GeneralPurposeBit'); } - else if (typeof input === "string") { - return hasNewBufferAPI ? Buffer.from(input) : new Buffer(input); + + this.gpb = gpb; +}; + +/** + * Sets the internal file attributes of the entry. + * + * @param attr + */ +ZipArchiveEntry.prototype.setInternalAttributes = function(attr) { + this.inattr = attr; +}; + +/** + * Sets the compression method of the entry. + * + * @param method + */ +ZipArchiveEntry.prototype.setMethod = function(method) { + if (method < 0) { + throw new Error('invalid entry compression method'); } - else { - throw new Error("input must be buffer, number, or string, received " + - typeof input); + + this.method = method; +}; + +/** + * Sets the name of the entry. + * + * @param name + * @param prependSlash + */ +ZipArchiveEntry.prototype.setName = function(name, prependSlash = false) { + name = normalizePath(name, false) + .replace(/^\w+:/, '') + .replace(/^(\.\.\/|\/)+/, ''); + + if (prependSlash) { + name = `/${name}`; } -} -function bufferizeInt(num) { - var tmp = ensureBuffer(4); - tmp.writeInt32BE(num, 0); - return tmp; -} + if (Buffer.byteLength(name) !== name.length) { + this.getGeneralPurposeBit().useUTF8ForNames(true); + } -function _crc32(buf, previous) { - buf = ensureBuffer(buf); - if (Buffer.isBuffer(previous)) { - previous = previous.readUInt32BE(0); + this.name = name; +}; + +/** + * Sets the platform on which the entry was made. + * + * @param platform + */ +ZipArchiveEntry.prototype.setPlatform = function(platform) { + this.platform = platform; +}; + +/** + * Sets the size of the entry. + * + * @param size + */ +ZipArchiveEntry.prototype.setSize = function(size) { + if (size < 0) { + throw new Error('invalid entry size'); } - var crc = ~~previous ^ -1; - for (var n = 0; n < buf.length; n++) { - crc = CRC_TABLE[(crc ^ buf[n]) & 0xff] ^ (crc >>> 8); + + this.size = size; +}; + +/** + * Sets the time of the entry. + * + * @param time + * @param forceLocalTime + */ +ZipArchiveEntry.prototype.setTime = function(time, forceLocalTime) { + if (!(time instanceof Date)) { + throw new Error('invalid entry time'); } - return (crc ^ -1); -} -function crc32() { - return bufferizeInt(_crc32.apply(null, arguments)); -} -crc32.signed = function () { - return _crc32.apply(null, arguments); + this.time = zipUtil.dateToDos(time, forceLocalTime); }; -crc32.unsigned = function () { - return _crc32.apply(null, arguments) >>> 0; + +/** + * Sets the UNIX file permissions for the entry. + * + * @param mode + */ +ZipArchiveEntry.prototype.setUnixMode = function(mode) { + mode |= this.isDirectory() ? constants.S_IFDIR : constants.S_IFREG; + + var extattr = 0; + extattr |= (mode << constants.SHORT_SHIFT) | (this.isDirectory() ? constants.S_DOS_D : constants.S_DOS_A); + + this.setExternalAttributes(extattr); + this.mode = mode & constants.MODE_MASK; + this.platform = constants.PLATFORM_UNIX; }; -module.exports = crc32; +/** + * Sets the version of ZIP needed to extract this entry. + * + * @param minver + */ +ZipArchiveEntry.prototype.setVersionNeededToExtract = function(minver) { + this.minver = minver; +}; + +/** + * Returns true if this entry represents a directory. + * + * @returns {boolean} + */ +ZipArchiveEntry.prototype.isDirectory = function() { + return this.getName().slice(-1) === '/'; +}; + +/** + * Returns true if this entry represents a unix symlink, + * in which case the entry's content contains the target path + * for the symlink. + * + * @returns {boolean} + */ +ZipArchiveEntry.prototype.isUnixSymlink = function() { + return (this.getUnixMode() & UnixStat.FILE_TYPE_FLAG) === UnixStat.LINK_FLAG; +}; + +/** + * Returns true if this entry is using the ZIP64 extension of ZIP. + * + * @returns {boolean} + */ +ZipArchiveEntry.prototype.isZip64 = function() { + return this.csize > constants.ZIP64_MAGIC || this.size > constants.ZIP64_MAGIC; +}; /***/ }), -/***/ 91361: -/***/ ((__unused_webpack_module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 44432: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +/** + * node-compress-commons + * + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT + */ +var inherits = (__nccwpck_require__(73837).inherits); +var crc32 = __nccwpck_require__(84794); +var {CRC32Stream} = __nccwpck_require__(5101); +var {DeflateCRC32Stream} = __nccwpck_require__(5101); -var initBuffer = __nccwpck_require__(9405); +var ArchiveOutputStream = __nccwpck_require__(36728); +var ZipArchiveEntry = __nccwpck_require__(3179); +var GeneralPurposeBit = __nccwpck_require__(63229); -if (!Buffer.prototype.indexOf) { - Buffer.prototype.indexOf = function (value, offset) { - offset = offset || 0; +var constants = __nccwpck_require__(11704); +var util = __nccwpck_require__(95208); +var zipUtil = __nccwpck_require__(68682); - // Always wrap the input as a Buffer so that this method will support any - // data type such as array octet, string or buffer. - if (typeof value === "string" || value instanceof String) { - value = initBuffer(value); - } else if (typeof value === "number" || value instanceof Number) { - value = initBuffer([ value ]); - } +var ZipArchiveOutputStream = module.exports = function(options) { + if (!(this instanceof ZipArchiveOutputStream)) { + return new ZipArchiveOutputStream(options); + } - var len = value.length; + options = this.options = this._defaults(options); - for (var i = offset; i <= this.length - len; i++) { - var mismatch = false; - for (var j = 0; j < len; j++) { - if (this[i + j] != value[j]) { - mismatch = true; - break; - } - } + ArchiveOutputStream.call(this, options); - if (!mismatch) { - return i; - } - } + this._entry = null; + this._entries = []; + this._archive = { + centralLength: 0, + centralOffset: 0, + comment: '', + finish: false, + finished: false, + processing: false, + forceZip64: options.forceZip64, + forceLocalTime: options.forceLocalTime + }; +}; - return -1; - }; -} +inherits(ZipArchiveOutputStream, ArchiveOutputStream); -function bufferLastIndexOf (value, offset) { +ZipArchiveOutputStream.prototype._afterAppend = function(ae) { + this._entries.push(ae); - // Always wrap the input as a Buffer so that this method will support any - // data type such as array octet, string or buffer. - if (typeof value === "string" || value instanceof String) { - value = initBuffer(value); - } else if (typeof value === "number" || value instanceof Number) { - value = initBuffer([ value ]); - } + if (ae.getGeneralPurposeBit().usesDataDescriptor()) { + this._writeDataDescriptor(ae); + } - var len = value.length; - offset = offset || this.length - len; + this._archive.processing = false; + this._entry = null; - for (var i = offset; i >= 0; i--) { - var mismatch = false; - for (var j = 0; j < len; j++) { - if (this[i + j] != value[j]) { - mismatch = true; - break; - } - } + if (this._archive.finish && !this._archive.finished) { + this._finish(); + } +}; - if (!mismatch) { - return i; - } - } +ZipArchiveOutputStream.prototype._appendBuffer = function(ae, source, callback) { + if (source.length === 0) { + ae.setMethod(constants.METHOD_STORED); + } - return -1; -} + var method = ae.getMethod(); + if (method === constants.METHOD_STORED) { + ae.setSize(source.length); + ae.setCompressedSize(source.length); + ae.setCrc(crc32.unsigned(source)); + } -if (Buffer.prototype.lastIndexOf) { - // check Buffer#lastIndexOf is usable: https://github.com/nodejs/node/issues/4604 - if (initBuffer("ABC").lastIndexOf ("ABC") === -1) - Buffer.prototype.lastIndexOf = bufferLastIndexOf; -} else { - Buffer.prototype.lastIndexOf = bufferLastIndexOf; -} + this._writeLocalFileHeader(ae); + if (method === constants.METHOD_STORED) { + this.write(source); + this._afterAppend(ae); + callback(null, ae); + return; + } else if (method === constants.METHOD_DEFLATED) { + this._smartStream(ae, callback).end(source); + return; + } else { + callback(new Error('compression method ' + method + ' not implemented')); + return; + } +}; -/***/ }), +ZipArchiveOutputStream.prototype._appendStream = function(ae, source, callback) { + ae.getGeneralPurposeBit().useDataDescriptor(true); + ae.setVersionNeededToExtract(constants.MIN_VERSION_DATA_DESCRIPTOR); -/***/ 9405: -/***/ ((module) => { + this._writeLocalFileHeader(ae); -module.exports = function initBuffer(val) { - // assume old version - var nodeVersion = process && process.version ? process.version : "v5.0.0"; - var major = nodeVersion.split(".")[0].replace("v", ""); - return major < 6 - ? new Buffer(val) - : Buffer.from(val); + var smart = this._smartStream(ae, callback); + source.once('error', function(err) { + smart.emit('error', err); + smart.end(); + }) + source.pipe(smart); }; -/***/ }), +ZipArchiveOutputStream.prototype._defaults = function(o) { + if (typeof o !== 'object') { + o = {}; + } -/***/ 53913: -/***/ ((module) => { + if (typeof o.zlib !== 'object') { + o.zlib = {}; + } -module.exports = Buffers; + if (typeof o.zlib.level !== 'number') { + o.zlib.level = constants.ZLIB_BEST_SPEED; + } -function Buffers (bufs) { - if (!(this instanceof Buffers)) return new Buffers(bufs); - this.buffers = bufs || []; - this.length = this.buffers.reduce(function (size, buf) { - return size + buf.length - }, 0); -} + o.forceZip64 = !!o.forceZip64; + o.forceLocalTime = !!o.forceLocalTime; -Buffers.prototype.push = function () { - for (var i = 0; i < arguments.length; i++) { - if (!Buffer.isBuffer(arguments[i])) { - throw new TypeError('Tried to push a non-buffer'); - } - } - - for (var i = 0; i < arguments.length; i++) { - var buf = arguments[i]; - this.buffers.push(buf); - this.length += buf.length; - } - return this.length; + return o; }; -Buffers.prototype.unshift = function () { - for (var i = 0; i < arguments.length; i++) { - if (!Buffer.isBuffer(arguments[i])) { - throw new TypeError('Tried to unshift a non-buffer'); - } - } - - for (var i = 0; i < arguments.length; i++) { - var buf = arguments[i]; - this.buffers.unshift(buf); - this.length += buf.length; - } - return this.length; +ZipArchiveOutputStream.prototype._finish = function() { + this._archive.centralOffset = this.offset; + + this._entries.forEach(function(ae) { + this._writeCentralFileHeader(ae); + }.bind(this)); + + this._archive.centralLength = this.offset - this._archive.centralOffset; + + if (this.isZip64()) { + this._writeCentralDirectoryZip64(); + } + + this._writeCentralDirectoryEnd(); + + this._archive.processing = false; + this._archive.finish = true; + this._archive.finished = true; + this.end(); }; -Buffers.prototype.copy = function (dst, dStart, start, end) { - return this.slice(start, end).copy(dst, dStart, 0, end - start); +ZipArchiveOutputStream.prototype._normalizeEntry = function(ae) { + if (ae.getMethod() === -1) { + ae.setMethod(constants.METHOD_DEFLATED); + } + + if (ae.getMethod() === constants.METHOD_DEFLATED) { + ae.getGeneralPurposeBit().useDataDescriptor(true); + ae.setVersionNeededToExtract(constants.MIN_VERSION_DATA_DESCRIPTOR); + } + + if (ae.getTime() === -1) { + ae.setTime(new Date(), this._archive.forceLocalTime); + } + + ae._offsets = { + file: 0, + data: 0, + contents: 0, + }; }; -Buffers.prototype.splice = function (i, howMany) { - var buffers = this.buffers; - var index = i >= 0 ? i : this.length - i; - var reps = [].slice.call(arguments, 2); - - if (howMany === undefined) { - howMany = this.length - index; - } - else if (howMany > this.length - index) { - howMany = this.length - index; - } - - for (var i = 0; i < reps.length; i++) { - this.length += reps[i].length; - } - - var removed = new Buffers(); - var bytes = 0; - - var startBytes = 0; - for ( - var ii = 0; - ii < buffers.length && startBytes + buffers[ii].length < index; - ii ++ - ) { startBytes += buffers[ii].length } - - if (index - startBytes > 0) { - var start = index - startBytes; - - if (start + howMany < buffers[ii].length) { - removed.push(buffers[ii].slice(start, start + howMany)); - - var orig = buffers[ii]; - //var buf = new Buffer(orig.length - howMany); - var buf0 = new Buffer(start); - for (var i = 0; i < start; i++) { - buf0[i] = orig[i]; - } - - var buf1 = new Buffer(orig.length - start - howMany); - for (var i = start + howMany; i < orig.length; i++) { - buf1[ i - howMany - start ] = orig[i] - } - - if (reps.length > 0) { - var reps_ = reps.slice(); - reps_.unshift(buf0); - reps_.push(buf1); - buffers.splice.apply(buffers, [ ii, 1 ].concat(reps_)); - ii += reps_.length; - reps = []; - } - else { - buffers.splice(ii, 1, buf0, buf1); - //buffers[ii] = buf; - ii += 2; - } - } - else { - removed.push(buffers[ii].slice(start)); - buffers[ii] = buffers[ii].slice(0, start); - ii ++; - } - } - - if (reps.length > 0) { - buffers.splice.apply(buffers, [ ii, 0 ].concat(reps)); - ii += reps.length; - } - - while (removed.length < howMany) { - var buf = buffers[ii]; - var len = buf.length; - var take = Math.min(len, howMany - removed.length); - - if (take === len) { - removed.push(buf); - buffers.splice(ii, 1); - } - else { - removed.push(buf.slice(0, take)); - buffers[ii] = buffers[ii].slice(take); - } - } - - this.length -= removed.length; - - return removed; -}; - -Buffers.prototype.slice = function (i, j) { - var buffers = this.buffers; - if (j === undefined) j = this.length; - if (i === undefined) i = 0; - - if (j > this.length) j = this.length; - - var startBytes = 0; - for ( - var si = 0; - si < buffers.length && startBytes + buffers[si].length <= i; - si ++ - ) { startBytes += buffers[si].length } - - var target = new Buffer(j - i); - - var ti = 0; - for (var ii = si; ti < j - i && ii < buffers.length; ii++) { - var len = buffers[ii].length; - - var start = ti === 0 ? i - startBytes : 0; - var end = ti + len >= j - i - ? Math.min(start + (j - i) - ti, len) - : len - ; - - buffers[ii].copy(target, ti, start, end); - ti += end - start; - } - - return target; -}; +ZipArchiveOutputStream.prototype._smartStream = function(ae, callback) { + var deflate = ae.getMethod() === constants.METHOD_DEFLATED; + var process = deflate ? new DeflateCRC32Stream(this.options.zlib) : new CRC32Stream(); + var error = null; -Buffers.prototype.pos = function (i) { - if (i < 0 || i >= this.length) throw new Error('oob'); - var l = i, bi = 0, bu = null; - for (;;) { - bu = this.buffers[bi]; - if (l < bu.length) { - return {buf: bi, offset: l}; - } else { - l -= bu.length; - } - bi++; - } -}; + function handleStuff() { + var digest = process.digest().readUInt32BE(0); + ae.setCrc(digest); + ae.setSize(process.size()); + ae.setCompressedSize(process.size(true)); + this._afterAppend(ae); + callback(error, ae); + } -Buffers.prototype.get = function get (i) { - var pos = this.pos(i); + process.once('end', handleStuff.bind(this)); + process.once('error', function(err) { + error = err; + }); - return this.buffers[pos.buf].get(pos.offset); + process.pipe(this, { end: false }); + + return process; }; -Buffers.prototype.set = function set (i, b) { - var pos = this.pos(i); +ZipArchiveOutputStream.prototype._writeCentralDirectoryEnd = function() { + var records = this._entries.length; + var size = this._archive.centralLength; + var offset = this._archive.centralOffset; - return this.buffers[pos.buf].set(pos.offset, b); -}; + if (this.isZip64()) { + records = constants.ZIP64_MAGIC_SHORT; + size = constants.ZIP64_MAGIC; + offset = constants.ZIP64_MAGIC; + } -Buffers.prototype.indexOf = function (needle, offset) { - if ("string" === typeof needle) { - needle = new Buffer(needle); - } else if (needle instanceof Buffer) { - // already a buffer - } else { - throw new Error('Invalid type for a search string'); - } + // signature + this.write(zipUtil.getLongBytes(constants.SIG_EOCD)); - if (!needle.length) { - return 0; - } + // disk numbers + this.write(constants.SHORT_ZERO); + this.write(constants.SHORT_ZERO); - if (!this.length) { - return -1; - } + // number of entries + this.write(zipUtil.getShortBytes(records)); + this.write(zipUtil.getShortBytes(records)); - var i = 0, j = 0, match = 0, mstart, pos = 0; + // length and location of CD + this.write(zipUtil.getLongBytes(size)); + this.write(zipUtil.getLongBytes(offset)); - // start search from a particular point in the virtual buffer - if (offset) { - var p = this.pos(offset); - i = p.buf; - j = p.offset; - pos = offset; - } + // archive comment + var comment = this.getComment(); + var commentLength = Buffer.byteLength(comment); + this.write(zipUtil.getShortBytes(commentLength)); + this.write(comment); +}; - // for each character in virtual buffer - for (;;) { - while (j >= this.buffers[i].length) { - j = 0; - i++; +ZipArchiveOutputStream.prototype._writeCentralDirectoryZip64 = function() { + // signature + this.write(zipUtil.getLongBytes(constants.SIG_ZIP64_EOCD)); - if (i >= this.buffers.length) { - // search string not found - return -1; - } - } + // size of the ZIP64 EOCD record + this.write(zipUtil.getEightBytes(44)); - var char = this.buffers[i][j]; + // version made by + this.write(zipUtil.getShortBytes(constants.MIN_VERSION_ZIP64)); - if (char == needle[match]) { - // keep track where match started - if (match == 0) { - mstart = { - i: i, - j: j, - pos: pos - }; - } - match++; - if (match == needle.length) { - // full match - return mstart.pos; - } - } else if (match != 0) { - // a partial match ended, go back to match starting position - // this will continue the search at the next character - i = mstart.i; - j = mstart.j; - pos = mstart.pos; - match = 0; - } + // version to extract + this.write(zipUtil.getShortBytes(constants.MIN_VERSION_ZIP64)); - j++; - pos++; - } -}; + // disk numbers + this.write(constants.LONG_ZERO); + this.write(constants.LONG_ZERO); -Buffers.prototype.toBuffer = function() { - return this.slice(); -} + // number of entries + this.write(zipUtil.getEightBytes(this._entries.length)); + this.write(zipUtil.getEightBytes(this._entries.length)); -Buffers.prototype.toString = function(encoding, start, end) { - return this.slice(start, end).toString(encoding); -} + // length and location of CD + this.write(zipUtil.getEightBytes(this._archive.centralLength)); + this.write(zipUtil.getEightBytes(this._archive.centralOffset)); + // extensible data sector + // not implemented at this time -/***/ }), + // end of central directory locator + this.write(zipUtil.getLongBytes(constants.SIG_ZIP64_EOCD_LOC)); -/***/ 9242: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // disk number holding the ZIP64 EOCD record + this.write(constants.LONG_ZERO); -var Traverse = __nccwpck_require__(24203); -var EventEmitter = (__nccwpck_require__(82361).EventEmitter); + // relative offset of the ZIP64 EOCD record + this.write(zipUtil.getEightBytes(this._archive.centralOffset + this._archive.centralLength)); -module.exports = Chainsaw; -function Chainsaw (builder) { - var saw = Chainsaw.saw(builder, {}); - var r = builder.call(saw.handlers, saw); - if (r !== undefined) saw.handlers = r; - saw.record(); - return saw.chain(); + // total number of disks + this.write(zipUtil.getLongBytes(1)); }; -Chainsaw.light = function ChainsawLight (builder) { - var saw = Chainsaw.saw(builder, {}); - var r = builder.call(saw.handlers, saw); - if (r !== undefined) saw.handlers = r; - return saw.chain(); -}; +ZipArchiveOutputStream.prototype._writeCentralFileHeader = function(ae) { + var gpb = ae.getGeneralPurposeBit(); + var method = ae.getMethod(); + var offsets = ae._offsets; -Chainsaw.saw = function (builder, handlers) { - var saw = new EventEmitter; - saw.handlers = handlers; - saw.actions = []; + var size = ae.getSize(); + var compressedSize = ae.getCompressedSize(); - saw.chain = function () { - var ch = Traverse(saw.handlers).map(function (node) { - if (this.isRoot) return node; - var ps = this.path; + if (ae.isZip64() || offsets.file > constants.ZIP64_MAGIC) { + size = constants.ZIP64_MAGIC; + compressedSize = constants.ZIP64_MAGIC; - if (typeof node === 'function') { - this.update(function () { - saw.actions.push({ - path : ps, - args : [].slice.call(arguments) - }); - return ch; - }); - } - }); + ae.setVersionNeededToExtract(constants.MIN_VERSION_ZIP64); - process.nextTick(function () { - saw.emit('begin'); - saw.next(); - }); + var extraBuf = Buffer.concat([ + zipUtil.getShortBytes(constants.ZIP64_EXTRA_ID), + zipUtil.getShortBytes(24), + zipUtil.getEightBytes(ae.getSize()), + zipUtil.getEightBytes(ae.getCompressedSize()), + zipUtil.getEightBytes(offsets.file) + ], 28); - return ch; - }; + ae.setExtra(extraBuf); + } - saw.pop = function () { - return saw.actions.shift(); - }; + // signature + this.write(zipUtil.getLongBytes(constants.SIG_CFH)); - saw.next = function () { - var action = saw.pop(); + // version made by + this.write(zipUtil.getShortBytes((ae.getPlatform() << 8) | constants.VERSION_MADEBY)); - if (!action) { - saw.emit('end'); - } - else if (!action.trap) { - var node = saw.handlers; - action.path.forEach(function (key) { node = node[key] }); - node.apply(saw.handlers, action.args); - } - }; + // version to extract and general bit flag + this.write(zipUtil.getShortBytes(ae.getVersionNeededToExtract())); + this.write(gpb.encode()); - saw.nest = function (cb) { - var args = [].slice.call(arguments, 1); - var autonext = true; + // compression method + this.write(zipUtil.getShortBytes(method)); - if (typeof cb === 'boolean') { - var autonext = cb; - cb = args.shift(); - } + // datetime + this.write(zipUtil.getLongBytes(ae.getTimeDos())); - var s = Chainsaw.saw(builder, {}); - var r = builder.call(s.handlers, s); + // crc32 checksum + this.write(zipUtil.getLongBytes(ae.getCrc())); - if (r !== undefined) s.handlers = r; + // sizes + this.write(zipUtil.getLongBytes(compressedSize)); + this.write(zipUtil.getLongBytes(size)); - // If we are recording... - if ("undefined" !== typeof saw.step) { - // ... our children should, too - s.record(); - } + var name = ae.getName(); + var comment = ae.getComment(); + var extra = ae.getCentralDirectoryExtra(); - cb.apply(s.chain(), args); - if (autonext !== false) s.on('end', saw.next); - }; + if (gpb.usesUTF8ForNames()) { + name = Buffer.from(name); + comment = Buffer.from(comment); + } - saw.record = function () { - upgradeChainsaw(saw); - }; + // name length + this.write(zipUtil.getShortBytes(name.length)); - ['trap', 'down', 'jump'].forEach(function (method) { - saw[method] = function () { - throw new Error("To use the trap, down and jump features, please "+ - "call record() first to start recording actions."); - }; - }); + // extra length + this.write(zipUtil.getShortBytes(extra.length)); - return saw; -}; + // comments length + this.write(zipUtil.getShortBytes(comment.length)); -function upgradeChainsaw(saw) { - saw.step = 0; + // disk number start + this.write(constants.SHORT_ZERO); - // override pop - saw.pop = function () { - return saw.actions[saw.step++]; - }; + // internal attributes + this.write(zipUtil.getShortBytes(ae.getInternalAttributes())); - saw.trap = function (name, cb) { - var ps = Array.isArray(name) ? name : [name]; - saw.actions.push({ - path : ps, - step : saw.step, - cb : cb, - trap : true - }); - }; + // external attributes + this.write(zipUtil.getLongBytes(ae.getExternalAttributes())); - saw.down = function (name) { - var ps = (Array.isArray(name) ? name : [name]).join('/'); - var i = saw.actions.slice(saw.step).map(function (x) { - if (x.trap && x.step <= saw.step) return false; - return x.path.join('/') == ps; - }).indexOf(true); + // relative offset of LFH + if (offsets.file > constants.ZIP64_MAGIC) { + this.write(zipUtil.getLongBytes(constants.ZIP64_MAGIC)); + } else { + this.write(zipUtil.getLongBytes(offsets.file)); + } - if (i >= 0) saw.step += i; - else saw.step = saw.actions.length; + // name + this.write(name); - var act = saw.actions[saw.step - 1]; - if (act && act.trap) { - // It's a trap! - saw.step = act.step; - act.cb(); - } - else saw.next(); - }; + // extra + this.write(extra); - saw.jump = function (step) { - saw.step = step; - saw.next(); - }; + // comment + this.write(comment); }; +ZipArchiveOutputStream.prototype._writeDataDescriptor = function(ae) { + // signature + this.write(zipUtil.getLongBytes(constants.SIG_DD)); -/***/ }), - -/***/ 96283: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(73837); -var Stream = (__nccwpck_require__(12781).Stream); -var DelayedStream = __nccwpck_require__(88420); + // crc32 checksum + this.write(zipUtil.getLongBytes(ae.getCrc())); -module.exports = CombinedStream; -function CombinedStream() { - this.writable = false; - this.readable = true; - this.dataSize = 0; - this.maxDataSize = 2 * 1024 * 1024; - this.pauseStreams = true; + // sizes + if (ae.isZip64()) { + this.write(zipUtil.getEightBytes(ae.getCompressedSize())); + this.write(zipUtil.getEightBytes(ae.getSize())); + } else { + this.write(zipUtil.getLongBytes(ae.getCompressedSize())); + this.write(zipUtil.getLongBytes(ae.getSize())); + } +}; - this._released = false; - this._streams = []; - this._currentStream = null; - this._insideLoop = false; - this._pendingNext = false; -} -util.inherits(CombinedStream, Stream); +ZipArchiveOutputStream.prototype._writeLocalFileHeader = function(ae) { + var gpb = ae.getGeneralPurposeBit(); + var method = ae.getMethod(); + var name = ae.getName(); + var extra = ae.getLocalFileDataExtra(); -CombinedStream.create = function(options) { - var combinedStream = new this(); + if (ae.isZip64()) { + gpb.useDataDescriptor(true); + ae.setVersionNeededToExtract(constants.MIN_VERSION_ZIP64); + } - options = options || {}; - for (var option in options) { - combinedStream[option] = options[option]; + if (gpb.usesUTF8ForNames()) { + name = Buffer.from(name); } - return combinedStream; -}; + ae._offsets.file = this.offset; -CombinedStream.isStreamLike = function(stream) { - return (typeof stream !== 'function') - && (typeof stream !== 'string') - && (typeof stream !== 'boolean') - && (typeof stream !== 'number') - && (!Buffer.isBuffer(stream)); -}; + // signature + this.write(zipUtil.getLongBytes(constants.SIG_LFH)); -CombinedStream.prototype.append = function(stream) { - var isStreamLike = CombinedStream.isStreamLike(stream); + // version to extract and general bit flag + this.write(zipUtil.getShortBytes(ae.getVersionNeededToExtract())); + this.write(gpb.encode()); - if (isStreamLike) { - if (!(stream instanceof DelayedStream)) { - var newStream = DelayedStream.create(stream, { - maxDataSize: Infinity, - pauseStream: this.pauseStreams, - }); - stream.on('data', this._checkDataSize.bind(this)); - stream = newStream; - } + // compression method + this.write(zipUtil.getShortBytes(method)); - this._handleErrors(stream); + // datetime + this.write(zipUtil.getLongBytes(ae.getTimeDos())); - if (this.pauseStreams) { - stream.pause(); - } + ae._offsets.data = this.offset; + + // crc32 checksum and sizes + if (gpb.usesDataDescriptor()) { + this.write(constants.LONG_ZERO); + this.write(constants.LONG_ZERO); + this.write(constants.LONG_ZERO); + } else { + this.write(zipUtil.getLongBytes(ae.getCrc())); + this.write(zipUtil.getLongBytes(ae.getCompressedSize())); + this.write(zipUtil.getLongBytes(ae.getSize())); } - this._streams.push(stream); - return this; -}; + // name length + this.write(zipUtil.getShortBytes(name.length)); -CombinedStream.prototype.pipe = function(dest, options) { - Stream.prototype.pipe.call(this, dest, options); - this.resume(); - return dest; -}; + // extra length + this.write(zipUtil.getShortBytes(extra.length)); -CombinedStream.prototype._getNext = function() { - this._currentStream = null; + // name + this.write(name); - if (this._insideLoop) { - this._pendingNext = true; - return; // defer call - } + // extra + this.write(extra); - this._insideLoop = true; - try { - do { - this._pendingNext = false; - this._realGetNext(); - } while (this._pendingNext); - } finally { - this._insideLoop = false; - } -}; - -CombinedStream.prototype._realGetNext = function() { - var stream = this._streams.shift(); - - - if (typeof stream == 'undefined') { - this.end(); - return; - } - - if (typeof stream !== 'function') { - this._pipeNext(stream); - return; - } - - var getStream = stream; - getStream(function(stream) { - var isStreamLike = CombinedStream.isStreamLike(stream); - if (isStreamLike) { - stream.on('data', this._checkDataSize.bind(this)); - this._handleErrors(stream); - } - - this._pipeNext(stream); - }.bind(this)); -}; - -CombinedStream.prototype._pipeNext = function(stream) { - this._currentStream = stream; - - var isStreamLike = CombinedStream.isStreamLike(stream); - if (isStreamLike) { - stream.on('end', this._getNext.bind(this)); - stream.pipe(this, {end: false}); - return; - } - - var value = stream; - this.write(value); - this._getNext(); -}; - -CombinedStream.prototype._handleErrors = function(stream) { - var self = this; - stream.on('error', function(err) { - self._emitError(err); - }); -}; - -CombinedStream.prototype.write = function(data) { - this.emit('data', data); -}; - -CombinedStream.prototype.pause = function() { - if (!this.pauseStreams) { - return; - } - - if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); - this.emit('pause'); -}; - -CombinedStream.prototype.resume = function() { - if (!this._released) { - this._released = true; - this.writable = true; - this._getNext(); - } - - if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); - this.emit('resume'); -}; - -CombinedStream.prototype.end = function() { - this._reset(); - this.emit('end'); -}; - -CombinedStream.prototype.destroy = function() { - this._reset(); - this.emit('close'); -}; - -CombinedStream.prototype._reset = function() { - this.writable = false; - this._streams = []; - this._currentStream = null; + ae._offsets.contents = this.offset; }; -CombinedStream.prototype._checkDataSize = function() { - this._updateDataSize(); - if (this.dataSize <= this.maxDataSize) { - return; - } - - var message = - 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; - this._emitError(new Error(message)); +ZipArchiveOutputStream.prototype.getComment = function(comment) { + return this._archive.comment !== null ? this._archive.comment : ''; }; -CombinedStream.prototype._updateDataSize = function() { - this.dataSize = 0; - - var self = this; - this._streams.forEach(function(stream) { - if (!stream.dataSize) { - return; - } - - self.dataSize += stream.dataSize; - }); - - if (this._currentStream && this._currentStream.dataSize) { - this.dataSize += this._currentStream.dataSize; - } +ZipArchiveOutputStream.prototype.isZip64 = function() { + return this._archive.forceZip64 || this._entries.length > constants.ZIP64_MAGIC_SHORT || this._archive.centralLength > constants.ZIP64_MAGIC || this._archive.centralOffset > constants.ZIP64_MAGIC; }; -CombinedStream.prototype._emitError = function(err) { - this._reset(); - this.emit('error', err); +ZipArchiveOutputStream.prototype.setComment = function(comment) { + this._archive.comment = comment; }; /***/ }), -/***/ 89766: -/***/ ((module) => { +/***/ 25445: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** * node-compress-commons @@ -73947,19 +67665,16 @@ CombinedStream.prototype._emitError = function(err) { * Licensed under the MIT license. * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT */ -var ArchiveEntry = module.exports = function() {}; - -ArchiveEntry.prototype.getName = function() {}; - -ArchiveEntry.prototype.getSize = function() {}; - -ArchiveEntry.prototype.getLastModifiedDate = function() {}; - -ArchiveEntry.prototype.isDirectory = function() {}; +module.exports = { + ArchiveEntry: __nccwpck_require__(92240), + ZipArchiveEntry: __nccwpck_require__(3179), + ArchiveOutputStream: __nccwpck_require__(36728), + ZipArchiveOutputStream: __nccwpck_require__(44432) +}; /***/ }), -/***/ 98985: +/***/ 95208: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** @@ -73969,2719 +67684,3532 @@ ArchiveEntry.prototype.isDirectory = function() {}; * Licensed under the MIT license. * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT */ -var inherits = (__nccwpck_require__(73837).inherits); -var Transform = (__nccwpck_require__(84123).Transform); +var Stream = (__nccwpck_require__(12781).Stream); +var PassThrough = (__nccwpck_require__(51642).PassThrough); -var ArchiveEntry = __nccwpck_require__(89766); -var util = __nccwpck_require__(67592); +var util = module.exports = {}; -var ArchiveOutputStream = module.exports = function(options) { - if (!(this instanceof ArchiveOutputStream)) { - return new ArchiveOutputStream(options); - } +util.isStream = function(source) { + return source instanceof Stream; +}; - Transform.call(this, options); +util.normalizeInputSource = function(source) { + if (source === null) { + return Buffer.alloc(0); + } else if (typeof source === 'string') { + return Buffer.from(source); + } else if (util.isStream(source) && !source._readableState) { + var normalized = new PassThrough(); + source.pipe(normalized); - this.offset = 0; - this._archive = { - finish: false, - finished: false, - processing: false - }; + return normalized; + } + + return source; }; -inherits(ArchiveOutputStream, Transform); +/***/ }), -ArchiveOutputStream.prototype._appendBuffer = function(zae, source, callback) { - // scaffold only -}; +/***/ 86891: +/***/ ((module) => { -ArchiveOutputStream.prototype._appendStream = function(zae, source, callback) { - // scaffold only +module.exports = function (xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + var x = fn(xs[i], i); + if (isArray(x)) res.push.apply(res, x); + else res.push(x); + } + return res; }; -ArchiveOutputStream.prototype._emitErrorCallback = function(err) { - if (err) { - this.emit('error', err); - } +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; }; -ArchiveOutputStream.prototype._finish = function(ae) { - // scaffold only -}; -ArchiveOutputStream.prototype._normalizeEntry = function(ae) { - // scaffold only -}; +/***/ }), -ArchiveOutputStream.prototype._transform = function(chunk, encoding, callback) { - callback(null, chunk); -}; +/***/ 95898: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -ArchiveOutputStream.prototype.entry = function(ae, source, callback) { - source = source || null; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - if (typeof callback !== 'function') { - callback = this._emitErrorCallback.bind(this); - } +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. - if (!(ae instanceof ArchiveEntry)) { - callback(new Error('not a valid instance of ArchiveEntry')); - return; +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; - if (this._archive.finish || this._archive.finished) { - callback(new Error('unacceptable entry after finish')); - return; - } +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; - if (this._archive.processing) { - callback(new Error('already processing an entry')); - return; - } +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; - this._archive.processing = true; - this._normalizeEntry(ae); - this._entry = ae; +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; - source = util.normalizeInputSource(source); +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; - if (Buffer.isBuffer(source)) { - this._appendBuffer(ae, source, callback); - } else if (util.isStream(source)) { - this._appendStream(ae, source, callback); - } else { - this._archive.processing = false; - callback(new Error('input source must be valid Stream or Buffer instance')); - return; - } +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; - return this; -}; +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; -ArchiveOutputStream.prototype.finish = function() { - if (this._archive.processing) { - this._archive.finish = true; - return; - } +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; - this._finish(); -}; +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; -ArchiveOutputStream.prototype.getBytesWritten = function() { - return this.offset; -}; +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; -ArchiveOutputStream.prototype.write = function(chunk, cb) { - if (chunk) { - this.offset += chunk.length; - } +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; - return Transform.prototype.write.call(this, chunk, cb); -}; +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; -/***/ }), +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; -/***/ 90114: -/***/ ((module) => { +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; -/** - * node-compress-commons - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT - */ -module.exports = { - WORD: 4, - DWORD: 8, - EMPTY: Buffer.alloc(0), +exports.isBuffer = __nccwpck_require__(14300).Buffer.isBuffer; - SHORT: 2, - SHORT_MASK: 0xffff, - SHORT_SHIFT: 16, - SHORT_ZERO: Buffer.from(Array(2)), - LONG: 4, - LONG_ZERO: Buffer.from(Array(4)), +function objectToString(o) { + return Object.prototype.toString.call(o); +} - MIN_VERSION_INITIAL: 10, - MIN_VERSION_DATA_DESCRIPTOR: 20, - MIN_VERSION_ZIP64: 45, - VERSION_MADEBY: 45, - METHOD_STORED: 0, - METHOD_DEFLATED: 8, +/***/ }), - PLATFORM_UNIX: 3, - PLATFORM_FAT: 0, +/***/ 83201: +/***/ ((__unused_webpack_module, exports) => { - SIG_LFH: 0x04034b50, - SIG_DD: 0x08074b50, - SIG_CFH: 0x02014b50, - SIG_EOCD: 0x06054b50, - SIG_ZIP64_EOCD: 0x06064B50, - SIG_ZIP64_EOCD_LOC: 0x07064B50, +/*! crc32.js (C) 2014-present SheetJS -- http://sheetjs.com */ +/* vim: set ts=2: */ +/*exported CRC32 */ +var CRC32; +(function (factory) { + /*jshint ignore:start */ + /*eslint-disable */ + if(typeof DO_NOT_EXPORT_CRC === 'undefined') { + if(true) { + factory(exports); + } else {} + } else { + factory(CRC32 = {}); + } + /*eslint-enable */ + /*jshint ignore:end */ +}(function(CRC32) { +CRC32.version = '1.2.2'; +/*global Int32Array */ +function signed_crc_table() { + var c = 0, table = new Array(256); - ZIP64_MAGIC_SHORT: 0xffff, - ZIP64_MAGIC: 0xffffffff, - ZIP64_EXTRA_ID: 0x0001, + for(var n =0; n != 256; ++n){ + c = n; + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + table[n] = c; + } - ZLIB_NO_COMPRESSION: 0, - ZLIB_BEST_SPEED: 1, - ZLIB_BEST_COMPRESSION: 9, - ZLIB_DEFAULT_COMPRESSION: -1, + return typeof Int32Array !== 'undefined' ? new Int32Array(table) : table; +} - MODE_MASK: 0xFFF, - DEFAULT_FILE_MODE: 33188, // 010644 = -rw-r--r-- = S_IFREG | S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH - DEFAULT_DIR_MODE: 16877, // 040755 = drwxr-xr-x = S_IFDIR | S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH +var T0 = signed_crc_table(); +function slice_by_16_tables(T) { + var c = 0, v = 0, n = 0, table = typeof Int32Array !== 'undefined' ? new Int32Array(4096) : new Array(4096) ; - EXT_FILE_ATTR_DIR: 1106051088, // 010173200020 = drwxr-xr-x = (((S_IFDIR | 0755) << 16) | S_DOS_D) - EXT_FILE_ATTR_FILE: 2175008800, // 020151000040 = -rw-r--r-- = (((S_IFREG | 0644) << 16) | S_DOS_A) >>> 0 + for(n = 0; n != 256; ++n) table[n] = T[n]; + for(n = 0; n != 256; ++n) { + v = T[n]; + for(c = 256 + n; c < 4096; c += 256) v = table[c] = (v >>> 8) ^ T[v & 0xFF]; + } + var out = []; + for(n = 1; n != 16; ++n) out[n - 1] = typeof Int32Array !== 'undefined' ? table.subarray(n * 256, n * 256 + 256) : table.slice(n * 256, n * 256 + 256); + return out; +} +var TT = slice_by_16_tables(T0); +var T1 = TT[0], T2 = TT[1], T3 = TT[2], T4 = TT[3], T5 = TT[4]; +var T6 = TT[5], T7 = TT[6], T8 = TT[7], T9 = TT[8], Ta = TT[9]; +var Tb = TT[10], Tc = TT[11], Td = TT[12], Te = TT[13], Tf = TT[14]; +function crc32_bstr(bstr, seed) { + var C = seed ^ -1; + for(var i = 0, L = bstr.length; i < L;) C = (C>>>8) ^ T0[(C^bstr.charCodeAt(i++))&0xFF]; + return ~C; +} - // Unix file types - S_IFMT: 61440, // 0170000 type of file mask - S_IFIFO: 4096, // 010000 named pipe (fifo) - S_IFCHR: 8192, // 020000 character special - S_IFDIR: 16384, // 040000 directory - S_IFBLK: 24576, // 060000 block special - S_IFREG: 32768, // 0100000 regular - S_IFLNK: 40960, // 0120000 symbolic link - S_IFSOCK: 49152, // 0140000 socket +function crc32_buf(B, seed) { + var C = seed ^ -1, L = B.length - 15, i = 0; + for(; i < L;) C = + Tf[B[i++] ^ (C & 255)] ^ + Te[B[i++] ^ ((C >> 8) & 255)] ^ + Td[B[i++] ^ ((C >> 16) & 255)] ^ + Tc[B[i++] ^ (C >>> 24)] ^ + Tb[B[i++]] ^ Ta[B[i++]] ^ T9[B[i++]] ^ T8[B[i++]] ^ + T7[B[i++]] ^ T6[B[i++]] ^ T5[B[i++]] ^ T4[B[i++]] ^ + T3[B[i++]] ^ T2[B[i++]] ^ T1[B[i++]] ^ T0[B[i++]]; + L += 15; + while(i < L) C = (C>>>8) ^ T0[(C^B[i++])&0xFF]; + return ~C; +} - // DOS file type flags - S_DOS_A: 32, // 040 Archive - S_DOS_D: 16, // 020 Directory - S_DOS_V: 8, // 010 Volume - S_DOS_S: 4, // 04 System - S_DOS_H: 2, // 02 Hidden - S_DOS_R: 1 // 01 Read Only -}; +function crc32_str(str, seed) { + var C = seed ^ -1; + for(var i = 0, L = str.length, c = 0, d = 0; i < L;) { + c = str.charCodeAt(i++); + if(c < 0x80) { + C = (C>>>8) ^ T0[(C^c)&0xFF]; + } else if(c < 0x800) { + C = (C>>>8) ^ T0[(C ^ (192|((c>>6)&31)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|(c&63)))&0xFF]; + } else if(c >= 0xD800 && c < 0xE000) { + c = (c&1023)+64; d = str.charCodeAt(i++)&1023; + C = (C>>>8) ^ T0[(C ^ (240|((c>>8)&7)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|((c>>2)&63)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|((d>>6)&15)|((c&3)<<4)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|(d&63)))&0xFF]; + } else { + C = (C>>>8) ^ T0[(C ^ (224|((c>>12)&15)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|((c>>6)&63)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|(c&63)))&0xFF]; + } + } + return ~C; +} +CRC32.table = T0; +// $FlowIgnore +CRC32.bstr = crc32_bstr; +// $FlowIgnore +CRC32.buf = crc32_buf; +// $FlowIgnore +CRC32.str = crc32_str; +})); /***/ }), -/***/ 84611: +/***/ 94521: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; /** - * node-compress-commons + * node-crc32-stream * * Copyright (c) 2014 Chris Talkington, contributors. * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT + * https://github.com/archiverjs/node-crc32-stream/blob/master/LICENSE-MIT */ -var zipUtil = __nccwpck_require__(19195); -var DATA_DESCRIPTOR_FLAG = 1 << 3; -var ENCRYPTION_FLAG = 1 << 0; -var NUMBER_OF_SHANNON_FANO_TREES_FLAG = 1 << 2; -var SLIDING_DICTIONARY_SIZE_FLAG = 1 << 1; -var STRONG_ENCRYPTION_FLAG = 1 << 6; -var UFT8_NAMES_FLAG = 1 << 11; + -var GeneralPurposeBit = module.exports = function() { - if (!(this instanceof GeneralPurposeBit)) { - return new GeneralPurposeBit(); - } +const {Transform} = __nccwpck_require__(51642); - this.descriptor = false; - this.encryption = false; - this.utf8 = false; - this.numberOfShannonFanoTrees = 0; - this.strongEncryption = false; - this.slidingDictionarySize = 0; +const crc32 = __nccwpck_require__(83201); - return this; -}; +class CRC32Stream extends Transform { + constructor(options) { + super(options); + this.checksum = Buffer.allocUnsafe(4); + this.checksum.writeInt32BE(0, 0); -GeneralPurposeBit.prototype.encode = function() { - return zipUtil.getShortBytes( - (this.descriptor ? DATA_DESCRIPTOR_FLAG : 0) | - (this.utf8 ? UFT8_NAMES_FLAG : 0) | - (this.encryption ? ENCRYPTION_FLAG : 0) | - (this.strongEncryption ? STRONG_ENCRYPTION_FLAG : 0) - ); -}; + this.rawSize = 0; + } -GeneralPurposeBit.prototype.parse = function(buf, offset) { - var flag = zipUtil.getShortBytesValue(buf, offset); - var gbp = new GeneralPurposeBit(); + _transform(chunk, encoding, callback) { + if (chunk) { + this.checksum = crc32.buf(chunk, this.checksum) >>> 0; + this.rawSize += chunk.length; + } - gbp.useDataDescriptor((flag & DATA_DESCRIPTOR_FLAG) !== 0); - gbp.useUTF8ForNames((flag & UFT8_NAMES_FLAG) !== 0); - gbp.useStrongEncryption((flag & STRONG_ENCRYPTION_FLAG) !== 0); - gbp.useEncryption((flag & ENCRYPTION_FLAG) !== 0); - gbp.setSlidingDictionarySize((flag & SLIDING_DICTIONARY_SIZE_FLAG) !== 0 ? 8192 : 4096); - gbp.setNumberOfShannonFanoTrees((flag & NUMBER_OF_SHANNON_FANO_TREES_FLAG) !== 0 ? 3 : 2); + callback(null, chunk); + } - return gbp; -}; + digest(encoding) { + const checksum = Buffer.allocUnsafe(4); + checksum.writeUInt32BE(this.checksum >>> 0, 0); + return encoding ? checksum.toString(encoding) : checksum; + } -GeneralPurposeBit.prototype.setNumberOfShannonFanoTrees = function(n) { - this.numberOfShannonFanoTrees = n; -}; + hex() { + return this.digest('hex').toUpperCase(); + } -GeneralPurposeBit.prototype.getNumberOfShannonFanoTrees = function() { - return this.numberOfShannonFanoTrees; -}; + size() { + return this.rawSize; + } +} -GeneralPurposeBit.prototype.setSlidingDictionarySize = function(n) { - this.slidingDictionarySize = n; -}; +module.exports = CRC32Stream; -GeneralPurposeBit.prototype.getSlidingDictionarySize = function() { - return this.slidingDictionarySize; -}; -GeneralPurposeBit.prototype.useDataDescriptor = function(b) { - this.descriptor = b; -}; +/***/ }), -GeneralPurposeBit.prototype.usesDataDescriptor = function() { - return this.descriptor; -}; +/***/ 92563: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -GeneralPurposeBit.prototype.useEncryption = function(b) { - this.encryption = b; -}; +"use strict"; +/** + * node-crc32-stream + * + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-crc32-stream/blob/master/LICENSE-MIT + */ -GeneralPurposeBit.prototype.usesEncryption = function() { - return this.encryption; -}; -GeneralPurposeBit.prototype.useStrongEncryption = function(b) { - this.strongEncryption = b; -}; -GeneralPurposeBit.prototype.usesStrongEncryption = function() { - return this.strongEncryption; -}; +const {DeflateRaw} = __nccwpck_require__(59796); -GeneralPurposeBit.prototype.useUTF8ForNames = function(b) { - this.utf8 = b; -}; +const crc32 = __nccwpck_require__(83201); -GeneralPurposeBit.prototype.usesUTF8ForNames = function() { - return this.utf8; -}; +class DeflateCRC32Stream extends DeflateRaw { + constructor(options) { + super(options); -/***/ }), + this.checksum = Buffer.allocUnsafe(4); + this.checksum.writeInt32BE(0, 0); -/***/ 25743: -/***/ ((module) => { + this.rawSize = 0; + this.compressedSize = 0; + } -/** - * node-compress-commons - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT - */ -module.exports = { - /** - * Bits used for permissions (and sticky bit) - */ - PERM_MASK: 4095, // 07777 + push(chunk, encoding) { + if (chunk) { + this.compressedSize += chunk.length; + } - /** - * Bits used to indicate the filesystem object type. - */ - FILE_TYPE_FLAG: 61440, // 0170000 + return super.push(chunk, encoding); + } - /** - * Indicates symbolic links. - */ - LINK_FLAG: 40960, // 0120000 + _transform(chunk, encoding, callback) { + if (chunk) { + this.checksum = crc32.buf(chunk, this.checksum) >>> 0; + this.rawSize += chunk.length; + } - /** - * Indicates plain files. - */ - FILE_FLAG: 32768, // 0100000 + super._transform(chunk, encoding, callback) + } - /** - * Indicates directories. - */ - DIR_FLAG: 16384, // 040000 + digest(encoding) { + const checksum = Buffer.allocUnsafe(4); + checksum.writeUInt32BE(this.checksum >>> 0, 0); + return encoding ? checksum.toString(encoding) : checksum; + } - // ---------------------------------------------------------- - // somewhat arbitrary choices that are quite common for shared - // installations - // ----------------------------------------------------------- + hex() { + return this.digest('hex').toUpperCase(); + } - /** - * Default permissions for symbolic links. - */ - DEFAULT_LINK_PERM: 511, // 0777 + size(compressed = false) { + if (compressed) { + return this.compressedSize; + } else { + return this.rawSize; + } + } +} - /** - * Default permissions for directories. - */ - DEFAULT_DIR_PERM: 493, // 0755 +module.exports = DeflateCRC32Stream; - /** - * Default permissions for plain files. - */ - DEFAULT_FILE_PERM: 420 // 0644 -}; /***/ }), -/***/ 19195: -/***/ ((module) => { +/***/ 5101: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; /** - * node-compress-commons + * node-crc32-stream * * Copyright (c) 2014 Chris Talkington, contributors. * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT + * https://github.com/archiverjs/node-crc32-stream/blob/master/LICENSE-MIT */ -var util = module.exports = {}; -util.dateToDos = function(d, forceLocalTime) { - forceLocalTime = forceLocalTime || false; - var year = forceLocalTime ? d.getFullYear() : d.getUTCFullYear(); - if (year < 1980) { - return 2162688; // 1980-1-1 00:00:00 - } else if (year >= 2044) { - return 2141175677; // 2043-12-31 23:59:58 +module.exports = { + CRC32Stream: __nccwpck_require__(94521), + DeflateCRC32Stream: __nccwpck_require__(92563) +} + + +/***/ }), + +/***/ 18611: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var Stream = (__nccwpck_require__(12781).Stream); +var util = __nccwpck_require__(73837); + +module.exports = DelayedStream; +function DelayedStream() { + this.source = null; + this.dataSize = 0; + this.maxDataSize = 1024 * 1024; + this.pauseStream = true; + + this._maxDataSizeExceeded = false; + this._released = false; + this._bufferedEvents = []; +} +util.inherits(DelayedStream, Stream); + +DelayedStream.create = function(source, options) { + var delayedStream = new this(); + + options = options || {}; + for (var option in options) { + delayedStream[option] = options[option]; } - var val = { - year: year, - month: forceLocalTime ? d.getMonth() : d.getUTCMonth(), - date: forceLocalTime ? d.getDate() : d.getUTCDate(), - hours: forceLocalTime ? d.getHours() : d.getUTCHours(), - minutes: forceLocalTime ? d.getMinutes() : d.getUTCMinutes(), - seconds: forceLocalTime ? d.getSeconds() : d.getUTCSeconds() + delayedStream.source = source; + + var realEmit = source.emit; + source.emit = function() { + delayedStream._handleEmit(arguments); + return realEmit.apply(source, arguments); }; - return ((val.year - 1980) << 25) | ((val.month + 1) << 21) | (val.date << 16) | - (val.hours << 11) | (val.minutes << 5) | (val.seconds / 2); -}; + source.on('error', function() {}); + if (delayedStream.pauseStream) { + source.pause(); + } -util.dosToDate = function(dos) { - return new Date(((dos >> 25) & 0x7f) + 1980, ((dos >> 21) & 0x0f) - 1, (dos >> 16) & 0x1f, (dos >> 11) & 0x1f, (dos >> 5) & 0x3f, (dos & 0x1f) << 1); + return delayedStream; }; -util.fromDosTime = function(buf) { - return util.dosToDate(buf.readUInt32LE(0)); +Object.defineProperty(DelayedStream.prototype, 'readable', { + configurable: true, + enumerable: true, + get: function() { + return this.source.readable; + } +}); + +DelayedStream.prototype.setEncoding = function() { + return this.source.setEncoding.apply(this.source, arguments); }; -util.getEightBytes = function(v) { - var buf = Buffer.alloc(8); - buf.writeUInt32LE(v % 0x0100000000, 0); - buf.writeUInt32LE((v / 0x0100000000) | 0, 4); +DelayedStream.prototype.resume = function() { + if (!this._released) { + this.release(); + } - return buf; + this.source.resume(); }; -util.getShortBytes = function(v) { - var buf = Buffer.alloc(2); - buf.writeUInt16LE((v & 0xFFFF) >>> 0, 0); +DelayedStream.prototype.pause = function() { + this.source.pause(); +}; - return buf; +DelayedStream.prototype.release = function() { + this._released = true; + + this._bufferedEvents.forEach(function(args) { + this.emit.apply(this, args); + }.bind(this)); + this._bufferedEvents = []; }; -util.getShortBytesValue = function(buf, offset) { - return buf.readUInt16LE(offset); +DelayedStream.prototype.pipe = function() { + var r = Stream.prototype.pipe.apply(this, arguments); + this.resume(); + return r; }; -util.getLongBytes = function(v) { - var buf = Buffer.alloc(4); - buf.writeUInt32LE((v & 0xFFFFFFFF) >>> 0, 0); +DelayedStream.prototype._handleEmit = function(args) { + if (this._released) { + this.emit.apply(this, args); + return; + } - return buf; -}; + if (args[0] === 'data') { + this.dataSize += args[1].length; + this._checkIfMaxDataSizeExceeded(); + } -util.getLongBytesValue = function(buf, offset) { - return buf.readUInt32LE(offset); + this._bufferedEvents.push(args); }; -util.toDosTime = function(d) { - return util.getLongBytes(util.dateToDos(d)); +DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { + if (this._maxDataSizeExceeded) { + return; + } + + if (this.dataSize <= this.maxDataSize) { + return; + } + + this._maxDataSizeExceeded = true; + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' + this.emit('error', new Error(message)); }; + /***/ }), -/***/ 54970: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 58932: +/***/ ((__unused_webpack_module, exports) => { -/** - * node-compress-commons - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT - */ -var inherits = (__nccwpck_require__(73837).inherits); -var normalizePath = __nccwpck_require__(19796); +"use strict"; -var ArchiveEntry = __nccwpck_require__(89766); -var GeneralPurposeBit = __nccwpck_require__(84611); -var UnixStat = __nccwpck_require__(25743); -var constants = __nccwpck_require__(90114); -var zipUtil = __nccwpck_require__(19195); +Object.defineProperty(exports, "__esModule", ({ value: true })); -var ZipArchiveEntry = module.exports = function(name) { - if (!(this instanceof ZipArchiveEntry)) { - return new ZipArchiveEntry(name); - } +class Deprecation extends Error { + constructor(message) { + super(message); // Maintains proper stack trace (only available on V8) - ArchiveEntry.call(this); + /* istanbul ignore next */ - this.platform = constants.PLATFORM_FAT; - this.method = -1; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } - this.name = null; - this.size = 0; - this.csize = 0; - this.gpb = new GeneralPurposeBit(); - this.crc = 0; - this.time = -1; + this.name = 'Deprecation'; + } - this.minver = constants.MIN_VERSION_INITIAL; - this.mode = -1; - this.extra = null; - this.exattr = 0; - this.inattr = 0; - this.comment = null; +} - if (name) { - this.setName(name); - } -}; +exports.Deprecation = Deprecation; -inherits(ZipArchiveEntry, ArchiveEntry); -/** - * Returns the extra fields related to the entry. - * - * @returns {Buffer} - */ -ZipArchiveEntry.prototype.getCentralDirectoryExtra = function() { - return this.getExtra(); -}; +/***/ }), -/** - * Returns the comment set for the entry. - * - * @returns {string} - */ -ZipArchiveEntry.prototype.getComment = function() { - return this.comment !== null ? this.comment : ''; -}; +/***/ 13598: +/***/ ((module) => { -/** - * Returns the compressed size of the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getCompressedSize = function() { - return this.csize; -}; +"use strict"; -/** - * Returns the CRC32 digest for the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getCrc = function() { - return this.crc; -}; -/** - * Returns the external file attributes for the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getExternalAttributes = function() { - return this.exattr; -}; +function _process (v, mod) { + var i + var r -/** - * Returns the extra fields related to the entry. - * - * @returns {Buffer} - */ -ZipArchiveEntry.prototype.getExtra = function() { - return this.extra !== null ? this.extra : constants.EMPTY; -}; + if (typeof mod === 'function') { + r = mod(v) + if (r !== undefined) { + v = r + } + } else if (Array.isArray(mod)) { + for (i = 0; i < mod.length; i++) { + r = mod[i](v) + if (r !== undefined) { + v = r + } + } + } -/** - * Returns the general purpose bits related to the entry. - * - * @returns {GeneralPurposeBit} - */ -ZipArchiveEntry.prototype.getGeneralPurposeBit = function() { - return this.gpb; -}; + return v +} -/** - * Returns the internal file attributes for the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getInternalAttributes = function() { - return this.inattr; -}; +function parseKey (key, val) { + // detect negative index notation + if (key[0] === '-' && Array.isArray(val) && /^-\d+$/.test(key)) { + return val.length + parseInt(key, 10) + } + return key +} -/** - * Returns the last modified date of the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getLastModifiedDate = function() { - return this.getTime(); -}; +function isIndex (k) { + return /^\d+$/.test(k) +} -/** - * Returns the extra fields related to the entry. - * - * @returns {Buffer} - */ -ZipArchiveEntry.prototype.getLocalFileDataExtra = function() { - return this.getExtra(); -}; +function isObject (val) { + return Object.prototype.toString.call(val) === '[object Object]' +} -/** - * Returns the compression method used on the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getMethod = function() { - return this.method; -}; +function isArrayOrObject (val) { + return Object(val) === val +} -/** - * Returns the filename of the entry. - * - * @returns {string} - */ -ZipArchiveEntry.prototype.getName = function() { - return this.name; -}; +function isEmptyObject (val) { + return Object.keys(val).length === 0 +} -/** - * Returns the platform on which the entry was made. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getPlatform = function() { - return this.platform; -}; +var blacklist = ['__proto__', 'prototype', 'constructor'] +var blacklistFilter = function (part) { return blacklist.indexOf(part) === -1 } -/** - * Returns the size of the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getSize = function() { - return this.size; -}; +function parsePath (path, sep) { + if (path.indexOf('[') >= 0) { + path = path.replace(/\[/g, sep).replace(/]/g, '') + } -/** - * Returns a date object representing the last modified date of the entry. - * - * @returns {number|Date} - */ -ZipArchiveEntry.prototype.getTime = function() { - return this.time !== -1 ? zipUtil.dosToDate(this.time) : -1; -}; + var parts = path.split(sep) -/** - * Returns the DOS timestamp for the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getTimeDos = function() { - return this.time !== -1 ? this.time : 0; -}; + var check = parts.filter(blacklistFilter) -/** - * Returns the UNIX file permissions for the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getUnixMode = function() { - return this.platform !== constants.PLATFORM_UNIX ? 0 : ((this.getExternalAttributes() >> constants.SHORT_SHIFT) & constants.SHORT_MASK); -}; + if (check.length !== parts.length) { + throw Error('Refusing to update blacklisted property ' + path) + } -/** - * Returns the version of ZIP needed to extract the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getVersionNeededToExtract = function() { - return this.minver; -}; + return parts +} -/** - * Sets the comment of the entry. - * - * @param comment - */ -ZipArchiveEntry.prototype.setComment = function(comment) { - if (Buffer.byteLength(comment) !== comment.length) { - this.getGeneralPurposeBit().useUTF8ForNames(true); +var hasOwnProperty = Object.prototype.hasOwnProperty + +function DotObject (separator, override, useArray, useBrackets) { + if (!(this instanceof DotObject)) { + return new DotObject(separator, override, useArray, useBrackets) } - this.comment = comment; -}; + if (typeof override === 'undefined') override = false + if (typeof useArray === 'undefined') useArray = true + if (typeof useBrackets === 'undefined') useBrackets = true + this.separator = separator || '.' + this.override = override + this.useArray = useArray + this.useBrackets = useBrackets + this.keepArray = false -/** - * Sets the compressed size of the entry. - * - * @param size - */ -ZipArchiveEntry.prototype.setCompressedSize = function(size) { - if (size < 0) { - throw new Error('invalid entry compressed size'); + // contains touched arrays + this.cleanup = [] +} + +var dotDefault = new DotObject('.', false, true, true) +function wrap (method) { + return function () { + return dotDefault[method].apply(dotDefault, arguments) } +} - this.csize = size; -}; +DotObject.prototype._fill = function (a, obj, v, mod) { + var k = a.shift() -/** - * Sets the checksum of the entry. - * - * @param crc - */ -ZipArchiveEntry.prototype.setCrc = function(crc) { - if (crc < 0) { - throw new Error('invalid entry crc32'); - } + if (a.length > 0) { + obj[k] = obj[k] || (this.useArray && isIndex(a[0]) ? [] : {}) - this.crc = crc; -}; + if (!isArrayOrObject(obj[k])) { + if (this.override) { + obj[k] = {} + } else { + if (!(isArrayOrObject(v) && isEmptyObject(v))) { + throw new Error( + 'Trying to redefine `' + k + '` which is a ' + typeof obj[k] + ) + } -/** - * Sets the external file attributes of the entry. - * - * @param attr - */ -ZipArchiveEntry.prototype.setExternalAttributes = function(attr) { - this.exattr = attr >>> 0; -}; + return + } + } + + this._fill(a, obj[k], v, mod) + } else { + if (!this.override && isArrayOrObject(obj[k]) && !isEmptyObject(obj[k])) { + if (!(isArrayOrObject(v) && isEmptyObject(v))) { + throw new Error("Trying to redefine non-empty obj['" + k + "']") + } + + return + } + + obj[k] = _process(v, mod) + } +} /** - * Sets the extra fields related to the entry. * - * @param extra + * Converts an object with dotted-key/value pairs to it's expanded version + * + * Optionally transformed by a set of modifiers. + * + * Usage: + * + * var row = { + * 'nr': 200, + * 'doc.name': ' My Document ' + * } + * + * var mods = { + * 'doc.name': [_s.trim, _s.underscored] + * } + * + * dot.object(row, mods) + * + * @param {Object} obj + * @param {Object} mods */ -ZipArchiveEntry.prototype.setExtra = function(extra) { - this.extra = extra; -}; +DotObject.prototype.object = function (obj, mods) { + var self = this + + Object.keys(obj).forEach(function (k) { + var mod = mods === undefined ? null : mods[k] + // normalize array notation. + var ok = parsePath(k, self.separator).join(self.separator) + + if (ok.indexOf(self.separator) !== -1) { + self._fill(ok.split(self.separator), obj, obj[k], mod) + delete obj[k] + } else { + obj[k] = _process(obj[k], mod) + } + }) + + return obj +} /** - * Sets the general purpose bits related to the entry. - * - * @param gpb + * @param {String} path dotted path + * @param {String} v value to be set + * @param {Object} obj object to be modified + * @param {Function|Array} mod optional modifier */ -ZipArchiveEntry.prototype.setGeneralPurposeBit = function(gpb) { - if (!(gpb instanceof GeneralPurposeBit)) { - throw new Error('invalid entry GeneralPurposeBit'); +DotObject.prototype.str = function (path, v, obj, mod) { + var ok = parsePath(path, this.separator).join(this.separator) + + if (path.indexOf(this.separator) !== -1) { + this._fill(ok.split(this.separator), obj, v, mod) + } else { + obj[path] = _process(v, mod) } - this.gpb = gpb; -}; + return obj +} /** - * Sets the internal file attributes of the entry. * - * @param attr + * Pick a value from an object using dot notation. + * + * Optionally remove the value + * + * @param {String} path + * @param {Object} obj + * @param {Boolean} remove */ -ZipArchiveEntry.prototype.setInternalAttributes = function(attr) { - this.inattr = attr; -}; +DotObject.prototype.pick = function (path, obj, remove, reindexArray) { + var i + var keys + var val + var key + var cp + keys = parsePath(path, this.separator) + for (i = 0; i < keys.length; i++) { + key = parseKey(keys[i], obj) + if (obj && typeof obj === 'object' && key in obj) { + if (i === keys.length - 1) { + if (remove) { + val = obj[key] + if (reindexArray && Array.isArray(obj)) { + obj.splice(key, 1) + } else { + delete obj[key] + } + if (Array.isArray(obj)) { + cp = keys.slice(0, -1).join('.') + if (this.cleanup.indexOf(cp) === -1) { + this.cleanup.push(cp) + } + } + return val + } else { + return obj[key] + } + } else { + obj = obj[key] + } + } else { + return undefined + } + } + if (remove && Array.isArray(obj)) { + obj = obj.filter(function (n) { + return n !== undefined + }) + } + return obj +} /** - * Sets the compression method of the entry. * - * @param method + * Delete value from an object using dot notation. + * + * @param {String} path + * @param {Object} obj + * @return {any} The removed value */ -ZipArchiveEntry.prototype.setMethod = function(method) { - if (method < 0) { - throw new Error('invalid entry compression method'); - } - - this.method = method; -}; +DotObject.prototype.delete = function (path, obj) { + return this.remove(path, obj, true) +} /** - * Sets the name of the entry. * - * @param name - * @param prependSlash + * Remove value from an object using dot notation. + * + * Will remove multiple items if path is an array. + * In this case array indexes will be retained until all + * removals have been processed. + * + * Use dot.delete() to automatically re-index arrays. + * + * @param {String|Array} path + * @param {Object} obj + * @param {Boolean} reindexArray + * @return {any} The removed value */ -ZipArchiveEntry.prototype.setName = function(name, prependSlash = false) { - name = normalizePath(name, false) - .replace(/^\w+:/, '') - .replace(/^(\.\.\/|\/)+/, ''); +DotObject.prototype.remove = function (path, obj, reindexArray) { + var i - if (prependSlash) { - name = `/${name}`; + this.cleanup = [] + if (Array.isArray(path)) { + for (i = 0; i < path.length; i++) { + this.pick(path[i], obj, true, reindexArray) + } + if (!reindexArray) { + this._cleanup(obj) + } + return obj + } else { + return this.pick(path, obj, true, reindexArray) } +} - if (Buffer.byteLength(name) !== name.length) { - this.getGeneralPurposeBit().useUTF8ForNames(true); +DotObject.prototype._cleanup = function (obj) { + var ret + var i + var keys + var root + if (this.cleanup.length) { + for (i = 0; i < this.cleanup.length; i++) { + keys = this.cleanup[i].split('.') + root = keys.splice(0, -1).join('.') + ret = root ? this.pick(root, obj) : obj + ret = ret[keys[0]].filter(function (v) { + return v !== undefined + }) + this.set(this.cleanup[i], ret, obj) + } + this.cleanup = [] } - - this.name = name; -}; +} /** - * Sets the platform on which the entry was made. + * Alias method for `dot.remove` * - * @param platform + * Note: this is not an alias for dot.delete() + * + * @param {String|Array} path + * @param {Object} obj + * @param {Boolean} reindexArray + * @return {any} The removed value */ -ZipArchiveEntry.prototype.setPlatform = function(platform) { - this.platform = platform; -}; +DotObject.prototype.del = DotObject.prototype.remove /** - * Sets the size of the entry. * - * @param size + * Move a property from one place to the other. + * + * If the source path does not exist (undefined) + * the target property will not be set. + * + * @param {String} source + * @param {String} target + * @param {Object} obj + * @param {Function|Array} mods + * @param {Boolean} merge */ -ZipArchiveEntry.prototype.setSize = function(size) { - if (size < 0) { - throw new Error('invalid entry size'); +DotObject.prototype.move = function (source, target, obj, mods, merge) { + if (typeof mods === 'function' || Array.isArray(mods)) { + this.set(target, _process(this.pick(source, obj, true), mods), obj, merge) + } else { + merge = mods + this.set(target, this.pick(source, obj, true), obj, merge) } - this.size = size; -}; + return obj +} /** - * Sets the time of the entry. * - * @param time - * @param forceLocalTime + * Transfer a property from one object to another object. + * + * If the source path does not exist (undefined) + * the property on the other object will not be set. + * + * @param {String} source + * @param {String} target + * @param {Object} obj1 + * @param {Object} obj2 + * @param {Function|Array} mods + * @param {Boolean} merge */ -ZipArchiveEntry.prototype.setTime = function(time, forceLocalTime) { - if (!(time instanceof Date)) { - throw new Error('invalid entry time'); +DotObject.prototype.transfer = function ( + source, + target, + obj1, + obj2, + mods, + merge +) { + if (typeof mods === 'function' || Array.isArray(mods)) { + this.set( + target, + _process(this.pick(source, obj1, true), mods), + obj2, + merge + ) + } else { + merge = mods + this.set(target, this.pick(source, obj1, true), obj2, merge) } - this.time = zipUtil.dateToDos(time, forceLocalTime); -}; + return obj2 +} /** - * Sets the UNIX file permissions for the entry. * - * @param mode - */ -ZipArchiveEntry.prototype.setUnixMode = function(mode) { - mode |= this.isDirectory() ? constants.S_IFDIR : constants.S_IFREG; - - var extattr = 0; - extattr |= (mode << constants.SHORT_SHIFT) | (this.isDirectory() ? constants.S_DOS_D : constants.S_DOS_A); - - this.setExternalAttributes(extattr); - this.mode = mode & constants.MODE_MASK; - this.platform = constants.PLATFORM_UNIX; -}; - -/** - * Sets the version of ZIP needed to extract this entry. + * Copy a property from one object to another object. * - * @param minver - */ -ZipArchiveEntry.prototype.setVersionNeededToExtract = function(minver) { - this.minver = minver; -}; - -/** - * Returns true if this entry represents a directory. + * If the source path does not exist (undefined) + * the property on the other object will not be set. * - * @returns {boolean} + * @param {String} source + * @param {String} target + * @param {Object} obj1 + * @param {Object} obj2 + * @param {Function|Array} mods + * @param {Boolean} merge */ -ZipArchiveEntry.prototype.isDirectory = function() { - return this.getName().slice(-1) === '/'; -}; +DotObject.prototype.copy = function (source, target, obj1, obj2, mods, merge) { + if (typeof mods === 'function' || Array.isArray(mods)) { + this.set( + target, + _process( + // clone what is picked + JSON.parse(JSON.stringify(this.pick(source, obj1, false))), + mods + ), + obj2, + merge + ) + } else { + merge = mods + this.set(target, this.pick(source, obj1, false), obj2, merge) + } -/** - * Returns true if this entry represents a unix symlink, - * in which case the entry's content contains the target path - * for the symlink. - * - * @returns {boolean} - */ -ZipArchiveEntry.prototype.isUnixSymlink = function() { - return (this.getUnixMode() & UnixStat.FILE_TYPE_FLAG) === UnixStat.LINK_FLAG; -}; + return obj2 +} /** - * Returns true if this entry is using the ZIP64 extension of ZIP. * - * @returns {boolean} + * Set a property on an object using dot notation. + * + * @param {String} path + * @param {any} val + * @param {Object} obj + * @param {Boolean} merge */ -ZipArchiveEntry.prototype.isZip64 = function() { - return this.csize > constants.ZIP64_MAGIC || this.size > constants.ZIP64_MAGIC; -}; - +DotObject.prototype.set = function (path, val, obj, merge) { + var i + var k + var keys + var key -/***/ }), + // Do not operate if the value is undefined. + if (typeof val === 'undefined') { + return obj + } + keys = parsePath(path, this.separator) -/***/ 55116: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + for (i = 0; i < keys.length; i++) { + key = keys[i] + if (i === keys.length - 1) { + if (merge && isObject(val) && isObject(obj[key])) { + for (k in val) { + if (hasOwnProperty.call(val, k)) { + obj[key][k] = val[k] + } + } + } else if (merge && Array.isArray(obj[key]) && Array.isArray(val)) { + for (var j = 0; j < val.length; j++) { + obj[keys[i]].push(val[j]) + } + } else { + obj[key] = val + } + } else if ( + // force the value to be an object + !hasOwnProperty.call(obj, key) || + (!isObject(obj[key]) && !Array.isArray(obj[key])) + ) { + // initialize as array if next key is numeric + if (/^\d+$/.test(keys[i + 1])) { + obj[key] = [] + } else { + obj[key] = {} + } + } + obj = obj[key] + } + return obj +} /** - * node-compress-commons * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT + * Transform an object + * + * Usage: + * + * var obj = { + * "id": 1, + * "some": { + * "thing": "else" + * } + * } + * + * var transform = { + * "id": "nr", + * "some.thing": "name" + * } + * + * var tgt = dot.transform(transform, obj) + * + * @param {Object} recipe Transform recipe + * @param {Object} obj Object to be transformed + * @param {Array} mods modifiers for the target */ -var inherits = (__nccwpck_require__(73837).inherits); -var crc32 = __nccwpck_require__(6075); -var {CRC32Stream} = __nccwpck_require__(31593); -var {DeflateCRC32Stream} = __nccwpck_require__(31593); +DotObject.prototype.transform = function (recipe, obj, tgt) { + obj = obj || {} + tgt = tgt || {} + Object.keys(recipe).forEach( + function (key) { + this.set(recipe[key], this.pick(key, obj), tgt) + }.bind(this) + ) + return tgt +} -var ArchiveOutputStream = __nccwpck_require__(98985); -var ZipArchiveEntry = __nccwpck_require__(54970); -var GeneralPurposeBit = __nccwpck_require__(84611); +/** + * + * Convert object to dotted-key/value pair + * + * Usage: + * + * var tgt = dot.dot(obj) + * + * or + * + * var tgt = {} + * dot.dot(obj, tgt) + * + * @param {Object} obj source object + * @param {Object} tgt target object + * @param {Array} path path array (internal) + */ +DotObject.prototype.dot = function (obj, tgt, path) { + tgt = tgt || {} + path = path || [] + var isArray = Array.isArray(obj) -var constants = __nccwpck_require__(90114); -var util = __nccwpck_require__(67592); -var zipUtil = __nccwpck_require__(19195); + Object.keys(obj).forEach( + function (key) { + var index = isArray && this.useBrackets ? '[' + key + ']' : key + if ( + isArrayOrObject(obj[key]) && + ((isObject(obj[key]) && !isEmptyObject(obj[key])) || + (Array.isArray(obj[key]) && !this.keepArray && obj[key].length !== 0)) + ) { + if (isArray && this.useBrackets) { + var previousKey = path[path.length - 1] || '' + return this.dot( + obj[key], + tgt, + path.slice(0, -1).concat(previousKey + index) + ) + } else { + return this.dot(obj[key], tgt, path.concat(index)) + } + } else { + if (isArray && this.useBrackets) { + tgt[path.join(this.separator).concat('[' + key + ']')] = obj[key] + } else { + tgt[path.concat(index).join(this.separator)] = obj[key] + } + } + }.bind(this) + ) + return tgt +} -var ZipArchiveOutputStream = module.exports = function(options) { - if (!(this instanceof ZipArchiveOutputStream)) { - return new ZipArchiveOutputStream(options); - } +DotObject.pick = wrap('pick') +DotObject.move = wrap('move') +DotObject.transfer = wrap('transfer') +DotObject.transform = wrap('transform') +DotObject.copy = wrap('copy') +DotObject.object = wrap('object') +DotObject.str = wrap('str') +DotObject.set = wrap('set') +DotObject.delete = wrap('delete') +DotObject.del = DotObject.remove = wrap('remove') +DotObject.dot = wrap('dot'); +['override', 'overwrite'].forEach(function (prop) { + Object.defineProperty(DotObject, prop, { + get: function () { + return dotDefault.override + }, + set: function (val) { + dotDefault.override = !!val + } + }) +}); +['useArray', 'keepArray', 'useBrackets'].forEach(function (prop) { + Object.defineProperty(DotObject, prop, { + get: function () { + return dotDefault[prop] + }, + set: function (val) { + dotDefault[prop] = val + } + }) +}) - options = this.options = this._defaults(options); +DotObject._process = _process - ArchiveOutputStream.call(this, options); +module.exports = DotObject - this._entry = null; - this._entries = []; - this._archive = { - centralLength: 0, - centralOffset: 0, - comment: '', - finish: false, - finished: false, - processing: false, - forceZip64: options.forceZip64, - forceLocalTime: options.forceLocalTime - }; -}; -inherits(ZipArchiveOutputStream, ArchiveOutputStream); +/***/ }), -ZipArchiveOutputStream.prototype._afterAppend = function(ae) { - this._entries.push(ae); +/***/ 81205: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (ae.getGeneralPurposeBit().usesDataDescriptor()) { - this._writeDataDescriptor(ae); - } +var once = __nccwpck_require__(1223); - this._archive.processing = false; - this._entry = null; +var noop = function() {}; - if (this._archive.finish && !this._archive.finished) { - this._finish(); - } +var isRequest = function(stream) { + return stream.setHeader && typeof stream.abort === 'function'; }; -ZipArchiveOutputStream.prototype._appendBuffer = function(ae, source, callback) { - if (source.length === 0) { - ae.setMethod(constants.METHOD_STORED); - } +var isChildProcess = function(stream) { + return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 +}; - var method = ae.getMethod(); +var eos = function(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; - if (method === constants.METHOD_STORED) { - ae.setSize(source.length); - ae.setCompressedSize(source.length); - ae.setCrc(crc32.unsigned(source)); - } + callback = once(callback || noop); - this._writeLocalFileHeader(ae); + var ws = stream._writableState; + var rs = stream._readableState; + var readable = opts.readable || (opts.readable !== false && stream.readable); + var writable = opts.writable || (opts.writable !== false && stream.writable); + var cancelled = false; - if (method === constants.METHOD_STORED) { - this.write(source); - this._afterAppend(ae); - callback(null, ae); - return; - } else if (method === constants.METHOD_DEFLATED) { - this._smartStream(ae, callback).end(source); - return; - } else { - callback(new Error('compression method ' + method + ' not implemented')); - return; - } -}; + var onlegacyfinish = function() { + if (!stream.writable) onfinish(); + }; -ZipArchiveOutputStream.prototype._appendStream = function(ae, source, callback) { - ae.getGeneralPurposeBit().useDataDescriptor(true); - ae.setVersionNeededToExtract(constants.MIN_VERSION_DATA_DESCRIPTOR); + var onfinish = function() { + writable = false; + if (!readable) callback.call(stream); + }; - this._writeLocalFileHeader(ae); + var onend = function() { + readable = false; + if (!writable) callback.call(stream); + }; - var smart = this._smartStream(ae, callback); - source.once('error', function(err) { - smart.emit('error', err); - smart.end(); - }) - source.pipe(smart); -}; + var onexit = function(exitCode) { + callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); + }; -ZipArchiveOutputStream.prototype._defaults = function(o) { - if (typeof o !== 'object') { - o = {}; - } + var onerror = function(err) { + callback.call(stream, err); + }; - if (typeof o.zlib !== 'object') { - o.zlib = {}; - } + var onclose = function() { + process.nextTick(onclosenexttick); + }; - if (typeof o.zlib.level !== 'number') { - o.zlib.level = constants.ZLIB_BEST_SPEED; - } + var onclosenexttick = function() { + if (cancelled) return; + if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close')); + if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close')); + }; - o.forceZip64 = !!o.forceZip64; - o.forceLocalTime = !!o.forceLocalTime; + var onrequest = function() { + stream.req.on('finish', onfinish); + }; - return o; + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest(); + else stream.on('request', onrequest); + } else if (writable && !ws) { // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + + if (isChildProcess(stream)) stream.on('exit', onexit); + + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + + return function() { + cancelled = true; + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('exit', onexit); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; }; -ZipArchiveOutputStream.prototype._finish = function() { - this._archive.centralOffset = this.offset; +module.exports = eos; - this._entries.forEach(function(ae) { - this._writeCentralFileHeader(ae); - }.bind(this)); - this._archive.centralLength = this.offset - this._archive.centralOffset; +/***/ }), - if (this.isZip64()) { - this._writeCentralDirectoryZip64(); - } +/***/ 64334: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this._writeCentralDirectoryEnd(); +var CombinedStream = __nccwpck_require__(85443); +var util = __nccwpck_require__(73837); +var path = __nccwpck_require__(71017); +var http = __nccwpck_require__(13685); +var https = __nccwpck_require__(95687); +var parseUrl = (__nccwpck_require__(57310).parse); +var fs = __nccwpck_require__(57147); +var Stream = (__nccwpck_require__(12781).Stream); +var mime = __nccwpck_require__(43583); +var asynckit = __nccwpck_require__(14812); +var populate = __nccwpck_require__(17142); - this._archive.processing = false; - this._archive.finish = true; - this._archive.finished = true; - this.end(); -}; +// Public API +module.exports = FormData; -ZipArchiveOutputStream.prototype._normalizeEntry = function(ae) { - if (ae.getMethod() === -1) { - ae.setMethod(constants.METHOD_DEFLATED); +// make it a Stream +util.inherits(FormData, CombinedStream); + +/** + * Create readable "multipart/form-data" streams. + * Can be used to submit forms + * and file uploads to other web applications. + * + * @constructor + * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream + */ +function FormData(options) { + if (!(this instanceof FormData)) { + return new FormData(options); } - if (ae.getMethod() === constants.METHOD_DEFLATED) { - ae.getGeneralPurposeBit().useDataDescriptor(true); - ae.setVersionNeededToExtract(constants.MIN_VERSION_DATA_DESCRIPTOR); + this._overheadLength = 0; + this._valueLength = 0; + this._valuesToMeasure = []; + + CombinedStream.call(this); + + options = options || {}; + for (var option in options) { + this[option] = options[option]; } +} - if (ae.getTime() === -1) { - ae.setTime(new Date(), this._archive.forceLocalTime); +FormData.LINE_BREAK = '\r\n'; +FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; + +FormData.prototype.append = function(field, value, options) { + + options = options || {}; + + // allow filename as single option + if (typeof options == 'string') { + options = {filename: options}; } - ae._offsets = { - file: 0, - data: 0, - contents: 0, - }; -}; + var append = CombinedStream.prototype.append.bind(this); -ZipArchiveOutputStream.prototype._smartStream = function(ae, callback) { - var deflate = ae.getMethod() === constants.METHOD_DEFLATED; - var process = deflate ? new DeflateCRC32Stream(this.options.zlib) : new CRC32Stream(); - var error = null; + // all that streamy business can't handle numbers + if (typeof value == 'number') { + value = '' + value; + } - function handleStuff() { - var digest = process.digest().readUInt32BE(0); - ae.setCrc(digest); - ae.setSize(process.size()); - ae.setCompressedSize(process.size(true)); - this._afterAppend(ae); - callback(error, ae); + // https://github.com/felixge/node-form-data/issues/38 + if (util.isArray(value)) { + // Please convert your array into string + // the way web server expects it + this._error(new Error('Arrays are not supported.')); + return; } - process.once('end', handleStuff.bind(this)); - process.once('error', function(err) { - error = err; - }); + var header = this._multiPartHeader(field, value, options); + var footer = this._multiPartFooter(); - process.pipe(this, { end: false }); + append(header); + append(value); + append(footer); - return process; + // pass along options.knownLength + this._trackLength(header, value, options); }; -ZipArchiveOutputStream.prototype._writeCentralDirectoryEnd = function() { - var records = this._entries.length; - var size = this._archive.centralLength; - var offset = this._archive.centralOffset; +FormData.prototype._trackLength = function(header, value, options) { + var valueLength = 0; - if (this.isZip64()) { - records = constants.ZIP64_MAGIC_SHORT; - size = constants.ZIP64_MAGIC; - offset = constants.ZIP64_MAGIC; + // used w/ getLengthSync(), when length is known. + // e.g. for streaming directly from a remote server, + // w/ a known file a size, and not wanting to wait for + // incoming file to finish to get its size. + if (options.knownLength != null) { + valueLength += +options.knownLength; + } else if (Buffer.isBuffer(value)) { + valueLength = value.length; + } else if (typeof value === 'string') { + valueLength = Buffer.byteLength(value); } - // signature - this.write(zipUtil.getLongBytes(constants.SIG_EOCD)); - - // disk numbers - this.write(constants.SHORT_ZERO); - this.write(constants.SHORT_ZERO); + this._valueLength += valueLength; - // number of entries - this.write(zipUtil.getShortBytes(records)); - this.write(zipUtil.getShortBytes(records)); + // @check why add CRLF? does this account for custom/multiple CRLFs? + this._overheadLength += + Buffer.byteLength(header) + + FormData.LINE_BREAK.length; - // length and location of CD - this.write(zipUtil.getLongBytes(size)); - this.write(zipUtil.getLongBytes(offset)); + // empty or either doesn't have path or not an http response or not a stream + if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) && !(value instanceof Stream))) { + return; + } - // archive comment - var comment = this.getComment(); - var commentLength = Buffer.byteLength(comment); - this.write(zipUtil.getShortBytes(commentLength)); - this.write(comment); + // no need to bother with the length + if (!options.knownLength) { + this._valuesToMeasure.push(value); + } }; -ZipArchiveOutputStream.prototype._writeCentralDirectoryZip64 = function() { - // signature - this.write(zipUtil.getLongBytes(constants.SIG_ZIP64_EOCD)); +FormData.prototype._lengthRetriever = function(value, callback) { - // size of the ZIP64 EOCD record - this.write(zipUtil.getEightBytes(44)); + if (value.hasOwnProperty('fd')) { - // version made by - this.write(zipUtil.getShortBytes(constants.MIN_VERSION_ZIP64)); + // take read range into a account + // `end` = Infinity –> read file till the end + // + // TODO: Looks like there is bug in Node fs.createReadStream + // it doesn't respect `end` options without `start` options + // Fix it when node fixes it. + // https://github.com/joyent/node/issues/7819 + if (value.end != undefined && value.end != Infinity && value.start != undefined) { - // version to extract - this.write(zipUtil.getShortBytes(constants.MIN_VERSION_ZIP64)); + // when end specified + // no need to calculate range + // inclusive, starts with 0 + callback(null, value.end + 1 - (value.start ? value.start : 0)); - // disk numbers - this.write(constants.LONG_ZERO); - this.write(constants.LONG_ZERO); + // not that fast snoopy + } else { + // still need to fetch file size from fs + fs.stat(value.path, function(err, stat) { - // number of entries - this.write(zipUtil.getEightBytes(this._entries.length)); - this.write(zipUtil.getEightBytes(this._entries.length)); + var fileSize; - // length and location of CD - this.write(zipUtil.getEightBytes(this._archive.centralLength)); - this.write(zipUtil.getEightBytes(this._archive.centralOffset)); + if (err) { + callback(err); + return; + } - // extensible data sector - // not implemented at this time - - // end of central directory locator - this.write(zipUtil.getLongBytes(constants.SIG_ZIP64_EOCD_LOC)); + // update final size based on the range options + fileSize = stat.size - (value.start ? value.start : 0); + callback(null, fileSize); + }); + } - // disk number holding the ZIP64 EOCD record - this.write(constants.LONG_ZERO); + // or http response + } else if (value.hasOwnProperty('httpVersion')) { + callback(null, +value.headers['content-length']); - // relative offset of the ZIP64 EOCD record - this.write(zipUtil.getEightBytes(this._archive.centralOffset + this._archive.centralLength)); + // or request stream http://github.com/mikeal/request + } else if (value.hasOwnProperty('httpModule')) { + // wait till response come back + value.on('response', function(response) { + value.pause(); + callback(null, +response.headers['content-length']); + }); + value.resume(); - // total number of disks - this.write(zipUtil.getLongBytes(1)); + // something else + } else { + callback('Unknown stream'); + } }; -ZipArchiveOutputStream.prototype._writeCentralFileHeader = function(ae) { - var gpb = ae.getGeneralPurposeBit(); - var method = ae.getMethod(); - var offsets = ae._offsets; +FormData.prototype._multiPartHeader = function(field, value, options) { + // custom header specified (as string)? + // it becomes responsible for boundary + // (e.g. to handle extra CRLFs on .NET servers) + if (typeof options.header == 'string') { + return options.header; + } - var size = ae.getSize(); - var compressedSize = ae.getCompressedSize(); + var contentDisposition = this._getContentDisposition(value, options); + var contentType = this._getContentType(value, options); - if (ae.isZip64() || offsets.file > constants.ZIP64_MAGIC) { - size = constants.ZIP64_MAGIC; - compressedSize = constants.ZIP64_MAGIC; + var contents = ''; + var headers = { + // add custom disposition as third element or keep it two elements if not + 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), + // if no content type. allow it to be empty array + 'Content-Type': [].concat(contentType || []) + }; - ae.setVersionNeededToExtract(constants.MIN_VERSION_ZIP64); + // allow custom headers. + if (typeof options.header == 'object') { + populate(headers, options.header); + } - var extraBuf = Buffer.concat([ - zipUtil.getShortBytes(constants.ZIP64_EXTRA_ID), - zipUtil.getShortBytes(24), - zipUtil.getEightBytes(ae.getSize()), - zipUtil.getEightBytes(ae.getCompressedSize()), - zipUtil.getEightBytes(offsets.file) - ], 28); + var header; + for (var prop in headers) { + if (!headers.hasOwnProperty(prop)) continue; + header = headers[prop]; - ae.setExtra(extraBuf); + // skip nullish headers. + if (header == null) { + continue; + } + + // convert all headers to arrays. + if (!Array.isArray(header)) { + header = [header]; + } + + // add non-empty headers. + if (header.length) { + contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; + } } - // signature - this.write(zipUtil.getLongBytes(constants.SIG_CFH)); + return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; +}; - // version made by - this.write(zipUtil.getShortBytes((ae.getPlatform() << 8) | constants.VERSION_MADEBY)); +FormData.prototype._getContentDisposition = function(value, options) { - // version to extract and general bit flag - this.write(zipUtil.getShortBytes(ae.getVersionNeededToExtract())); - this.write(gpb.encode()); + var filename + , contentDisposition + ; - // compression method - this.write(zipUtil.getShortBytes(method)); + if (typeof options.filepath === 'string') { + // custom filepath for relative paths + filename = path.normalize(options.filepath).replace(/\\/g, '/'); + } else if (options.filename || value.name || value.path) { + // custom filename take precedence + // formidable and the browser add a name property + // fs- and request- streams have path property + filename = path.basename(options.filename || value.name || value.path); + } else if (value.readable && value.hasOwnProperty('httpVersion')) { + // or try http response + filename = path.basename(value.client._httpMessage.path || ''); + } - // datetime - this.write(zipUtil.getLongBytes(ae.getTimeDos())); + if (filename) { + contentDisposition = 'filename="' + filename + '"'; + } - // crc32 checksum - this.write(zipUtil.getLongBytes(ae.getCrc())); + return contentDisposition; +}; - // sizes - this.write(zipUtil.getLongBytes(compressedSize)); - this.write(zipUtil.getLongBytes(size)); +FormData.prototype._getContentType = function(value, options) { - var name = ae.getName(); - var comment = ae.getComment(); - var extra = ae.getCentralDirectoryExtra(); + // use custom content-type above all + var contentType = options.contentType; - if (gpb.usesUTF8ForNames()) { - name = Buffer.from(name); - comment = Buffer.from(comment); + // or try `name` from formidable, browser + if (!contentType && value.name) { + contentType = mime.lookup(value.name); } - // name length - this.write(zipUtil.getShortBytes(name.length)); + // or try `path` from fs-, request- streams + if (!contentType && value.path) { + contentType = mime.lookup(value.path); + } - // extra length - this.write(zipUtil.getShortBytes(extra.length)); + // or if it's http-reponse + if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { + contentType = value.headers['content-type']; + } - // comments length - this.write(zipUtil.getShortBytes(comment.length)); + // or guess it from the filepath or filename + if (!contentType && (options.filepath || options.filename)) { + contentType = mime.lookup(options.filepath || options.filename); + } - // disk number start - this.write(constants.SHORT_ZERO); + // fallback to the default content type if `value` is not simple value + if (!contentType && typeof value == 'object') { + contentType = FormData.DEFAULT_CONTENT_TYPE; + } - // internal attributes - this.write(zipUtil.getShortBytes(ae.getInternalAttributes())); + return contentType; +}; - // external attributes - this.write(zipUtil.getLongBytes(ae.getExternalAttributes())); +FormData.prototype._multiPartFooter = function() { + return function(next) { + var footer = FormData.LINE_BREAK; - // relative offset of LFH - if (offsets.file > constants.ZIP64_MAGIC) { - this.write(zipUtil.getLongBytes(constants.ZIP64_MAGIC)); - } else { - this.write(zipUtil.getLongBytes(offsets.file)); + var lastPart = (this._streams.length === 0); + if (lastPart) { + footer += this._lastBoundary(); + } + + next(footer); + }.bind(this); +}; + +FormData.prototype._lastBoundary = function() { + return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; +}; + +FormData.prototype.getHeaders = function(userHeaders) { + var header; + var formHeaders = { + 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() + }; + + for (header in userHeaders) { + if (userHeaders.hasOwnProperty(header)) { + formHeaders[header.toLowerCase()] = userHeaders[header]; + } } - // name - this.write(name); + return formHeaders; +}; - // extra - this.write(extra); +FormData.prototype.setBoundary = function(boundary) { + this._boundary = boundary; +}; - // comment - this.write(comment); +FormData.prototype.getBoundary = function() { + if (!this._boundary) { + this._generateBoundary(); + } + + return this._boundary; }; -ZipArchiveOutputStream.prototype._writeDataDescriptor = function(ae) { - // signature - this.write(zipUtil.getLongBytes(constants.SIG_DD)); +FormData.prototype.getBuffer = function() { + var dataBuffer = new Buffer.alloc( 0 ); + var boundary = this.getBoundary(); - // crc32 checksum - this.write(zipUtil.getLongBytes(ae.getCrc())); + // Create the form content. Add Line breaks to the end of data. + for (var i = 0, len = this._streams.length; i < len; i++) { + if (typeof this._streams[i] !== 'function') { - // sizes - if (ae.isZip64()) { - this.write(zipUtil.getEightBytes(ae.getCompressedSize())); - this.write(zipUtil.getEightBytes(ae.getSize())); - } else { - this.write(zipUtil.getLongBytes(ae.getCompressedSize())); - this.write(zipUtil.getLongBytes(ae.getSize())); + // Add content to the buffer. + if(Buffer.isBuffer(this._streams[i])) { + dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]); + }else { + dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]); + } + + // Add break after content. + if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) { + dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData.LINE_BREAK)] ); + } + } } + + // Add the footer and return the Buffer object. + return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] ); }; -ZipArchiveOutputStream.prototype._writeLocalFileHeader = function(ae) { - var gpb = ae.getGeneralPurposeBit(); - var method = ae.getMethod(); - var name = ae.getName(); - var extra = ae.getLocalFileDataExtra(); +FormData.prototype._generateBoundary = function() { + // This generates a 50 character boundary similar to those used by Firefox. + // They are optimized for boyer-moore parsing. + var boundary = '--------------------------'; + for (var i = 0; i < 24; i++) { + boundary += Math.floor(Math.random() * 10).toString(16); + } - if (ae.isZip64()) { - gpb.useDataDescriptor(true); - ae.setVersionNeededToExtract(constants.MIN_VERSION_ZIP64); + this._boundary = boundary; +}; + +// Note: getLengthSync DOESN'T calculate streams length +// As workaround one can calculate file size manually +// and add it as knownLength option +FormData.prototype.getLengthSync = function() { + var knownLength = this._overheadLength + this._valueLength; + + // Don't get confused, there are 3 "internal" streams for each keyval pair + // so it basically checks if there is any value added to the form + if (this._streams.length) { + knownLength += this._lastBoundary().length; } - if (gpb.usesUTF8ForNames()) { - name = Buffer.from(name); + // https://github.com/form-data/form-data/issues/40 + if (!this.hasKnownLength()) { + // Some async length retrievers are present + // therefore synchronous length calculation is false. + // Please use getLength(callback) to get proper length + this._error(new Error('Cannot calculate proper length in synchronous way.')); } - ae._offsets.file = this.offset; + return knownLength; +}; - // signature - this.write(zipUtil.getLongBytes(constants.SIG_LFH)); +// Public API to check if length of added values is known +// https://github.com/form-data/form-data/issues/196 +// https://github.com/form-data/form-data/issues/262 +FormData.prototype.hasKnownLength = function() { + var hasKnownLength = true; - // version to extract and general bit flag - this.write(zipUtil.getShortBytes(ae.getVersionNeededToExtract())); - this.write(gpb.encode()); + if (this._valuesToMeasure.length) { + hasKnownLength = false; + } - // compression method - this.write(zipUtil.getShortBytes(method)); + return hasKnownLength; +}; - // datetime - this.write(zipUtil.getLongBytes(ae.getTimeDos())); +FormData.prototype.getLength = function(cb) { + var knownLength = this._overheadLength + this._valueLength; - ae._offsets.data = this.offset; + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } - // crc32 checksum and sizes - if (gpb.usesDataDescriptor()) { - this.write(constants.LONG_ZERO); - this.write(constants.LONG_ZERO); - this.write(constants.LONG_ZERO); - } else { - this.write(zipUtil.getLongBytes(ae.getCrc())); - this.write(zipUtil.getLongBytes(ae.getCompressedSize())); - this.write(zipUtil.getLongBytes(ae.getSize())); + if (!this._valuesToMeasure.length) { + process.nextTick(cb.bind(this, null, knownLength)); + return; } - // name length - this.write(zipUtil.getShortBytes(name.length)); + asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { + if (err) { + cb(err); + return; + } - // extra length - this.write(zipUtil.getShortBytes(extra.length)); + values.forEach(function(length) { + knownLength += length; + }); - // name - this.write(name); + cb(null, knownLength); + }); +}; - // extra - this.write(extra); +FormData.prototype.submit = function(params, cb) { + var request + , options + , defaults = {method: 'post'} + ; - ae._offsets.contents = this.offset; -}; + // parse provided url if it's string + // or treat it as options object + if (typeof params == 'string') { -ZipArchiveOutputStream.prototype.getComment = function(comment) { - return this._archive.comment !== null ? this._archive.comment : ''; -}; + params = parseUrl(params); + options = populate({ + port: params.port, + path: params.pathname, + host: params.hostname, + protocol: params.protocol + }, defaults); -ZipArchiveOutputStream.prototype.isZip64 = function() { - return this._archive.forceZip64 || this._entries.length > constants.ZIP64_MAGIC_SHORT || this._archive.centralLength > constants.ZIP64_MAGIC || this._archive.centralOffset > constants.ZIP64_MAGIC; -}; + // use custom params + } else { -ZipArchiveOutputStream.prototype.setComment = function(comment) { - this._archive.comment = comment; -}; + options = populate(params, defaults); + // if no port provided use default one + if (!options.port) { + options.port = options.protocol == 'https:' ? 443 : 80; + } + } + // put that good code in getHeaders to some use + options.headers = this.getHeaders(params.headers); -/***/ }), + // https if specified, fallback to http in any other case + if (options.protocol == 'https:') { + request = https.request(options); + } else { + request = http.request(options); + } -/***/ 21563: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // get content length and fire away + this.getLength(function(err, length) { + if (err && err !== 'Unknown stream') { + this._error(err); + return; + } -/** - * node-compress-commons - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT - */ -module.exports = { - ArchiveEntry: __nccwpck_require__(89766), - ZipArchiveEntry: __nccwpck_require__(54970), - ArchiveOutputStream: __nccwpck_require__(98985), - ZipArchiveOutputStream: __nccwpck_require__(55116) -}; + // add content length + if (length) { + request.setHeader('Content-Length', length); + } -/***/ }), + this.pipe(request); + if (cb) { + var onResponse; -/***/ 67592: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var callback = function (error, responce) { + request.removeListener('error', callback); + request.removeListener('response', onResponse); -/** - * node-compress-commons - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT - */ -var Stream = (__nccwpck_require__(12781).Stream); -var PassThrough = (__nccwpck_require__(84123).PassThrough); + return cb.call(this, error, responce); + }; -var util = module.exports = {}; + onResponse = callback.bind(this, null); -util.isStream = function(source) { - return source instanceof Stream; -}; + request.on('error', callback); + request.on('response', onResponse); + } + }.bind(this)); -util.normalizeInputSource = function(source) { - if (source === null) { - return Buffer.alloc(0); - } else if (typeof source === 'string') { - return Buffer.from(source); - } else if (util.isStream(source) && !source._readableState) { - var normalized = new PassThrough(); - source.pipe(normalized); + return request; +}; - return normalized; +FormData.prototype._error = function(err) { + if (!this.error) { + this.error = err; + this.pause(); + this.emit('error', err); } +}; - return source; +FormData.prototype.toString = function () { + return '[object FormData]'; }; + /***/ }), -/***/ 42360: +/***/ 17142: /***/ ((module) => { -module.exports = function (xs, fn) { - var res = []; - for (var i = 0; i < xs.length; i++) { - var x = fn(xs[i], i); - if (isArray(x)) res.push.apply(res, x); - else res.push(x); - } - return res; -}; +// populates missing values +module.exports = function(dst, src) { -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; + Object.keys(src).forEach(function(prop) + { + dst[prop] = dst[prop] || src[prop]; + }); + + return dst; }; /***/ }), -/***/ 32137: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 73186: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. +module.exports = (__nccwpck_require__(57147).constants) || __nccwpck_require__(22057) -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(arg) { - if (Array.isArray) { - return Array.isArray(arg); - } - return objectToString(arg) === '[object Array]'; -} -exports.isArray = isArray; +/***/ }), -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; +/***/ 46863: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; +module.exports = realpath +realpath.realpath = realpath +realpath.sync = realpathSync +realpath.realpathSync = realpathSync +realpath.monkeypatch = monkeypatch +realpath.unmonkeypatch = unmonkeypatch -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; +var fs = __nccwpck_require__(57147) +var origRealpath = fs.realpath +var origRealpathSync = fs.realpathSync -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; +var version = process.version +var ok = /^v[0-5]\./.test(version) +var old = __nccwpck_require__(71734) -function isSymbol(arg) { - return typeof arg === 'symbol'; +function newError (er) { + return er && er.syscall === 'realpath' && ( + er.code === 'ELOOP' || + er.code === 'ENOMEM' || + er.code === 'ENAMETOOLONG' + ) } -exports.isSymbol = isSymbol; -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; +function realpath (p, cache, cb) { + if (ok) { + return origRealpath(p, cache, cb) + } -function isRegExp(re) { - return objectToString(re) === '[object RegExp]'; + if (typeof cache === 'function') { + cb = cache + cache = null + } + origRealpath(p, cache, function (er, result) { + if (newError(er)) { + old.realpath(p, cache, cb) + } else { + cb(er, result) + } + }) } -exports.isRegExp = isRegExp; -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; +function realpathSync (p, cache) { + if (ok) { + return origRealpathSync(p, cache) + } -function isDate(d) { - return objectToString(d) === '[object Date]'; + try { + return origRealpathSync(p, cache) + } catch (er) { + if (newError(er)) { + return old.realpathSync(p, cache) + } else { + throw er + } + } } -exports.isDate = isDate; -function isError(e) { - return (objectToString(e) === '[object Error]' || e instanceof Error); +function monkeypatch () { + fs.realpath = realpath + fs.realpathSync = realpathSync } -exports.isError = isError; -function isFunction(arg) { - return typeof arg === 'function'; +function unmonkeypatch () { + fs.realpath = origRealpath + fs.realpathSync = origRealpathSync } -exports.isFunction = isFunction; -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; -exports.isBuffer = __nccwpck_require__(14300).Buffer.isBuffer; +/***/ }), -function objectToString(o) { - return Object.prototype.toString.call(o); -} +/***/ 71734: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. -/***/ }), +var pathModule = __nccwpck_require__(71017); +var isWindows = process.platform === 'win32'; +var fs = __nccwpck_require__(57147); -/***/ 13080: -/***/ ((__unused_webpack_module, exports) => { +// JavaScript implementation of realpath, ported from node pre-v6 -/*! crc32.js (C) 2014-present SheetJS -- http://sheetjs.com */ -/* vim: set ts=2: */ -/*exported CRC32 */ -var CRC32; -(function (factory) { - /*jshint ignore:start */ - /*eslint-disable */ - if(typeof DO_NOT_EXPORT_CRC === 'undefined') { - if(true) { - factory(exports); - } else {} - } else { - factory(CRC32 = {}); - } - /*eslint-enable */ - /*jshint ignore:end */ -}(function(CRC32) { -CRC32.version = '1.2.2'; -/*global Int32Array */ -function signed_crc_table() { - var c = 0, table = new Array(256); +var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); - for(var n =0; n != 256; ++n){ - c = n; - c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); - c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); - c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); - c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); - c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); - c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); - c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); - c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); - table[n] = c; - } +function rethrow() { + // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and + // is fairly slow to generate. + var callback; + if (DEBUG) { + var backtrace = new Error; + callback = debugCallback; + } else + callback = missingCallback; - return typeof Int32Array !== 'undefined' ? new Int32Array(table) : table; -} + return callback; -var T0 = signed_crc_table(); -function slice_by_16_tables(T) { - var c = 0, v = 0, n = 0, table = typeof Int32Array !== 'undefined' ? new Int32Array(4096) : new Array(4096) ; + function debugCallback(err) { + if (err) { + backtrace.message = err.message; + err = backtrace; + missingCallback(err); + } + } - for(n = 0; n != 256; ++n) table[n] = T[n]; - for(n = 0; n != 256; ++n) { - v = T[n]; - for(c = 256 + n; c < 4096; c += 256) v = table[c] = (v >>> 8) ^ T[v & 0xFF]; - } - var out = []; - for(n = 1; n != 16; ++n) out[n - 1] = typeof Int32Array !== 'undefined' ? table.subarray(n * 256, n * 256 + 256) : table.slice(n * 256, n * 256 + 256); - return out; -} -var TT = slice_by_16_tables(T0); -var T1 = TT[0], T2 = TT[1], T3 = TT[2], T4 = TT[3], T5 = TT[4]; -var T6 = TT[5], T7 = TT[6], T8 = TT[7], T9 = TT[8], Ta = TT[9]; -var Tb = TT[10], Tc = TT[11], Td = TT[12], Te = TT[13], Tf = TT[14]; -function crc32_bstr(bstr, seed) { - var C = seed ^ -1; - for(var i = 0, L = bstr.length; i < L;) C = (C>>>8) ^ T0[(C^bstr.charCodeAt(i++))&0xFF]; - return ~C; + function missingCallback(err) { + if (err) { + if (process.throwDeprecation) + throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs + else if (!process.noDeprecation) { + var msg = 'fs: missing callback ' + (err.stack || err.message); + if (process.traceDeprecation) + console.trace(msg); + else + console.error(msg); + } + } + } } -function crc32_buf(B, seed) { - var C = seed ^ -1, L = B.length - 15, i = 0; - for(; i < L;) C = - Tf[B[i++] ^ (C & 255)] ^ - Te[B[i++] ^ ((C >> 8) & 255)] ^ - Td[B[i++] ^ ((C >> 16) & 255)] ^ - Tc[B[i++] ^ (C >>> 24)] ^ - Tb[B[i++]] ^ Ta[B[i++]] ^ T9[B[i++]] ^ T8[B[i++]] ^ - T7[B[i++]] ^ T6[B[i++]] ^ T5[B[i++]] ^ T4[B[i++]] ^ - T3[B[i++]] ^ T2[B[i++]] ^ T1[B[i++]] ^ T0[B[i++]]; - L += 15; - while(i < L) C = (C>>>8) ^ T0[(C^B[i++])&0xFF]; - return ~C; +function maybeCallback(cb) { + return typeof cb === 'function' ? cb : rethrow(); } -function crc32_str(str, seed) { - var C = seed ^ -1; - for(var i = 0, L = str.length, c = 0, d = 0; i < L;) { - c = str.charCodeAt(i++); - if(c < 0x80) { - C = (C>>>8) ^ T0[(C^c)&0xFF]; - } else if(c < 0x800) { - C = (C>>>8) ^ T0[(C ^ (192|((c>>6)&31)))&0xFF]; - C = (C>>>8) ^ T0[(C ^ (128|(c&63)))&0xFF]; - } else if(c >= 0xD800 && c < 0xE000) { - c = (c&1023)+64; d = str.charCodeAt(i++)&1023; - C = (C>>>8) ^ T0[(C ^ (240|((c>>8)&7)))&0xFF]; - C = (C>>>8) ^ T0[(C ^ (128|((c>>2)&63)))&0xFF]; - C = (C>>>8) ^ T0[(C ^ (128|((d>>6)&15)|((c&3)<<4)))&0xFF]; - C = (C>>>8) ^ T0[(C ^ (128|(d&63)))&0xFF]; - } else { - C = (C>>>8) ^ T0[(C ^ (224|((c>>12)&15)))&0xFF]; - C = (C>>>8) ^ T0[(C ^ (128|((c>>6)&63)))&0xFF]; - C = (C>>>8) ^ T0[(C ^ (128|(c&63)))&0xFF]; - } - } - return ~C; -} -CRC32.table = T0; -// $FlowIgnore -CRC32.bstr = crc32_bstr; -// $FlowIgnore -CRC32.buf = crc32_buf; -// $FlowIgnore -CRC32.str = crc32_str; -})); +var normalize = pathModule.normalize; +// Regexp that finds the next partion of a (partial) path +// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] +if (isWindows) { + var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; +} else { + var nextPartRe = /(.*?)(?:[\/]+|$)/g; +} -/***/ }), +// Regex to find the device root, including trailing slash. E.g. 'c:\\'. +if (isWindows) { + var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; +} else { + var splitRootRe = /^[\/]*/; +} -/***/ 81629: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +exports.realpathSync = function realpathSync(p, cache) { + // make p is absolute + p = pathModule.resolve(p); -"use strict"; -/** - * node-crc32-stream - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-crc32-stream/blob/master/LICENSE-MIT - */ + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return cache[p]; + } - + var original = p, + seenLinks = {}, + knownHard = {}; -const {Transform} = __nccwpck_require__(84123); + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; -const crc32 = __nccwpck_require__(13080); + start(); -class CRC32Stream extends Transform { - constructor(options) { - super(options); - this.checksum = Buffer.allocUnsafe(4); - this.checksum.writeInt32BE(0, 0); + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; - this.rawSize = 0; + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs.lstatSync(base); + knownHard[base] = true; + } } - _transform(chunk, encoding, callback) { - if (chunk) { - this.checksum = crc32.buf(chunk, this.checksum) >>> 0; - this.rawSize += chunk.length; - } + // walk down the path, swapping out linked pathparts for their real + // values + // NB: p.length changes. + while (pos < p.length) { + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; - callback(null, chunk); - } + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + continue; + } - digest(encoding) { - const checksum = Buffer.allocUnsafe(4); - checksum.writeUInt32BE(this.checksum >>> 0, 0); - return encoding ? checksum.toString(encoding) : checksum; - } + var resolvedLink; + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // some known symbolic link. no need to stat again. + resolvedLink = cache[base]; + } else { + var stat = fs.lstatSync(base); + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + continue; + } - hex() { - return this.digest('hex').toUpperCase(); - } + // read the link if it wasn't read before + // dev/ino always return 0 on windows, so skip the check. + var linkTarget = null; + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + linkTarget = seenLinks[id]; + } + } + if (linkTarget === null) { + fs.statSync(base); + linkTarget = fs.readlinkSync(base); + } + resolvedLink = pathModule.resolve(previous, linkTarget); + // track this, if given a cache. + if (cache) cache[base] = resolvedLink; + if (!isWindows) seenLinks[id] = linkTarget; + } - size() { - return this.rawSize; + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); } -} - -module.exports = CRC32Stream; + if (cache) cache[original] = p; -/***/ }), + return p; +}; -/***/ 32737: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; -/** - * node-crc32-stream - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-crc32-stream/blob/master/LICENSE-MIT - */ +exports.realpath = function realpath(p, cache, cb) { + if (typeof cb !== 'function') { + cb = maybeCallback(cache); + cache = null; + } + // make p is absolute + p = pathModule.resolve(p); + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return process.nextTick(cb.bind(null, null, cache[p])); + } -const {DeflateRaw} = __nccwpck_require__(59796); + var original = p, + seenLinks = {}, + knownHard = {}; -const crc32 = __nccwpck_require__(13080); + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; -class DeflateCRC32Stream extends DeflateRaw { - constructor(options) { - super(options); + start(); - this.checksum = Buffer.allocUnsafe(4); - this.checksum.writeInt32BE(0, 0); + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; - this.rawSize = 0; - this.compressedSize = 0; + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs.lstat(base, function(err) { + if (err) return cb(err); + knownHard[base] = true; + LOOP(); + }); + } else { + process.nextTick(LOOP); + } } - push(chunk, encoding) { - if (chunk) { - this.compressedSize += chunk.length; + // walk down the path, swapping out linked pathparts for their real + // values + function LOOP() { + // stop if scanned past end of path + if (pos >= p.length) { + if (cache) cache[original] = p; + return cb(null, p); } - return super.push(chunk, encoding); - } + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; - _transform(chunk, encoding, callback) { - if (chunk) { - this.checksum = crc32.buf(chunk, this.checksum) >>> 0; - this.rawSize += chunk.length; + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + return process.nextTick(LOOP); } - super._transform(chunk, encoding, callback) - } + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // known symbolic link. no need to stat again. + return gotResolvedLink(cache[base]); + } - digest(encoding) { - const checksum = Buffer.allocUnsafe(4); - checksum.writeUInt32BE(this.checksum >>> 0, 0); - return encoding ? checksum.toString(encoding) : checksum; + return fs.lstat(base, gotStat); } - hex() { - return this.digest('hex').toUpperCase(); - } + function gotStat(err, stat) { + if (err) return cb(err); - size(compressed = false) { - if (compressed) { - return this.compressedSize; - } else { - return this.rawSize; + // if not a symlink, skip to the next path part + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + return process.nextTick(LOOP); } - } -} - -module.exports = DeflateCRC32Stream; + // stat & read the link if not read before + // call gotTarget as soon as the link target is known + // dev/ino always return 0 on windows, so skip the check. + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + return gotTarget(null, seenLinks[id], base); + } + } + fs.stat(base, function(err) { + if (err) return cb(err); -/***/ }), - -/***/ 31593: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/** - * node-crc32-stream - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-crc32-stream/blob/master/LICENSE-MIT - */ - - - -module.exports = { - CRC32Stream: __nccwpck_require__(81629), - DeflateCRC32Stream: __nccwpck_require__(32737) -} - - -/***/ }), - -/***/ 88420: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var Stream = (__nccwpck_require__(12781).Stream); -var util = __nccwpck_require__(73837); - -module.exports = DelayedStream; -function DelayedStream() { - this.source = null; - this.dataSize = 0; - this.maxDataSize = 1024 * 1024; - this.pauseStream = true; - - this._maxDataSizeExceeded = false; - this._released = false; - this._bufferedEvents = []; -} -util.inherits(DelayedStream, Stream); - -DelayedStream.create = function(source, options) { - var delayedStream = new this(); - - options = options || {}; - for (var option in options) { - delayedStream[option] = options[option]; + fs.readlink(base, function(err, target) { + if (!isWindows) seenLinks[id] = target; + gotTarget(err, target); + }); + }); } - delayedStream.source = source; - - var realEmit = source.emit; - source.emit = function() { - delayedStream._handleEmit(arguments); - return realEmit.apply(source, arguments); - }; + function gotTarget(err, target, base) { + if (err) return cb(err); - source.on('error', function() {}); - if (delayedStream.pauseStream) { - source.pause(); + var resolvedLink = pathModule.resolve(previous, target); + if (cache) cache[base] = resolvedLink; + gotResolvedLink(resolvedLink); } - return delayedStream; -}; - -Object.defineProperty(DelayedStream.prototype, 'readable', { - configurable: true, - enumerable: true, - get: function() { - return this.source.readable; + function gotResolvedLink(resolvedLink) { + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); } -}); - -DelayedStream.prototype.setEncoding = function() { - return this.source.setEncoding.apply(this.source, arguments); }; -DelayedStream.prototype.resume = function() { - if (!this._released) { - this.release(); - } - this.source.resume(); -}; - -DelayedStream.prototype.pause = function() { - this.source.pause(); -}; +/***/ }), -DelayedStream.prototype.release = function() { - this._released = true; +/***/ 67356: +/***/ ((module) => { - this._bufferedEvents.forEach(function(args) { - this.emit.apply(this, args); - }.bind(this)); - this._bufferedEvents = []; -}; +"use strict"; -DelayedStream.prototype.pipe = function() { - var r = Stream.prototype.pipe.apply(this, arguments); - this.resume(); - return r; -}; -DelayedStream.prototype._handleEmit = function(args) { - if (this._released) { - this.emit.apply(this, args); - return; - } +module.exports = clone - if (args[0] === 'data') { - this.dataSize += args[1].length; - this._checkIfMaxDataSizeExceeded(); - } +var getPrototypeOf = Object.getPrototypeOf || function (obj) { + return obj.__proto__ +} - this._bufferedEvents.push(args); -}; +function clone (obj) { + if (obj === null || typeof obj !== 'object') + return obj -DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { - if (this._maxDataSizeExceeded) { - return; - } + if (obj instanceof Object) + var copy = { __proto__: getPrototypeOf(obj) } + else + var copy = Object.create(null) - if (this.dataSize <= this.maxDataSize) { - return; - } + Object.getOwnPropertyNames(obj).forEach(function (key) { + Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) + }) - this._maxDataSizeExceeded = true; - var message = - 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' - this.emit('error', new Error(message)); -}; + return copy +} /***/ }), -/***/ 24107: -/***/ ((__unused_webpack_module, exports) => { +/***/ 77758: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +var fs = __nccwpck_require__(57147) +var polyfills = __nccwpck_require__(20263) +var legacy = __nccwpck_require__(73086) +var clone = __nccwpck_require__(67356) +var util = __nccwpck_require__(73837) -Object.defineProperty(exports, "__esModule", ({ value: true })); +/* istanbul ignore next - node 0.x polyfill */ +var gracefulQueue +var previousSymbol -class Deprecation extends Error { - constructor(message) { - super(message); // Maintains proper stack trace (only available on V8) +/* istanbul ignore else - node 0.x polyfill */ +if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { + gracefulQueue = Symbol.for('graceful-fs.queue') + // This is used in testing by future versions + previousSymbol = Symbol.for('graceful-fs.previous') +} else { + gracefulQueue = '___graceful-fs.queue' + previousSymbol = '___graceful-fs.previous' +} - /* istanbul ignore next */ +function noop () {} - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); +function publishQueue(context, queue) { + Object.defineProperty(context, gracefulQueue, { + get: function() { + return queue } - - this.name = 'Deprecation'; - } - + }) } -exports.Deprecation = Deprecation; - - -/***/ }), +var debug = noop +if (util.debuglog) + debug = util.debuglog('gfs4') +else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) + debug = function() { + var m = util.format.apply(util, arguments) + m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') + console.error(m) + } -/***/ 91205: -/***/ ((module) => { +// Once time initialization +if (!fs[gracefulQueue]) { + // This queue can be shared by multiple loaded instances + var queue = global[gracefulQueue] || [] + publishQueue(fs, queue) -"use strict"; + // Patch fs.close/closeSync to shared queue version, because we need + // to retry() whenever a close happens *anywhere* in the program. + // This is essential when multiple graceful-fs instances are + // in play at the same time. + fs.close = (function (fs$close) { + function close (fd, cb) { + return fs$close.call(fs, fd, function (err) { + // This function uses the graceful-fs shared queue + if (!err) { + resetQueue() + } + if (typeof cb === 'function') + cb.apply(this, arguments) + }) + } -function _process (v, mod) { - var i - var r + Object.defineProperty(close, previousSymbol, { + value: fs$close + }) + return close + })(fs.close) - if (typeof mod === 'function') { - r = mod(v) - if (r !== undefined) { - v = r - } - } else if (Array.isArray(mod)) { - for (i = 0; i < mod.length; i++) { - r = mod[i](v) - if (r !== undefined) { - v = r - } + fs.closeSync = (function (fs$closeSync) { + function closeSync (fd) { + // This function uses the graceful-fs shared queue + fs$closeSync.apply(fs, arguments) + resetQueue() } - } - return v -} + Object.defineProperty(closeSync, previousSymbol, { + value: fs$closeSync + }) + return closeSync + })(fs.closeSync) -function parseKey (key, val) { - // detect negative index notation - if (key[0] === '-' && Array.isArray(val) && /^-\d+$/.test(key)) { - return val.length + parseInt(key, 10) + if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { + process.on('exit', function() { + debug(fs[gracefulQueue]) + __nccwpck_require__(39491).equal(fs[gracefulQueue].length, 0) + }) } - return key } -function isIndex (k) { - return /^\d+$/.test(k) +if (!global[gracefulQueue]) { + publishQueue(global, fs[gracefulQueue]); } -function isObject (val) { - return Object.prototype.toString.call(val) === '[object Object]' +module.exports = patch(clone(fs)) +if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { + module.exports = patch(fs) + fs.__patched = true; } -function isArrayOrObject (val) { - return Object(val) === val -} +function patch (fs) { + // Everything that references the open() function needs to be in here + polyfills(fs) + fs.gracefulify = patch -function isEmptyObject (val) { - return Object.keys(val).length === 0 -} + fs.createReadStream = createReadStream + fs.createWriteStream = createWriteStream + var fs$readFile = fs.readFile + fs.readFile = readFile + function readFile (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null -var blacklist = ['__proto__', 'prototype', 'constructor'] -var blacklistFilter = function (part) { return blacklist.indexOf(part) === -1 } + return go$readFile(path, options, cb) -function parsePath (path, sep) { - if (path.indexOf('[') >= 0) { - path = path.replace(/\[/g, sep).replace(/]/g, '') + function go$readFile (path, options, cb, startTime) { + return fs$readFile(path, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } } - var parts = path.split(sep) + var fs$writeFile = fs.writeFile + fs.writeFile = writeFile + function writeFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null - var check = parts.filter(blacklistFilter) + return go$writeFile(path, data, options, cb) - if (check.length !== parts.length) { - throw Error('Refusing to update blacklisted property ' + path) + function go$writeFile (path, data, options, cb, startTime) { + return fs$writeFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } } - return parts -} + var fs$appendFile = fs.appendFile + if (fs$appendFile) + fs.appendFile = appendFile + function appendFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null -var hasOwnProperty = Object.prototype.hasOwnProperty + return go$appendFile(path, data, options, cb) -function DotObject (separator, override, useArray, useBrackets) { - if (!(this instanceof DotObject)) { - return new DotObject(separator, override, useArray, useBrackets) + function go$appendFile (path, data, options, cb, startTime) { + return fs$appendFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } } - if (typeof override === 'undefined') override = false - if (typeof useArray === 'undefined') useArray = true - if (typeof useBrackets === 'undefined') useBrackets = true - this.separator = separator || '.' - this.override = override - this.useArray = useArray - this.useBrackets = useBrackets - this.keepArray = false - - // contains touched arrays - this.cleanup = [] -} + var fs$copyFile = fs.copyFile + if (fs$copyFile) + fs.copyFile = copyFile + function copyFile (src, dest, flags, cb) { + if (typeof flags === 'function') { + cb = flags + flags = 0 + } + return go$copyFile(src, dest, flags, cb) -var dotDefault = new DotObject('.', false, true, true) -function wrap (method) { - return function () { - return dotDefault[method].apply(dotDefault, arguments) + function go$copyFile (src, dest, flags, cb, startTime) { + return fs$copyFile(src, dest, flags, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } } -} -DotObject.prototype._fill = function (a, obj, v, mod) { - var k = a.shift() + var fs$readdir = fs.readdir + fs.readdir = readdir + var noReaddirOptionVersions = /^v[0-5]\./ + function readdir (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null - if (a.length > 0) { - obj[k] = obj[k] || (this.useArray && isIndex(a[0]) ? [] : {}) + var go$readdir = noReaddirOptionVersions.test(process.version) + ? function go$readdir (path, options, cb, startTime) { + return fs$readdir(path, fs$readdirCallback( + path, options, cb, startTime + )) + } + : function go$readdir (path, options, cb, startTime) { + return fs$readdir(path, options, fs$readdirCallback( + path, options, cb, startTime + )) + } - if (!isArrayOrObject(obj[k])) { - if (this.override) { - obj[k] = {} - } else { - if (!(isArrayOrObject(v) && isEmptyObject(v))) { - throw new Error( - 'Trying to redefine `' + k + '` which is a ' + typeof obj[k] - ) - } + return go$readdir(path, options, cb) - return - } - } + function fs$readdirCallback (path, options, cb, startTime) { + return function (err, files) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([ + go$readdir, + [path, options, cb], + err, + startTime || Date.now(), + Date.now() + ]) + else { + if (files && files.sort) + files.sort() - this._fill(a, obj[k], v, mod) - } else { - if (!this.override && isArrayOrObject(obj[k]) && !isEmptyObject(obj[k])) { - if (!(isArrayOrObject(v) && isEmptyObject(v))) { - throw new Error("Trying to redefine non-empty obj['" + k + "']") + if (typeof cb === 'function') + cb.call(this, err, files) + } } - - return } + } - obj[k] = _process(v, mod) + if (process.version.substr(0, 4) === 'v0.8') { + var legStreams = legacy(fs) + ReadStream = legStreams.ReadStream + WriteStream = legStreams.WriteStream } -} -/** - * - * Converts an object with dotted-key/value pairs to it's expanded version - * - * Optionally transformed by a set of modifiers. - * - * Usage: - * - * var row = { - * 'nr': 200, - * 'doc.name': ' My Document ' - * } - * - * var mods = { - * 'doc.name': [_s.trim, _s.underscored] - * } - * - * dot.object(row, mods) - * - * @param {Object} obj - * @param {Object} mods - */ -DotObject.prototype.object = function (obj, mods) { - var self = this + var fs$ReadStream = fs.ReadStream + if (fs$ReadStream) { + ReadStream.prototype = Object.create(fs$ReadStream.prototype) + ReadStream.prototype.open = ReadStream$open + } - Object.keys(obj).forEach(function (k) { - var mod = mods === undefined ? null : mods[k] - // normalize array notation. - var ok = parsePath(k, self.separator).join(self.separator) + var fs$WriteStream = fs.WriteStream + if (fs$WriteStream) { + WriteStream.prototype = Object.create(fs$WriteStream.prototype) + WriteStream.prototype.open = WriteStream$open + } - if (ok.indexOf(self.separator) !== -1) { - self._fill(ok.split(self.separator), obj, obj[k], mod) - delete obj[k] - } else { - obj[k] = _process(obj[k], mod) - } + Object.defineProperty(fs, 'ReadStream', { + get: function () { + return ReadStream + }, + set: function (val) { + ReadStream = val + }, + enumerable: true, + configurable: true + }) + Object.defineProperty(fs, 'WriteStream', { + get: function () { + return WriteStream + }, + set: function (val) { + WriteStream = val + }, + enumerable: true, + configurable: true }) - return obj -} - -/** - * @param {String} path dotted path - * @param {String} v value to be set - * @param {Object} obj object to be modified - * @param {Function|Array} mod optional modifier - */ -DotObject.prototype.str = function (path, v, obj, mod) { - var ok = parsePath(path, this.separator).join(this.separator) + // legacy names + var FileReadStream = ReadStream + Object.defineProperty(fs, 'FileReadStream', { + get: function () { + return FileReadStream + }, + set: function (val) { + FileReadStream = val + }, + enumerable: true, + configurable: true + }) + var FileWriteStream = WriteStream + Object.defineProperty(fs, 'FileWriteStream', { + get: function () { + return FileWriteStream + }, + set: function (val) { + FileWriteStream = val + }, + enumerable: true, + configurable: true + }) - if (path.indexOf(this.separator) !== -1) { - this._fill(ok.split(this.separator), obj, v, mod) - } else { - obj[path] = _process(v, mod) + function ReadStream (path, options) { + if (this instanceof ReadStream) + return fs$ReadStream.apply(this, arguments), this + else + return ReadStream.apply(Object.create(ReadStream.prototype), arguments) } - return obj -} - -/** - * - * Pick a value from an object using dot notation. - * - * Optionally remove the value - * - * @param {String} path - * @param {Object} obj - * @param {Boolean} remove - */ -DotObject.prototype.pick = function (path, obj, remove, reindexArray) { - var i - var keys - var val - var key - var cp + function ReadStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + if (that.autoClose) + that.destroy() - keys = parsePath(path, this.separator) - for (i = 0; i < keys.length; i++) { - key = parseKey(keys[i], obj) - if (obj && typeof obj === 'object' && key in obj) { - if (i === keys.length - 1) { - if (remove) { - val = obj[key] - if (reindexArray && Array.isArray(obj)) { - obj.splice(key, 1) - } else { - delete obj[key] - } - if (Array.isArray(obj)) { - cp = keys.slice(0, -1).join('.') - if (this.cleanup.indexOf(cp) === -1) { - this.cleanup.push(cp) - } - } - return val - } else { - return obj[key] - } + that.emit('error', err) } else { - obj = obj[key] + that.fd = fd + that.emit('open', fd) + that.read() } - } else { - return undefined - } + }) } - if (remove && Array.isArray(obj)) { - obj = obj.filter(function (n) { - return n !== undefined + + function WriteStream (path, options) { + if (this instanceof WriteStream) + return fs$WriteStream.apply(this, arguments), this + else + return WriteStream.apply(Object.create(WriteStream.prototype), arguments) + } + + function WriteStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + that.destroy() + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + } }) } - return obj -} -/** - * - * Delete value from an object using dot notation. - * - * @param {String} path - * @param {Object} obj - * @return {any} The removed value - */ -DotObject.prototype.delete = function (path, obj) { - return this.remove(path, obj, true) -} -/** - * - * Remove value from an object using dot notation. - * - * Will remove multiple items if path is an array. - * In this case array indexes will be retained until all - * removals have been processed. - * - * Use dot.delete() to automatically re-index arrays. - * - * @param {String|Array} path - * @param {Object} obj - * @param {Boolean} reindexArray - * @return {any} The removed value - */ -DotObject.prototype.remove = function (path, obj, reindexArray) { - var i + function createReadStream (path, options) { + return new fs.ReadStream(path, options) + } - this.cleanup = [] - if (Array.isArray(path)) { - for (i = 0; i < path.length; i++) { - this.pick(path[i], obj, true, reindexArray) - } - if (!reindexArray) { - this._cleanup(obj) - } - return obj - } else { - return this.pick(path, obj, true, reindexArray) + function createWriteStream (path, options) { + return new fs.WriteStream(path, options) } -} -DotObject.prototype._cleanup = function (obj) { - var ret - var i - var keys - var root - if (this.cleanup.length) { - for (i = 0; i < this.cleanup.length; i++) { - keys = this.cleanup[i].split('.') - root = keys.splice(0, -1).join('.') - ret = root ? this.pick(root, obj) : obj - ret = ret[keys[0]].filter(function (v) { - return v !== undefined + var fs$open = fs.open + fs.open = open + function open (path, flags, mode, cb) { + if (typeof mode === 'function') + cb = mode, mode = null + + return go$open(path, flags, mode, cb) + + function go$open (path, flags, mode, cb, startTime) { + return fs$open(path, flags, mode, function (err, fd) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } }) - this.set(this.cleanup[i], ret, obj) } - this.cleanup = [] } + + return fs } -/** - * Alias method for `dot.remove` - * - * Note: this is not an alias for dot.delete() - * - * @param {String|Array} path - * @param {Object} obj - * @param {Boolean} reindexArray - * @return {any} The removed value - */ -DotObject.prototype.del = DotObject.prototype.remove +function enqueue (elem) { + debug('ENQUEUE', elem[0].name, elem[1]) + fs[gracefulQueue].push(elem) + retry() +} -/** - * - * Move a property from one place to the other. - * - * If the source path does not exist (undefined) - * the target property will not be set. - * - * @param {String} source - * @param {String} target - * @param {Object} obj - * @param {Function|Array} mods - * @param {Boolean} merge - */ -DotObject.prototype.move = function (source, target, obj, mods, merge) { - if (typeof mods === 'function' || Array.isArray(mods)) { - this.set(target, _process(this.pick(source, obj, true), mods), obj, merge) - } else { - merge = mods - this.set(target, this.pick(source, obj, true), obj, merge) - } +// keep track of the timeout between retry() calls +var retryTimer - return obj +// reset the startTime and lastTime to now +// this resets the start of the 60 second overall timeout as well as the +// delay between attempts so that we'll retry these jobs sooner +function resetQueue () { + var now = Date.now() + for (var i = 0; i < fs[gracefulQueue].length; ++i) { + // entries that are only a length of 2 are from an older version, don't + // bother modifying those since they'll be retried anyway. + if (fs[gracefulQueue][i].length > 2) { + fs[gracefulQueue][i][3] = now // startTime + fs[gracefulQueue][i][4] = now // lastTime + } + } + // call retry to make sure we're actively processing the queue + retry() } -/** - * - * Transfer a property from one object to another object. - * - * If the source path does not exist (undefined) - * the property on the other object will not be set. - * - * @param {String} source - * @param {String} target - * @param {Object} obj1 - * @param {Object} obj2 - * @param {Function|Array} mods - * @param {Boolean} merge - */ -DotObject.prototype.transfer = function ( - source, - target, - obj1, - obj2, - mods, - merge -) { - if (typeof mods === 'function' || Array.isArray(mods)) { - this.set( - target, - _process(this.pick(source, obj1, true), mods), - obj2, - merge - ) - } else { - merge = mods - this.set(target, this.pick(source, obj1, true), obj2, merge) - } +function retry () { + // clear the timer and remove it to help prevent unintended concurrency + clearTimeout(retryTimer) + retryTimer = undefined - return obj2 -} + if (fs[gracefulQueue].length === 0) + return -/** - * - * Copy a property from one object to another object. - * - * If the source path does not exist (undefined) - * the property on the other object will not be set. - * - * @param {String} source - * @param {String} target - * @param {Object} obj1 - * @param {Object} obj2 - * @param {Function|Array} mods - * @param {Boolean} merge - */ -DotObject.prototype.copy = function (source, target, obj1, obj2, mods, merge) { - if (typeof mods === 'function' || Array.isArray(mods)) { - this.set( - target, - _process( - // clone what is picked - JSON.parse(JSON.stringify(this.pick(source, obj1, false))), - mods - ), - obj2, - merge - ) + var elem = fs[gracefulQueue].shift() + var fn = elem[0] + var args = elem[1] + // these items may be unset if they were added by an older graceful-fs + var err = elem[2] + var startTime = elem[3] + var lastTime = elem[4] + + // if we don't have a startTime we have no way of knowing if we've waited + // long enough, so go ahead and retry this item now + if (startTime === undefined) { + debug('RETRY', fn.name, args) + fn.apply(null, args) + } else if (Date.now() - startTime >= 60000) { + // it's been more than 60 seconds total, bail now + debug('TIMEOUT', fn.name, args) + var cb = args.pop() + if (typeof cb === 'function') + cb.call(null, err) } else { - merge = mods - this.set(target, this.pick(source, obj1, false), obj2, merge) + // the amount of time between the last attempt and right now + var sinceAttempt = Date.now() - lastTime + // the amount of time between when we first tried, and when we last tried + // rounded up to at least 1 + var sinceStart = Math.max(lastTime - startTime, 1) + // backoff. wait longer than the total time we've been retrying, but only + // up to a maximum of 100ms + var desiredDelay = Math.min(sinceStart * 1.2, 100) + // it's been long enough since the last retry, do it again + if (sinceAttempt >= desiredDelay) { + debug('RETRY', fn.name, args) + fn.apply(null, args.concat([startTime])) + } else { + // if we can't do this job yet, push it to the end of the queue + // and let the next iteration check again + fs[gracefulQueue].push(elem) + } } - return obj2 + // schedule our next run if one isn't already scheduled + if (retryTimer === undefined) { + retryTimer = setTimeout(retry, 0) + } } -/** - * - * Set a property on an object using dot notation. - * - * @param {String} path - * @param {any} val - * @param {Object} obj - * @param {Boolean} merge - */ -DotObject.prototype.set = function (path, val, obj, merge) { - var i - var k - var keys - var key - // Do not operate if the value is undefined. - if (typeof val === 'undefined') { - return obj +/***/ }), + +/***/ 73086: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var Stream = (__nccwpck_require__(12781).Stream) + +module.exports = legacy + +function legacy (fs) { + return { + ReadStream: ReadStream, + WriteStream: WriteStream } - keys = parsePath(path, this.separator) - for (i = 0; i < keys.length; i++) { - key = keys[i] - if (i === keys.length - 1) { - if (merge && isObject(val) && isObject(obj[key])) { - for (k in val) { - if (hasOwnProperty.call(val, k)) { - obj[key][k] = val[k] - } - } - } else if (merge && Array.isArray(obj[key]) && Array.isArray(val)) { - for (var j = 0; j < val.length; j++) { - obj[keys[i]].push(val[j]) - } - } else { - obj[key] = val + function ReadStream (path, options) { + if (!(this instanceof ReadStream)) return new ReadStream(path, options); + + Stream.call(this); + + var self = this; + + this.path = path; + this.fd = null; + this.readable = true; + this.paused = false; + + this.flags = 'r'; + this.mode = 438; /*=0666*/ + this.bufferSize = 64 * 1024; + + options = options || {}; + + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } + + if (this.encoding) this.setEncoding(this.encoding); + + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); } - } else if ( - // force the value to be an object - !hasOwnProperty.call(obj, key) || - (!isObject(obj[key]) && !Array.isArray(obj[key])) - ) { - // initialize as array if next key is numeric - if (/^\d+$/.test(keys[i + 1])) { - obj[key] = [] - } else { - obj[key] = {} + if (this.end === undefined) { + this.end = Infinity; + } else if ('number' !== typeof this.end) { + throw TypeError('end must be a Number'); + } + + if (this.start > this.end) { + throw new Error('start must be <= end'); } + + this.pos = this.start; } - obj = obj[key] - } - return obj -} -/** - * - * Transform an object - * - * Usage: - * - * var obj = { - * "id": 1, - * "some": { - * "thing": "else" - * } - * } - * - * var transform = { - * "id": "nr", - * "some.thing": "name" - * } - * - * var tgt = dot.transform(transform, obj) - * - * @param {Object} recipe Transform recipe - * @param {Object} obj Object to be transformed - * @param {Array} mods modifiers for the target - */ -DotObject.prototype.transform = function (recipe, obj, tgt) { - obj = obj || {} - tgt = tgt || {} - Object.keys(recipe).forEach( - function (key) { - this.set(recipe[key], this.pick(key, obj), tgt) - }.bind(this) - ) - return tgt -} + if (this.fd !== null) { + process.nextTick(function() { + self._read(); + }); + return; + } -/** - * - * Convert object to dotted-key/value pair - * - * Usage: - * - * var tgt = dot.dot(obj) - * - * or - * - * var tgt = {} - * dot.dot(obj, tgt) - * - * @param {Object} obj source object - * @param {Object} tgt target object - * @param {Array} path path array (internal) - */ -DotObject.prototype.dot = function (obj, tgt, path) { - tgt = tgt || {} - path = path || [] - var isArray = Array.isArray(obj) - - Object.keys(obj).forEach( - function (key) { - var index = isArray && this.useBrackets ? '[' + key + ']' : key - if ( - isArrayOrObject(obj[key]) && - ((isObject(obj[key]) && !isEmptyObject(obj[key])) || - (Array.isArray(obj[key]) && !this.keepArray && obj[key].length !== 0)) - ) { - if (isArray && this.useBrackets) { - var previousKey = path[path.length - 1] || '' - return this.dot( - obj[key], - tgt, - path.slice(0, -1).concat(previousKey + index) - ) - } else { - return this.dot(obj[key], tgt, path.concat(index)) - } - } else { - if (isArray && this.useBrackets) { - tgt[path.join(this.separator).concat('[' + key + ']')] = obj[key] - } else { - tgt[path.concat(index).join(this.separator)] = obj[key] - } + fs.open(this.path, this.flags, this.mode, function (err, fd) { + if (err) { + self.emit('error', err); + self.readable = false; + return; } - }.bind(this) - ) - return tgt -} - -DotObject.pick = wrap('pick') -DotObject.move = wrap('move') -DotObject.transfer = wrap('transfer') -DotObject.transform = wrap('transform') -DotObject.copy = wrap('copy') -DotObject.object = wrap('object') -DotObject.str = wrap('str') -DotObject.set = wrap('set') -DotObject.delete = wrap('delete') -DotObject.del = DotObject.remove = wrap('remove') -DotObject.dot = wrap('dot'); -['override', 'overwrite'].forEach(function (prop) { - Object.defineProperty(DotObject, prop, { - get: function () { - return dotDefault.override - }, - set: function (val) { - dotDefault.override = !!val - } - }) -}); -['useArray', 'keepArray', 'useBrackets'].forEach(function (prop) { - Object.defineProperty(DotObject, prop, { - get: function () { - return dotDefault[prop] - }, - set: function (val) { - dotDefault[prop] = val - } - }) -}) -DotObject._process = _process + self.fd = fd; + self.emit('open', fd); + self._read(); + }) + } -module.exports = DotObject + function WriteStream (path, options) { + if (!(this instanceof WriteStream)) return new WriteStream(path, options); + Stream.call(this); -/***/ }), + this.path = path; + this.fd = null; + this.writable = true; -/***/ 90679: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this.flags = 'w'; + this.encoding = 'binary'; + this.mode = 438; /*=0666*/ + this.bytesWritten = 0; -"use strict"; + options = options || {}; + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } -var stream = __nccwpck_require__(53820); + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.start < 0) { + throw new Error('start must be >= zero'); + } -function DuplexWrapper(options, writable, readable) { - if (typeof readable === "undefined") { - readable = writable; - writable = options; - options = null; - } + this.pos = this.start; + } - stream.Duplex.call(this, options); + this.busy = false; + this._queue = []; - if (typeof readable.read !== "function") { - readable = (new stream.Readable(options)).wrap(readable); + if (this.fd === null) { + this._open = fs.open; + this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); + this.flush(); + } } +} - this._writable = writable; - this._readable = readable; - this._waiting = false; - var self = this; +/***/ }), - writable.once("finish", function() { - self.end(); - }); +/***/ 20263: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this.once("finish", function() { - writable.end(); - }); +var constants = __nccwpck_require__(22057) - readable.on("readable", function() { - if (self._waiting) { - self._waiting = false; - self._read(); - } - }); +var origCwd = process.cwd +var cwd = null - readable.once("end", function() { - self.push(null); - }); +var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform - if (!options || typeof options.bubbleErrors === "undefined" || options.bubbleErrors) { - writable.on("error", function(err) { - self.emit("error", err); - }); +process.cwd = function() { + if (!cwd) + cwd = origCwd.call(process) + return cwd +} +try { + process.cwd() +} catch (er) {} - readable.on("error", function(err) { - self.emit("error", err); - }); +// This check is needed until node.js 12 is required +if (typeof process.chdir === 'function') { + var chdir = process.chdir + process.chdir = function (d) { + cwd = null + chdir.call(process, d) } + if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir) } -DuplexWrapper.prototype = Object.create(stream.Duplex.prototype, {constructor: {value: DuplexWrapper}}); +module.exports = patch -DuplexWrapper.prototype._write = function _write(input, encoding, done) { - this._writable.write(input, encoding, done); -}; +function patch (fs) { + // (re-)implement some things that are known busted or missing. -DuplexWrapper.prototype._read = function _read() { - var buf; - var reads = 0; - while ((buf = this._readable.read()) !== null) { - this.push(buf); - reads++; - } - if (reads === 0) { - this._waiting = true; + // lchmod, broken prior to 0.6.2 + // back-port the fix here. + if (constants.hasOwnProperty('O_SYMLINK') && + process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + patchLchmod(fs) } -}; -module.exports = function duplex2(options, writable, readable) { - return new DuplexWrapper(options, writable, readable); -}; + // lutimes implementation, or no-op + if (!fs.lutimes) { + patchLutimes(fs) + } -module.exports.DuplexWrapper = DuplexWrapper; + // https://github.com/isaacs/node-graceful-fs/issues/4 + // Chown should not fail on einval or eperm if non-root. + // It should not fail on enosys ever, as this just indicates + // that a fs doesn't support the intended operation. + fs.chown = chownFix(fs.chown) + fs.fchown = chownFix(fs.fchown) + fs.lchown = chownFix(fs.lchown) -/***/ }), + fs.chmod = chmodFix(fs.chmod) + fs.fchmod = chmodFix(fs.fchmod) + fs.lchmod = chmodFix(fs.lchmod) -/***/ 25293: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + fs.chownSync = chownFixSync(fs.chownSync) + fs.fchownSync = chownFixSync(fs.fchownSync) + fs.lchownSync = chownFixSync(fs.lchownSync) -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + fs.chmodSync = chmodFixSync(fs.chmodSync) + fs.fchmodSync = chmodFixSync(fs.fchmodSync) + fs.lchmodSync = chmodFixSync(fs.lchmodSync) -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. + fs.stat = statFix(fs.stat) + fs.fstat = statFix(fs.fstat) + fs.lstat = statFix(fs.lstat) + fs.statSync = statFixSync(fs.statSync) + fs.fstatSync = statFixSync(fs.fstatSync) + fs.lstatSync = statFixSync(fs.lstatSync) + // if lchmod/lchown do not exist, then make them no-ops + if (fs.chmod && !fs.lchmod) { + fs.lchmod = function (path, mode, cb) { + if (cb) process.nextTick(cb) + } + fs.lchmodSync = function () {} + } + if (fs.chown && !fs.lchown) { + fs.lchown = function (path, uid, gid, cb) { + if (cb) process.nextTick(cb) + } + fs.lchownSync = function () {} + } -/**/ + // on Windows, A/V software can lock the directory, causing this + // to fail with an EACCES or EPERM if the directory contains newly + // created files. Try again on failure, for up to 60 seconds. -var pna = __nccwpck_require__(13817); -/**/ + // Set the timeout this long because some Windows Anti-Virus, such as Parity + // bit9, may lock files for up to a minute, causing npm package install + // failures. Also, take care to yield the scheduler. Windows scheduling gives + // CPU to a busy looping process, which can cause the program causing the lock + // contention to be starved of CPU by node, so the contention doesn't resolve. + if (platform === "win32") { + fs.rename = typeof fs.rename !== 'function' ? fs.rename + : (function (fs$rename) { + function rename (from, to, cb) { + var start = Date.now() + var backoff = 0; + fs$rename(from, to, function CB (er) { + if (er + && (er.code === "EACCES" || er.code === "EPERM") + && Date.now() - start < 60000) { + setTimeout(function() { + fs.stat(to, function (stater, st) { + if (stater && stater.code === "ENOENT") + fs$rename(from, to, CB); + else + cb(er) + }) + }, backoff) + if (backoff < 100) + backoff += 10; + return; + } + if (cb) cb(er) + }) + } + if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename) + return rename + })(fs.rename) + } -/**/ -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - keys.push(key); - }return keys; -}; -/**/ + // if read() returns EAGAIN, then just try it again. + fs.read = typeof fs.read !== 'function' ? fs.read + : (function (fs$read) { + function read (fd, buffer, offset, length, position, callback_) { + var callback + if (callback_ && typeof callback_ === 'function') { + var eagCounter = 0 + callback = function (er, _, __) { + if (er && er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + callback_.apply(this, arguments) + } + } + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } -module.exports = Duplex; + // This ensures `util.promisify` works as it does for native `fs.read`. + if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read) + return read + })(fs.read) -/**/ -var util = Object.create(__nccwpck_require__(32137)); -util.inherits = __nccwpck_require__(42991); -/**/ + fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync + : (function (fs$readSync) { return function (fd, buffer, offset, length, position) { + var eagCounter = 0 + while (true) { + try { + return fs$readSync.call(fs, fd, buffer, offset, length, position) + } catch (er) { + if (er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + continue + } + throw er + } + } + }})(fs.readSync) -var Readable = __nccwpck_require__(99148); -var Writable = __nccwpck_require__(41631); + function patchLchmod (fs) { + fs.lchmod = function (path, mode, callback) { + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + if (callback) callback(err) + return + } + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + if (callback) callback(err || err2) + }) + }) + }) + } -util.inherits(Duplex, Readable); + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) -{ - // avoid scope creep, the keys array can then be collected - var keys = objectKeys(Writable.prototype); - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + var threw = true + var ret + try { + ret = fs.fchmodSync(fd, mode) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } } -} - -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - - Readable.call(this, options); - Writable.call(this, options); - if (options && options.readable === false) this.readable = false; - - if (options && options.writable === false) this.writable = false; - - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + function patchLutimes (fs) { + if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + if (er) { + if (cb) cb(er) + return + } + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + if (cb) cb(er || er2) + }) + }) + }) + } - this.once('end', onend); -} + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK) + var ret + var threw = true + try { + ret = fs.futimesSync(fd, at, mt) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function () { - return this._writableState.highWaterMark; + } else if (fs.futimes) { + fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } + fs.lutimesSync = function () {} + } } -}); -// the no-half-open enforcer -function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; + function chmodFix (orig) { + if (!orig) return orig + return function (target, mode, cb) { + return orig.call(fs, target, mode, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } - // no more data can be written. - // But allow more writes to happen in this tick. - pna.nextTick(onEndNT, this); -} + function chmodFixSync (orig) { + if (!orig) return orig + return function (target, mode) { + try { + return orig.call(fs, target, mode) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } -function onEndNT(self) { - self.end(); -} -Object.defineProperty(Duplex.prototype, 'destroyed', { - get: function () { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; + function chownFix (orig) { + if (!orig) return orig + return function (target, uid, gid, cb) { + return orig.call(fs, target, uid, gid, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) } - - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; - this._writableState.destroyed = value; } -}); -Duplex.prototype._destroy = function (err, cb) { - this.push(null); - this.end(); + function chownFixSync (orig) { + if (!orig) return orig + return function (target, uid, gid) { + try { + return orig.call(fs, target, uid, gid) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } - pna.nextTick(cb, err); -}; + function statFix (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + function callback (er, stats) { + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + if (cb) cb.apply(this, arguments) + } + return options ? orig.call(fs, target, options, callback) + : orig.call(fs, target, callback) + } + } + + function statFixSync (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options) { + var stats = options ? orig.call(fs, target, options) + : orig.call(fs, target) + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + return stats; + } + } + + // ENOSYS means that the fs doesn't support the op. Just ignore + // that, because it doesn't matter. + // + // if there's no getuid, or if getuid() is something other + // than 0, and the error is EINVAL or EPERM, then just ignore + // it. + // + // This specific case is a silent failure in cp, install, tar, + // and most other unix tools that manage permissions. + // + // When running as root, or if other types of errors are + // encountered, then it's strict. + function chownErOk (er) { + if (!er) + return true + + if (er.code === "ENOSYS") + return true + + var nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true + } + + return false + } +} + + +/***/ }), + +/***/ 52492: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var wrappy = __nccwpck_require__(62940) +var reqs = Object.create(null) +var once = __nccwpck_require__(1223) + +module.exports = wrappy(inflight) + +function inflight (key, cb) { + if (reqs[key]) { + reqs[key].push(cb) + return null + } else { + reqs[key] = [cb] + return makeres(key) + } +} + +function makeres (key) { + return once(function RES () { + var cbs = reqs[key] + var len = cbs.length + var args = slice(arguments) + + // XXX It's somewhat ambiguous whether a new callback added in this + // pass should be queued for later execution if something in the + // list of callbacks throws, or if it should just be discarded. + // However, it's such an edge case that it hardly matters, and either + // choice is likely as surprising as the other. + // As it happens, we do go ahead and schedule it for later execution. + try { + for (var i = 0; i < len; i++) { + cbs[i].apply(null, args) + } + } finally { + if (cbs.length > len) { + // added more in the interim. + // de-zalgo, just in case, but don't call again. + cbs.splice(0, len) + process.nextTick(function () { + RES.apply(null, args) + }) + } else { + delete reqs[key] + } + } + }) +} + +function slice (args) { + var length = args.length + var array = [] + + for (var i = 0; i < length; i++) array[i] = args[i] + return array +} + + +/***/ }), + +/***/ 44124: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +try { + var util = __nccwpck_require__(73837); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = __nccwpck_require__(8544); +} + + +/***/ }), + +/***/ 8544: +/***/ ((module) => { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} + + +/***/ }), + +/***/ 63287: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +/*! + * is-plain-object + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + +function isObject(o) { + return Object.prototype.toString.call(o) === '[object Object]'; +} + +function isPlainObject(o) { + var ctor,prot; + + if (isObject(o) === false) return false; + + // If has modified constructor + ctor = o.constructor; + if (ctor === undefined) return true; + + // If has modified prototype + prot = ctor.prototype; + if (isObject(prot) === false) return false; + + // If constructor does not have an Object-specific method + if (prot.hasOwnProperty('isPrototypeOf') === false) { + return false; + } + + // Most likely a plain Object + return true; +} + +exports.isPlainObject = isPlainObject; + + +/***/ }), + +/***/ 20893: +/***/ ((module) => { + +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + + +/***/ }), + +/***/ 84329: +/***/ ((module) => { + +"use strict"; +function e(e){this.message=e}e.prototype=new Error,e.prototype.name="InvalidCharacterError";var r="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(r){var t=String(r).replace(/=+$/,"");if(t.length%4==1)throw new e("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,o,a=0,i=0,c="";o=t.charAt(i++);~o&&(n=a%4?64*n+o:o,a++%4)?c+=String.fromCharCode(255&n>>(-2*a&6)):0)o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(o);return c};function t(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(r(e).replace(/(.)/g,(function(e,r){var t=r.charCodeAt(0).toString(16).toUpperCase();return t.length<2&&(t="0"+t),"%"+t})))}(t)}catch(e){return r(t)}}function n(e){this.message=e}function o(e,r){if("string"!=typeof e)throw new n("Invalid token specified");var o=!0===(r=r||{}).header?0:1;try{return JSON.parse(t(e.split(".")[o]))}catch(e){throw new n("Invalid token specified: "+e.message)}}n.prototype=new Error,n.prototype.name="InvalidTokenError";const a=o;a.default=o,a.InvalidTokenError=n,module.exports=a; +//# sourceMappingURL=jwt-decode.cjs.js.map + + +/***/ }), + +/***/ 12084: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var util = __nccwpck_require__(73837); +var PassThrough = __nccwpck_require__(27818); + +module.exports = { + Readable: Readable, + Writable: Writable +}; + +util.inherits(Readable, PassThrough); +util.inherits(Writable, PassThrough); + +// Patch the given method of instance so that the callback +// is executed once, before the actual method is called the +// first time. +function beforeFirstCall(instance, method, callback) { + instance[method] = function() { + delete instance[method]; + callback.apply(this, arguments); + return this[method].apply(this, arguments); + }; +} + +function Readable(fn, options) { + if (!(this instanceof Readable)) + return new Readable(fn, options); + + PassThrough.call(this, options); + + beforeFirstCall(this, '_read', function() { + var source = fn.call(this, options); + var emit = this.emit.bind(this, 'error'); + source.on('error', emit); + source.pipe(this); + }); + + this.emit('readable'); +} + +function Writable(fn, options) { + if (!(this instanceof Writable)) + return new Writable(fn, options); + + PassThrough.call(this, options); + + beforeFirstCall(this, '_write', function() { + var destination = fn.call(this, options); + var emit = this.emit.bind(this, 'error'); + destination.on('error', emit); + this.pipe(destination); + }); + + this.emit('writable'); +} + + + +/***/ }), + +/***/ 5706: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + + + +/**/ + +var pna = __nccwpck_require__(47810); +/**/ + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ + +module.exports = Duplex; + +/**/ +var util = Object.create(__nccwpck_require__(95898)); +util.inherits = __nccwpck_require__(44124); +/**/ + +var Readable = __nccwpck_require__(99140); +var Writable = __nccwpck_require__(14960); + +util.inherits(Duplex, Readable); + +{ + // avoid scope creep, the keys array can then be collected + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} + +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + pna.nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +Object.defineProperty(Duplex.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); + +Duplex.prototype._destroy = function (err, cb) { + this.push(null); + this.end(); + + pna.nextTick(cb, err); +}; /***/ }), -/***/ 91182: +/***/ 70982: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -76714,11 +71242,11 @@ Duplex.prototype._destroy = function (err, cb) { module.exports = PassThrough; -var Transform = __nccwpck_require__(90223); +var Transform = __nccwpck_require__(75072); /**/ -var util = Object.create(__nccwpck_require__(32137)); -util.inherits = __nccwpck_require__(42991); +var util = Object.create(__nccwpck_require__(95898)); +util.inherits = __nccwpck_require__(44124); /**/ util.inherits(PassThrough, Transform); @@ -76735,7 +71263,7 @@ PassThrough.prototype._transform = function (chunk, encoding, cb) { /***/ }), -/***/ 99148: +/***/ 99140: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -76764,13 +71292,13 @@ PassThrough.prototype._transform = function (chunk, encoding, cb) { /**/ -var pna = __nccwpck_require__(13817); +var pna = __nccwpck_require__(47810); /**/ module.exports = Readable; /**/ -var isArray = __nccwpck_require__(80456); +var isArray = __nccwpck_require__(20893); /**/ /**/ @@ -76788,12 +71316,12 @@ var EElistenerCount = function (emitter, type) { /**/ /**/ -var Stream = __nccwpck_require__(72740); +var Stream = __nccwpck_require__(58745); /**/ /**/ -var Buffer = (__nccwpck_require__(25003).Buffer); +var Buffer = (__nccwpck_require__(15054).Buffer); var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); @@ -76805,8 +71333,8 @@ function _isUint8Array(obj) { /**/ /**/ -var util = Object.create(__nccwpck_require__(32137)); -util.inherits = __nccwpck_require__(42991); +var util = Object.create(__nccwpck_require__(95898)); +util.inherits = __nccwpck_require__(44124); /**/ /**/ @@ -76819,8 +71347,8 @@ if (debugUtil && debugUtil.debuglog) { } /**/ -var BufferList = __nccwpck_require__(2217); -var destroyImpl = __nccwpck_require__(97098); +var BufferList = __nccwpck_require__(75454); +var destroyImpl = __nccwpck_require__(78999); var StringDecoder; util.inherits(Readable, Stream); @@ -76840,7 +71368,7 @@ function prependListener(emitter, event, fn) { } function ReadableState(options, stream) { - Duplex = Duplex || __nccwpck_require__(25293); + Duplex = Duplex || __nccwpck_require__(5706); options = options || {}; @@ -76910,14 +71438,14 @@ function ReadableState(options, stream) { this.decoder = null; this.encoding = null; if (options.encoding) { - if (!StringDecoder) StringDecoder = (__nccwpck_require__(49807)/* .StringDecoder */ .s); + if (!StringDecoder) StringDecoder = (__nccwpck_require__(24749)/* .StringDecoder */ .s); this.decoder = new StringDecoder(options.encoding); this.encoding = options.encoding; } } function Readable(options) { - Duplex = Duplex || __nccwpck_require__(25293); + Duplex = Duplex || __nccwpck_require__(5706); if (!(this instanceof Readable)) return new Readable(options); @@ -77066,7 +71594,7 @@ Readable.prototype.isPaused = function () { // backwards compatibility. Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = (__nccwpck_require__(49807)/* .StringDecoder */ .s); + if (!StringDecoder) StringDecoder = (__nccwpck_require__(24749)/* .StringDecoder */ .s); this._readableState.decoder = new StringDecoder(enc); this._readableState.encoding = enc; return this; @@ -77761,7 +72289,7 @@ function indexOf(xs, x) { /***/ }), -/***/ 90223: +/***/ 75072: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -77832,11 +72360,11 @@ function indexOf(xs, x) { module.exports = Transform; -var Duplex = __nccwpck_require__(25293); +var Duplex = __nccwpck_require__(5706); /**/ -var util = Object.create(__nccwpck_require__(32137)); -util.inherits = __nccwpck_require__(42991); +var util = Object.create(__nccwpck_require__(95898)); +util.inherits = __nccwpck_require__(44124); /**/ util.inherits(Transform, Duplex); @@ -77982,7 +72510,7 @@ function done(stream, er, data) { /***/ }), -/***/ 41631: +/***/ 14960: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -78015,7 +72543,7 @@ function done(stream, er, data) { /**/ -var pna = __nccwpck_require__(13817); +var pna = __nccwpck_require__(47810); /**/ module.exports = Writable; @@ -78052,23 +72580,23 @@ var Duplex; Writable.WritableState = WritableState; /**/ -var util = Object.create(__nccwpck_require__(32137)); -util.inherits = __nccwpck_require__(42991); +var util = Object.create(__nccwpck_require__(95898)); +util.inherits = __nccwpck_require__(44124); /**/ /**/ var internalUtil = { - deprecate: __nccwpck_require__(98485) + deprecate: __nccwpck_require__(65278) }; /**/ /**/ -var Stream = __nccwpck_require__(72740); +var Stream = __nccwpck_require__(58745); /**/ /**/ -var Buffer = (__nccwpck_require__(25003).Buffer); +var Buffer = (__nccwpck_require__(15054).Buffer); var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); @@ -78079,14 +72607,14 @@ function _isUint8Array(obj) { /**/ -var destroyImpl = __nccwpck_require__(97098); +var destroyImpl = __nccwpck_require__(78999); util.inherits(Writable, Stream); function nop() {} function WritableState(options, stream) { - Duplex = Duplex || __nccwpck_require__(25293); + Duplex = Duplex || __nccwpck_require__(5706); options = options || {}; @@ -78236,7 +72764,7 @@ if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.protot } function Writable(options) { - Duplex = Duplex || __nccwpck_require__(25293); + Duplex = Duplex || __nccwpck_require__(5706); // Writable ctor is applied to Duplexes, too. // `realHasInstance` is necessary because using plain `instanceof` @@ -78674,7 +73202,7 @@ Writable.prototype._destroy = function (err, cb) { /***/ }), -/***/ 2217: +/***/ 75454: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -78682,7 +73210,7 @@ Writable.prototype._destroy = function (err, cb) { function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -var Buffer = (__nccwpck_require__(25003).Buffer); +var Buffer = (__nccwpck_require__(15054).Buffer); var util = __nccwpck_require__(73837); function copyBuffer(src, target, offset) { @@ -78759,7 +73287,7 @@ if (util && util.inspect && util.inspect.custom) { /***/ }), -/***/ 97098: +/***/ 78999: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -78767,7 +73295,7 @@ if (util && util.inspect && util.inspect.custom) { /**/ -var pna = __nccwpck_require__(13817); +var pna = __nccwpck_require__(47810); /**/ // undocumented cb() API, needed for core, not for public API @@ -78850,7 +73378,7 @@ module.exports = { /***/ }), -/***/ 72740: +/***/ 58745: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = __nccwpck_require__(12781); @@ -78858,7 +73386,15 @@ module.exports = __nccwpck_require__(12781); /***/ }), -/***/ 53820: +/***/ 27818: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +module.exports = __nccwpck_require__(22399).PassThrough + + +/***/ }), + +/***/ 22399: /***/ ((module, exports, __nccwpck_require__) => { var Stream = __nccwpck_require__(12781); @@ -78872,19 +73408,19 @@ if (process.env.READABLE_STREAM === 'disable' && Stream) { exports.PassThrough = Stream.PassThrough; exports.Stream = Stream; } else { - exports = module.exports = __nccwpck_require__(99148); + exports = module.exports = __nccwpck_require__(99140); exports.Stream = Stream || exports; exports.Readable = exports; - exports.Writable = __nccwpck_require__(41631); - exports.Duplex = __nccwpck_require__(25293); - exports.Transform = __nccwpck_require__(90223); - exports.PassThrough = __nccwpck_require__(91182); + exports.Writable = __nccwpck_require__(14960); + exports.Duplex = __nccwpck_require__(5706); + exports.Transform = __nccwpck_require__(75072); + exports.PassThrough = __nccwpck_require__(70982); } /***/ }), -/***/ 25003: +/***/ 15054: /***/ ((module, exports, __nccwpck_require__) => { /* eslint-disable node/no-deprecated-api */ @@ -78953,7 +73489,7 @@ SafeBuffer.allocUnsafeSlow = function (size) { /***/ }), -/***/ 49807: +/***/ 24749: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -78982,7 +73518,7 @@ SafeBuffer.allocUnsafeSlow = function (size) { /**/ -var Buffer = (__nccwpck_require__(25003).Buffer); +var Buffer = (__nccwpck_require__(15054).Buffer); /**/ var isEncoding = Buffer.isEncoding || function (encoding) { @@ -79256,5819 +73792,6918 @@ function simpleEnd(buf) { /***/ }), -/***/ 95688: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var once = __nccwpck_require__(58203); - -var noop = function() {}; - -var isRequest = function(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -}; - -var isChildProcess = function(stream) { - return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 -}; - -var eos = function(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; - - callback = once(callback || noop); - - var ws = stream._writableState; - var rs = stream._readableState; - var readable = opts.readable || (opts.readable !== false && stream.readable); - var writable = opts.writable || (opts.writable !== false && stream.writable); - var cancelled = false; - - var onlegacyfinish = function() { - if (!stream.writable) onfinish(); - }; - - var onfinish = function() { - writable = false; - if (!readable) callback.call(stream); - }; - - var onend = function() { - readable = false; - if (!writable) callback.call(stream); - }; - - var onexit = function(exitCode) { - callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); - }; - - var onerror = function(err) { - callback.call(stream, err); - }; - - var onclose = function() { - process.nextTick(onclosenexttick); - }; - - var onclosenexttick = function() { - if (cancelled) return; - if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close')); - if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close')); - }; +/***/ 11289: +/***/ ((module) => { - var onrequest = function() { - stream.req.on('finish', onfinish); - }; +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest(); - else stream.on('request', onrequest); - } else if (writable && !ws) { // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; - if (isChildProcess(stream)) stream.on('exit', onexit); +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]'; - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; - return function() { - cancelled = true; - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('exit', onexit); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; -}; +/** + * 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); +} -module.exports = eos; +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} -/***/ }), +/** Used for built-in method references. */ +var objectProto = Object.prototype; -/***/ 79700: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; -var CombinedStream = __nccwpck_require__(96283); -var util = __nccwpck_require__(73837); -var path = __nccwpck_require__(71017); -var http = __nccwpck_require__(13685); -var https = __nccwpck_require__(95687); -var parseUrl = (__nccwpck_require__(57310).parse); -var fs = __nccwpck_require__(57147); -var Stream = (__nccwpck_require__(12781).Stream); -var mime = __nccwpck_require__(76628); -var asynckit = __nccwpck_require__(32944); -var populate = __nccwpck_require__(8065); +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; -// Public API -module.exports = FormData; +/** Built-in value references. */ +var propertyIsEnumerable = objectProto.propertyIsEnumerable; -// make it a Stream -util.inherits(FormData, CombinedStream); +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; /** - * Create readable "multipart/form-data" streams. - * Can be used to submit forms - * and file uploads to other web applications. + * Creates an array of the enumerable property names of the array-like `value`. * - * @constructor - * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. */ -function FormData(options) { - if (!(this instanceof FormData)) { - return new FormData(options); - } - - this._overheadLength = 0; - this._valueLength = 0; - this._valuesToMeasure = []; +function arrayLikeKeys(value, inherited) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + // Safari 9 makes `arguments.length` enumerable in strict mode. + var result = (isArray(value) || isArguments(value)) + ? baseTimes(value.length, String) + : []; - CombinedStream.call(this); + var length = result.length, + skipIndexes = !!length; - options = options || {}; - for (var option in options) { - this[option] = options[option]; + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && (key == 'length' || isIndex(key, length)))) { + result.push(key); + } } + return result; } -FormData.LINE_BREAK = '\r\n'; -FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; - -FormData.prototype.append = function(field, value, options) { - - options = options || {}; - - // allow filename as single option - if (typeof options == 'string') { - options = {filename: options}; +/** + * Used by `_.defaults` to customize its `_.assignIn` use. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to assign. + * @param {Object} object The parent object of `objValue`. + * @returns {*} Returns the value to assign. + */ +function assignInDefaults(objValue, srcValue, key, object) { + if (objValue === undefined || + (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { + return srcValue; } + return objValue; +} - var append = CombinedStream.prototype.append.bind(this); - - // all that streamy business can't handle numbers - if (typeof value == 'number') { - value = '' + value; +/** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + object[key] = value; } +} - // https://github.com/felixge/node-form-data/issues/38 - if (util.isArray(value)) { - // Please convert your array into string - // the way web server expects it - this._error(new Error('Arrays are not supported.')); - return; +/** + * 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 = []; - var header = this._multiPartHeader(field, value, options); - var footer = this._multiPartFooter(); - - append(header); - append(value); - append(footer); - - // pass along options.knownLength - this._trackLength(header, value, options); -}; - -FormData.prototype._trackLength = function(header, value, options) { - var valueLength = 0; - - // used w/ getLengthSync(), when length is known. - // e.g. for streaming directly from a remote server, - // w/ a known file a size, and not wanting to wait for - // incoming file to finish to get its size. - if (options.knownLength != null) { - valueLength += +options.knownLength; - } else if (Buffer.isBuffer(value)) { - valueLength = value.length; - } else if (typeof value === 'string') { - valueLength = Buffer.byteLength(value); + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); + } } + return result; +} - this._valueLength += valueLength; - - // @check why add CRLF? does this account for custom/multiple CRLFs? - this._overheadLength += - Buffer.byteLength(header) + - FormData.LINE_BREAK.length; - - // empty or either doesn't have path or not an http response or not a stream - if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) && !(value instanceof Stream))) { - return; - } +/** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ +function baseRest(func, start) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); - // no need to bother with the length - if (!options.knownLength) { - this._valuesToMeasure.push(value); - } -}; + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = array; + return apply(func, this, otherArgs); + }; +} -FormData.prototype._lengthRetriever = function(value, callback) { +/** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ +function copyObject(source, props, object, customizer) { + object || (object = {}); - if (value.hasOwnProperty('fd')) { + var index = -1, + length = props.length; - // take read range into a account - // `end` = Infinity –> read file till the end - // - // TODO: Looks like there is bug in Node fs.createReadStream - // it doesn't respect `end` options without `start` options - // Fix it when node fixes it. - // https://github.com/joyent/node/issues/7819 - if (value.end != undefined && value.end != Infinity && value.start != undefined) { + while (++index < length) { + var key = props[index]; - // when end specified - // no need to calculate range - // inclusive, starts with 0 - callback(null, value.end + 1 - (value.start ? value.start : 0)); + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; - // not that fast snoopy - } else { - // still need to fetch file size from fs - fs.stat(value.path, function(err, stat) { + assignValue(object, key, newValue === undefined ? source[key] : newValue); + } + return object; +} - var fileSize; +/** + * 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; - if (err) { - callback(err); - return; - } + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; - // update final size based on the range options - fileSize = stat.size - (value.start ? value.start : 0); - callback(null, fileSize); - }); + 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; + }); +} - // or http response - } else if (value.hasOwnProperty('httpVersion')) { - callback(null, +value.headers['content-length']); - - // or request stream http://github.com/mikeal/request - } else if (value.hasOwnProperty('httpModule')) { - // wait till response come back - value.on('response', function(response) { - value.pause(); - callback(null, +response.headers['content-length']); - }); - value.resume(); +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); +} - // something else - } else { - callback('Unknown stream'); +/** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ +function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; } -}; - -FormData.prototype._multiPartHeader = function(field, value, options) { - // custom header specified (as string)? - // it becomes responsible for boundary - // (e.g. to handle extra CRLFs on .NET servers) - if (typeof options.header == 'string') { - return options.header; + 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; +} - var contentDisposition = this._getContentDisposition(value, options); - var contentType = this._getContentType(value, options); - - var contents = ''; - var headers = { - // add custom disposition as third element or keep it two elements if not - 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), - // if no content type. allow it to be empty array - 'Content-Type': [].concat(contentType || []) - }; +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - // allow custom headers. - if (typeof options.header == 'object') { - populate(headers, options.header); - } + return value === proto; +} - var header; - for (var prop in headers) { - if (!headers.hasOwnProperty(prop)) continue; - header = headers[prop]; - - // skip nullish headers. - if (header == null) { - continue; - } - - // convert all headers to arrays. - if (!Array.isArray(header)) { - header = [header]; - } - - // add non-empty headers. - if (header.length) { - contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; +/** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); } } + return result; +} - return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; -}; +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); +} -FormData.prototype._getContentDisposition = function(value, options) { +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} - var filename - , contentDisposition - ; +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; - if (typeof options.filepath === 'string') { - // custom filepath for relative paths - filename = path.normalize(options.filepath).replace(/\\/g, '/'); - } else if (options.filename || value.name || value.path) { - // custom filename take precedence - // formidable and the browser add a name property - // fs- and request- streams have path property - filename = path.basename(options.filename || value.name || value.path); - } else if (value.readable && value.hasOwnProperty('httpVersion')) { - // or try http response - filename = path.basename(value.client._httpMessage.path || ''); - } +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} - if (filename) { - contentDisposition = 'filename="' + filename + '"'; - } +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} - return contentDisposition; -}; +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} -FormData.prototype._getContentType = function(value, options) { +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} - // use custom content-type above all - var contentType = options.contentType; +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} - // or try `name` from formidable, browser - if (!contentType && value.name) { - contentType = mime.lookup(value.name); - } +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - // or try `path` from fs-, request- streams - if (!contentType && value.path) { - contentType = mime.lookup(value.path); - } +/** + * This method is like `_.assignIn` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extendWith + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignInWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ +var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keysIn(source), object, customizer); +}); - // or if it's http-reponse - if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { - contentType = value.headers['content-type']; - } +/** + * Assigns own and inherited enumerable string keyed properties of source + * objects to the destination object for all destination properties that + * resolve to `undefined`. Source objects are applied from left to right. + * Once a property is set, additional values of the same property are ignored. + * + * **Note:** This method mutates `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaultsDeep + * @example + * + * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ +var defaults = baseRest(function(args) { + args.push(undefined, assignInDefaults); + return apply(assignInWith, undefined, args); +}); - // or guess it from the filepath or filename - if (!contentType && (options.filepath || options.filename)) { - contentType = mime.lookup(options.filepath || options.filename); - } +/** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ +function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); +} - // fallback to the default content type if `value` is not simple value - if (!contentType && typeof value == 'object') { - contentType = FormData.DEFAULT_CONTENT_TYPE; - } +module.exports = defaults; - return contentType; -}; -FormData.prototype._multiPartFooter = function() { - return function(next) { - var footer = FormData.LINE_BREAK; +/***/ }), - var lastPart = (this._streams.length === 0); - if (lastPart) { - footer += this._lastBoundary(); - } +/***/ 89764: +/***/ ((module) => { - next(footer); - }.bind(this); -}; +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ -FormData.prototype._lastBoundary = function() { - return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; -}; +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE = 200; -FormData.prototype.getHeaders = function(userHeaders) { - var header; - var formHeaders = { - 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() - }; +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; - for (header in userHeaders) { - if (userHeaders.hasOwnProperty(header)) { - formHeaders[header.toLowerCase()] = userHeaders[header]; - } - } +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; - return formHeaders; -}; +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]'; -FormData.prototype.setBoundary = function(boundary) { - this._boundary = boundary; -}; +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; -FormData.prototype.getBoundary = function() { - if (!this._boundary) { - this._generateBoundary(); - } +/** Used to detect host constructors (Safari). */ +var reIsHostCtor = /^\[object .+?Constructor\]$/; - return this._boundary; -}; +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; -FormData.prototype.getBuffer = function() { - var dataBuffer = new Buffer.alloc( 0 ); - var boundary = this.getBoundary(); +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - // Create the form content. Add Line breaks to the end of data. - for (var i = 0, len = this._streams.length; i < len; i++) { - if (typeof this._streams[i] !== 'function') { +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); - // Add content to the buffer. - if(Buffer.isBuffer(this._streams[i])) { - dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]); - }else { - dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]); - } +/** + * 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); +} - // Add break after content. - if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) { - dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData.LINE_BREAK)] ); - } - } - } - - // Add the footer and return the Buffer object. - return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] ); -}; - -FormData.prototype._generateBoundary = function() { - // This generates a 50 character boundary similar to those used by Firefox. - // They are optimized for boyer-moore parsing. - var boundary = '--------------------------'; - for (var i = 0; i < 24; i++) { - boundary += Math.floor(Math.random() * 10).toString(16); - } - - this._boundary = boundary; -}; - -// Note: getLengthSync DOESN'T calculate streams length -// As workaround one can calculate file size manually -// and add it as knownLength option -FormData.prototype.getLengthSync = function() { - var knownLength = this._overheadLength + this._valueLength; +/** + * 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 ? array.length : 0; + return !!length && baseIndexOf(array, value, 0) > -1; +} - // Don't get confused, there are 3 "internal" streams for each keyval pair - // so it basically checks if there is any value added to the form - if (this._streams.length) { - knownLength += this._lastBoundary().length; - } +/** + * 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 ? array.length : 0; - // https://github.com/form-data/form-data/issues/40 - if (!this.hasKnownLength()) { - // Some async length retrievers are present - // therefore synchronous length calculation is false. - // Please use getLength(callback) to get proper length - this._error(new Error('Cannot calculate proper length in synchronous way.')); + while (++index < length) { + if (comparator(value, array[index])) { + return true; + } } + return false; +} - return knownLength; -}; - -// Public API to check if length of added values is known -// https://github.com/form-data/form-data/issues/196 -// https://github.com/form-data/form-data/issues/262 -FormData.prototype.hasKnownLength = function() { - var hasKnownLength = true; +/** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function arrayMap(array, iteratee) { + var index = -1, + length = array ? array.length : 0, + result = Array(length); - if (this._valuesToMeasure.length) { - hasKnownLength = false; + while (++index < length) { + result[index] = iteratee(array[index], index, array); } + return result; +} - return hasKnownLength; -}; - -FormData.prototype.getLength = function(cb) { - var knownLength = this._overheadLength + this._valueLength; - - if (this._streams.length) { - knownLength += this._lastBoundary().length; - } +/** + * 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; - if (!this._valuesToMeasure.length) { - process.nextTick(cb.bind(this, null, knownLength)); - return; + while (++index < length) { + array[offset + index] = values[index]; } + return array; +} - asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { - if (err) { - cb(err); - return; - } - - values.forEach(function(length) { - knownLength += length; - }); - - cb(null, knownLength); - }); -}; - -FormData.prototype.submit = function(params, cb) { - var request - , options - , defaults = {method: 'post'} - ; - - // parse provided url if it's string - // or treat it as options object - if (typeof params == 'string') { - - params = parseUrl(params); - options = populate({ - port: params.port, - path: params.pathname, - host: params.hostname, - protocol: params.protocol - }, defaults); - - // use custom params - } else { +/** + * 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); - options = populate(params, defaults); - // if no port provided use default one - if (!options.port) { - options.port = options.protocol == 'https:' ? 443 : 80; + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; } } + return -1; +} - // put that good code in getHeaders to some use - options.headers = this.getHeaders(params.headers); - - // https if specified, fallback to http in any other case - if (options.protocol == 'https:') { - request = https.request(options); - } else { - request = http.request(options); +/** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseIndexOf(array, value, fromIndex) { + if (value !== value) { + return baseFindIndex(array, baseIsNaN, fromIndex); } + var index = fromIndex - 1, + length = array.length; - // get content length and fire away - this.getLength(function(err, length) { - if (err && err !== 'Unknown stream') { - this._error(err); - return; - } - - // add content length - if (length) { - request.setHeader('Content-Length', length); - } - - this.pipe(request); - if (cb) { - var onResponse; - - var callback = function (error, responce) { - request.removeListener('error', callback); - request.removeListener('response', onResponse); - - return cb.call(this, error, responce); - }; - - onResponse = callback.bind(this, null); - - request.on('error', callback); - request.on('response', onResponse); + while (++index < length) { + if (array[index] === value) { + return index; } - }.bind(this)); - - return request; -}; - -FormData.prototype._error = function(err) { - if (!this.error) { - this.error = err; - this.pause(); - this.emit('error', err); } -}; - -FormData.prototype.toString = function () { - return '[object FormData]'; -}; - + return -1; +} -/***/ }), +/** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ +function baseIsNaN(value) { + return value !== value; +} -/***/ 8065: -/***/ ((module) => { +/** + * 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); + }; +} -// populates missing values -module.exports = function(dst, src) { +/** + * 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); +} - Object.keys(src).forEach(function(prop) - { - dst[prop] = dst[prop] || src[prop]; - }); +/** + * 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 dst; -}; +/** + * Checks if `value` is a host object in IE < 9. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a host object, else `false`. + */ +function isHostObject(value) { + // Many host objects are `Object` objects that can coerce to strings + // despite having improperly defined `toString` methods. + var result = false; + if (value != null && typeof value.toString != 'function') { + try { + result = !!(value + ''); + } catch (e) {} + } + return result; +} +/** Used for built-in method references. */ +var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; -/***/ }), +/** Used to detect overreaching core-js shims. */ +var coreJsData = root['__core-js_shared__']; -/***/ 53370: -/***/ ((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) : ''; +}()); -module.exports = (__nccwpck_require__(57147).constants) || __nccwpck_require__(22057) +/** 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 resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; -/***/ 54421: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** Used to detect if a method is native. */ +var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' +); -module.exports = realpath -realpath.realpath = realpath -realpath.sync = realpathSync -realpath.realpathSync = realpathSync -realpath.monkeypatch = monkeypatch -realpath.unmonkeypatch = unmonkeypatch +/** Built-in value references. */ +var Symbol = root.Symbol, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; -var fs = __nccwpck_require__(57147) -var origRealpath = fs.realpath -var origRealpathSync = fs.realpathSync +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; -var version = process.version -var ok = /^v[0-5]\./.test(version) -var old = __nccwpck_require__(85877) +/* Built-in method references that are verified to be native. */ +var Map = getNative(root, 'Map'), + nativeCreate = getNative(Object, 'create'); -function newError (er) { - return er && er.syscall === 'realpath' && ( - er.code === 'ELOOP' || - er.code === 'ENOMEM' || - er.code === 'ENAMETOOLONG' - ) -} +/** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Hash(entries) { + var index = -1, + length = entries ? entries.length : 0; -function realpath (p, cache, cb) { - if (ok) { - return origRealpath(p, cache, cb) + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); } +} - if (typeof cache === 'function') { - cb = cache - cache = null - } - origRealpath(p, cache, function (er, result) { - if (newError(er)) { - old.realpath(p, cache, cb) - } else { - cb(er, result) - } - }) +/** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ +function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; } -function realpathSync (p, cache) { - if (ok) { - return origRealpathSync(p, cache) - } +/** + * 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) { + return this.has(key) && delete this.__data__[key]; +} - try { - return origRealpathSync(p, cache) - } catch (er) { - if (newError(er)) { - return old.realpathSync(p, cache) - } else { - throw er - } +/** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; } + return hasOwnProperty.call(data, key) ? data[key] : undefined; } -function monkeypatch () { - fs.realpath = realpath - fs.realpathSync = realpathSync +/** + * 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); } -function unmonkeypatch () { - fs.realpath = origRealpath - fs.realpathSync = origRealpathSync +/** + * 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__; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; } +// Add methods to `Hash`. +Hash.prototype.clear = hashClear; +Hash.prototype['delete'] = hashDelete; +Hash.prototype.get = hashGet; +Hash.prototype.has = hashHas; +Hash.prototype.set = hashSet; -/***/ }), - -/***/ 85877: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function ListCache(entries) { + var index = -1, + length = entries ? entries.length : 0; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} -var pathModule = __nccwpck_require__(71017); -var isWindows = process.platform === 'win32'; -var fs = __nccwpck_require__(57147); +/** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ +function listCacheClear() { + this.__data__ = []; +} -// JavaScript implementation of realpath, ported from node pre-v6 +/** + * 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); -var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + return true; +} -function rethrow() { - // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and - // is fairly slow to generate. - var callback; - if (DEBUG) { - var backtrace = new Error; - callback = debugCallback; - } else - callback = missingCallback; +/** + * 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); - return callback; + return index < 0 ? undefined : data[index][1]; +} - function debugCallback(err) { - if (err) { - backtrace.message = err.message; - err = backtrace; - missingCallback(err); - } +/** + * 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; +} + +/** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ +function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + data.push([key, value]); + } else { + data[index][1] = value; } + return this; +} - function missingCallback(err) { - if (err) { - if (process.throwDeprecation) - throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs - else if (!process.noDeprecation) { - var msg = 'fs: missing callback ' + (err.stack || err.message); - if (process.traceDeprecation) - console.trace(msg); - else - console.error(msg); - } - } +// Add methods to `ListCache`. +ListCache.prototype.clear = listCacheClear; +ListCache.prototype['delete'] = listCacheDelete; +ListCache.prototype.get = listCacheGet; +ListCache.prototype.has = listCacheHas; +ListCache.prototype.set = listCacheSet; + +/** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function MapCache(entries) { + var index = -1, + length = entries ? entries.length : 0; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); } } -function maybeCallback(cb) { - return typeof cb === 'function' ? cb : rethrow(); +/** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ +function mapCacheClear() { + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; } -var normalize = pathModule.normalize; +/** + * 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) { + return getMapData(this, key)['delete'](key); +} -// Regexp that finds the next partion of a (partial) path -// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] -if (isWindows) { - var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; -} else { - var nextPartRe = /(.*?)(?:[\/]+|$)/g; +/** + * 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); } -// Regex to find the device root, including trailing slash. E.g. 'c:\\'. -if (isWindows) { - var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; -} else { - var splitRootRe = /^[\/]*/; +/** + * 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); } -exports.realpathSync = function realpathSync(p, cache) { - // make p is absolute - p = pathModule.resolve(p); +/** + * 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) { + getMapData(this, key).set(key, value); + return this; +} - if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { - return cache[p]; - } +// Add methods to `MapCache`. +MapCache.prototype.clear = mapCacheClear; +MapCache.prototype['delete'] = mapCacheDelete; +MapCache.prototype.get = mapCacheGet; +MapCache.prototype.has = mapCacheHas; +MapCache.prototype.set = mapCacheSet; - var original = p, - seenLinks = {}, - knownHard = {}; +/** + * + * 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 ? values.length : 0; - // current character position in p - var pos; - // the partial path so far, including a trailing slash if any - var current; - // the partial path without a trailing slash (except when pointing at a root) - var base; - // the partial path scanned in the previous round, with slash - var previous; + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } +} - start(); +/** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ +function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; +} - function start() { - // Skip over roots - var m = splitRootRe.exec(p); - pos = m[0].length; - current = m[0]; - base = m[0]; - previous = ''; +/** + * 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); +} - // On windows, check that the root exists. On unix there is no need. - if (isWindows && !knownHard[base]) { - fs.lstatSync(base); - knownHard[base] = true; +// Add methods to `SetCache`. +SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; +SetCache.prototype.has = setCacheHas; + +/** + * 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; +} - // walk down the path, swapping out linked pathparts for their real - // values - // NB: p.length changes. - while (pos < p.length) { - // find the next part - nextPartRe.lastIndex = pos; - var result = nextPartRe.exec(p); - previous = current; - current += result[0]; - base = previous + result[1]; - pos = nextPartRe.lastIndex; - - // continue if not a symlink - if (knownHard[base] || (cache && cache[base] === base)) { - continue; - } +/** + * 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; - var resolvedLink; - if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { - // some known symbolic link. no need to stat again. - resolvedLink = cache[base]; - } else { - var stat = fs.lstatSync(base); - if (!stat.isSymbolicLink()) { - knownHard[base] = true; - if (cache) cache[base] = base; - continue; - } + 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 ? iteratee(value) : value; - // read the link if it wasn't read before - // dev/ino always return 0 on windows, so skip the check. - var linkTarget = null; - if (!isWindows) { - var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); - if (seenLinks.hasOwnProperty(id)) { - linkTarget = seenLinks[id]; + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values[valuesIndex] === computed) { + continue outer; } } - if (linkTarget === null) { - fs.statSync(base); - linkTarget = fs.readlinkSync(base); - } - resolvedLink = pathModule.resolve(previous, linkTarget); - // track this, if given a cache. - if (cache) cache[base] = resolvedLink; - if (!isWindows) seenLinks[id] = linkTarget; + result.push(value); + } + else if (!includes(values, computed, comparator)) { + result.push(value); } - - // resolve the link, then start over - p = pathModule.resolve(resolvedLink, p.slice(pos)); - start(); } + return result; +} - if (cache) cache[original] = p; - - return p; -}; +/** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ +function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; + predicate || (predicate = isFlattenable); + result || (result = []); -exports.realpath = function realpath(p, cache, cb) { - if (typeof cb !== 'function') { - cb = maybeCallback(cache); - cache = null; + 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; +} - // make p is absolute - p = pathModule.resolve(p); - - if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { - return process.nextTick(cb.bind(null, null, cache[p])); +/** + * 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) || isHostObject(value)) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); +} - var original = p, - seenLinks = {}, - knownHard = {}; - - // current character position in p - var pos; - // the partial path so far, including a trailing slash if any - var current; - // the partial path without a trailing slash (except when pointing at a root) - var base; - // the partial path scanned in the previous round, with slash - var previous; - - start(); +/** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ +function baseRest(func, start) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); - function start() { - // Skip over roots - var m = splitRootRe.exec(p); - pos = m[0].length; - current = m[0]; - base = m[0]; - previous = ''; - - // On windows, check that the root exists. On unix there is no need. - if (isWindows && !knownHard[base]) { - fs.lstat(base, function(err) { - if (err) return cb(err); - knownHard[base] = true; - LOOP(); - }); - } else { - process.nextTick(LOOP); - } - } - - // walk down the path, swapping out linked pathparts for their real - // values - function LOOP() { - // stop if scanned past end of path - if (pos >= p.length) { - if (cache) cache[original] = p; - return cb(null, p); - } - - // find the next part - nextPartRe.lastIndex = pos; - var result = nextPartRe.exec(p); - previous = current; - current += result[0]; - base = previous + result[1]; - pos = nextPartRe.lastIndex; - - // continue if not a symlink - if (knownHard[base] || (cache && cache[base] === base)) { - return process.nextTick(LOOP); - } - - if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { - // known symbolic link. no need to stat again. - return gotResolvedLink(cache[base]); - } - - return fs.lstat(base, gotStat); - } - - function gotStat(err, stat) { - if (err) return cb(err); - - // if not a symlink, skip to the next path part - if (!stat.isSymbolicLink()) { - knownHard[base] = true; - if (cache) cache[base] = base; - return process.nextTick(LOOP); + while (++index < length) { + array[index] = args[start + index]; } - - // stat & read the link if not read before - // call gotTarget as soon as the link target is known - // dev/ino always return 0 on windows, so skip the check. - if (!isWindows) { - var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); - if (seenLinks.hasOwnProperty(id)) { - return gotTarget(null, seenLinks[id], base); - } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; } - fs.stat(base, function(err) { - if (err) return cb(err); - - fs.readlink(base, function(err, target) { - if (!isWindows) seenLinks[id] = target; - gotTarget(err, target); - }); - }); - } - - function gotTarget(err, target, base) { - if (err) return cb(err); - - var resolvedLink = pathModule.resolve(previous, target); - if (cache) cache[base] = resolvedLink; - gotResolvedLink(resolvedLink); - } - - function gotResolvedLink(resolvedLink) { - // resolve the link, then start over - p = pathModule.resolve(resolvedLink, p.slice(pos)); - start(); - } -}; - - -/***/ }), - -/***/ 45694: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -var __webpack_unused_export__; -/* unused reexport */ __nccwpck_require__(32705) -/* unused reexport */ __nccwpck_require__(54707) -exports.Writer = __nccwpck_require__(36210) - -exports.$B = { - Reader: __nccwpck_require__(33238), - Writer: __nccwpck_require__(23604) + otherArgs[start] = array; + return apply(func, this, otherArgs); + }; } -exports.Lv = { - Reader: __nccwpck_require__(55069), - Writer: __nccwpck_require__(39359) +/** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ +function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; } -exports.rU = { - Reader: __nccwpck_require__(52919), - Writer: __nccwpck_require__(97876) +/** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ +function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; } -exports._S = { - Reader: __nccwpck_require__(40233), - Writer: __nccwpck_require__(29485) +/** + * 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]); } -__webpack_unused_export__ = __webpack_unused_export__ = exports.Lv.Reader -__webpack_unused_export__ = __webpack_unused_export__ = exports.$B.Reader -__webpack_unused_export__ = __webpack_unused_export__ = exports.rU.Reader -__webpack_unused_export__ = __webpack_unused_export__ = exports._S.Reader - -exports.Writer.Dir = __webpack_unused_export__ = exports.Lv.Writer -exports.Writer.File = __webpack_unused_export__ = exports.$B.Writer -exports.Writer.Link = __webpack_unused_export__ = exports.rU.Writer -exports.Writer.Proxy = __webpack_unused_export__ = exports._S.Writer - -/* unused reexport */ __nccwpck_require__(48324) - - -/***/ }), +/** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ +function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); +} -/***/ 32705: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ +function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); +} -// the parent class for all fstreams. +/** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to process. + * @returns {string} Returns the source code. + */ +function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; +} -module.exports = Abstract +/** + * 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 of result values is determined by the + * order they occur in the first array. + * + * **Note:** Unlike `_.pullAll`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.without, _.xor + * @example + * + * _.difference([2, 1], [2, 3]); + * // => [1] + */ +var difference = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) + : []; +}); -var Stream = (__nccwpck_require__(12781).Stream) -var inherits = __nccwpck_require__(42991) +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); +} -function Abstract () { - Stream.call(this) +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); } -inherits(Abstract, Stream) +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; -Abstract.prototype.on = function (ev, fn) { - if (ev === 'ready' && this.ready) { - process.nextTick(fn.bind(this)) - } else { - Stream.prototype.on.call(this, ev, fn) - } - return this +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); } -Abstract.prototype.abort = function () { - this._aborted = true - this.emit('abort') +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); } -Abstract.prototype.destroy = function () {} - -Abstract.prototype.warn = function (msg, code) { - var self = this - var er = decorate(msg, code, self) - if (!self.listeners('warn')) { - console.error('%s %s\n' + - 'path = %s\n' + - 'syscall = %s\n' + - 'fstream_type = %s\n' + - 'fstream_path = %s\n' + - 'fstream_unc_path = %s\n' + - 'fstream_class = %s\n' + - 'fstream_stack =\n%s\n', - code || 'UNKNOWN', - er.stack, - er.path, - er.syscall, - er.fstream_type, - er.fstream_path, - er.fstream_unc_path, - er.fstream_class, - er.fstream_stack.join('\n')) - } else { - self.emit('warn', er) - } +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; } -Abstract.prototype.info = function (msg, code) { - this.emit('info', msg, code) +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } -Abstract.prototype.error = function (msg, code, th) { - var er = decorate(msg, code, this) - if (th) throw er - else this.emit('error', er) +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); } -function decorate (er, code, self) { - if (!(er instanceof Error)) er = new Error(er) - er.code = er.code || code - er.path = er.path || self.path - er.fstream_type = er.fstream_type || self.type - er.fstream_path = er.fstream_path || self.path - if (self._path !== self.path) { - er.fstream_unc_path = er.fstream_unc_path || self._path - } - if (self.linkpath) { - er.fstream_linkpath = er.fstream_linkpath || self.linkpath - } - er.fstream_class = er.fstream_class || self.constructor.name - er.fstream_stack = er.fstream_stack || - new Error().stack.split(/\n/).slice(3).map(function (s) { - return s.replace(/^ {4}at /, '') - }) - - return er +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; } +module.exports = difference; + /***/ }), -/***/ 48324: +/***/ 48919: /***/ ((module) => { -module.exports = collect +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; -function collect (stream) { - if (stream._collected) return +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]'; - if (stream._paused) return stream.on('resume', collect.bind(null, stream)) +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - stream._collected = true - stream.pause() +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - stream.on('data', save) - stream.on('end', save) - var buf = [] - function save (b) { - if (typeof b === 'string') b = new Buffer(b) - if (Buffer.isBuffer(b) && !b.length) return - buf.push(b) - } +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); - stream.on('entry', saveEntry) - var entryBuffer = [] - function saveEntry (e) { - collect(e) - entryBuffer.push(e) - } +/** + * 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; - stream.on('proxy', proxyPause) - function proxyPause (p) { - p.pause() + while (++index < length) { + array[offset + index] = values[index]; } + return array; +} - // replace the pipe method with a new version that will - // unlock the buffered stuff. if you just call .pipe() - // without a destination, then it'll re-play the events. - stream.pipe = (function (orig) { - return function (dest) { - // console.error(' === open the pipes', dest && dest.path) - - // let the entries flow through one at a time. - // Once they're all done, then we can resume completely. - var e = 0 - ;(function unblockEntry () { - var entry = entryBuffer[e++] - // console.error(" ==== unblock entry", entry && entry.path) - if (!entry) return resume() - entry.on('end', unblockEntry) - if (dest) dest.add(entry) - else stream.emit('entry', entry) - })() +/** Used for built-in method references. */ +var objectProto = Object.prototype; - function resume () { - stream.removeListener('entry', saveEntry) - stream.removeListener('data', save) - stream.removeListener('end', save) +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - stream.pipe = orig - if (dest) stream.pipe(dest) - - buf.forEach(function (b) { - if (b) stream.emit('data', b) - else stream.emit('end') - }) - - stream.resume() - } - - return dest - } - })(stream.pipe) -} - - -/***/ }), - -/***/ 55069: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -// A thing that emits "entry" events with Reader objects -// Pausing it causes it to stop emitting entry events, and also -// pauses the current entry if there is one. - -module.exports = DirReader - -var fs = __nccwpck_require__(91468) -var inherits = __nccwpck_require__(42991) -var path = __nccwpck_require__(71017) -var Reader = __nccwpck_require__(54707) -var assert = (__nccwpck_require__(39491).ok) - -inherits(DirReader, Reader) +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; -function DirReader (props) { - var self = this - if (!(self instanceof DirReader)) { - throw new Error('DirReader must be called as constructor.') - } +/** Built-in value references. */ +var Symbol = root.Symbol, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; - // should already be established as a Directory type - if (props.type !== 'Directory' || !props.Directory) { - throw new Error('Non-directory type ' + props.type) - } +/** + * 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; - self.entries = null - self._index = -1 - self._paused = false - self._length = -1 + predicate || (predicate = isFlattenable); + result || (result = []); - if (props.sort) { - this.sort = props.sort + 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; + } } - - Reader.call(this, props) + return result; } -DirReader.prototype._getEntries = function () { - var self = this - - // race condition. might pause() before calling _getEntries, - // and then resume, and try to get them a second time. - if (self._gotEntries) return - self._gotEntries = true +/** + * 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]); +} - fs.readdir(self._path, function (er, entries) { - if (er) return self.error(er) +/** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */ +function flatten(array) { + var length = array ? array.length : 0; + return length ? baseFlatten(array, 1) : []; +} - self.entries = entries +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} - self.emit('entries', entries) - if (self._paused) self.once('resume', processEntries) - else processEntries() +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; - function processEntries () { - self._length = self.entries.length - if (typeof self.sort === 'function') { - self.entries = self.entries.sort(self.sort.bind(self)) - } - self._read() - } - }) +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); } -// start walking the dir, and emit an "entry" event for each one. -DirReader.prototype._read = function () { - var self = this - - if (!self.entries) return self._getEntries() +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} - if (self._paused || self._currentEntry || self._aborted) { - // console.error('DR paused=%j, current=%j, aborted=%j', self._paused, !!self._currentEntry, self._aborted) - return - } +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} - self._index++ - if (self._index >= self.entries.length) { - if (!self._ended) { - self._ended = true - self.emit('end') - self.emit('close') - } - return - } +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} - // ok, handle this one, then. +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} - // save creating a proxy, by stat'ing the thing now. - var p = path.resolve(self._path, self.entries[self._index]) - assert(p !== self._path) - assert(self.entries[self._index]) +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - // set this to prevent trying to _read() again in the stat time. - self._currentEntry = p - fs[ self.props.follow ? 'stat' : 'lstat' ](p, function (er, stat) { - if (er) return self.error(er) +module.exports = flatten; - var who = self._proxy || self - stat.path = p - stat.basename = path.basename(p) - stat.dirname = path.dirname(p) - var childProps = self.getChildProps.call(who, stat) - childProps.path = p - childProps.basename = path.basename(p) - childProps.dirname = path.dirname(p) +/***/ }), - var entry = Reader(childProps, stat) +/***/ 25723: +/***/ ((module) => { - // console.error("DR Entry", p, stat.size) +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ - self._currentEntry = entry +/** `Object#toString` result references. */ +var objectTag = '[object Object]'; - // "entry" events are for direct entries in a specific dir. - // "child" events are for any and all children at all levels. - // This nomenclature is not completely final. +/** + * Checks if `value` is a host object in IE < 9. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a host object, else `false`. + */ +function isHostObject(value) { + // Many host objects are `Object` objects that can coerce to strings + // despite having improperly defined `toString` methods. + var result = false; + if (value != null && typeof value.toString != 'function') { + try { + result = !!(value + ''); + } catch (e) {} + } + return result; +} - entry.on('pause', function (who) { - if (!self._paused && !entry._disowned) { - self.pause(who) - } - }) +/** + * 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)); + }; +} - entry.on('resume', function (who) { - if (self._paused && !entry._disowned) { - self.resume(who) - } - }) +/** Used for built-in method references. */ +var funcProto = Function.prototype, + objectProto = Object.prototype; - entry.on('stat', function (props) { - self.emit('_entryStat', entry, props) - if (entry._aborted) return - if (entry._paused) { - entry.once('resume', function () { - self.emit('entryStat', entry, props) - }) - } else self.emit('entryStat', entry, props) - }) +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; - entry.on('ready', function EMITCHILD () { - // console.error("DR emit child", entry._path) - if (self._paused) { - // console.error(" DR emit child - try again later") - // pause the child, and emit the "entry" event once we drain. - // console.error("DR pausing child entry") - entry.pause(self) - return self.once('resume', EMITCHILD) - } - - // skip over sockets. they can't be piped around properly, - // so there's really no sense even acknowledging them. - // if someone really wants to see them, they can listen to - // the "socket" events. - if (entry.type === 'Socket') { - self.emit('socket', entry) - } else { - self.emitEntry(entry) - } - }) +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - var ended = false - entry.on('close', onend) - entry.on('disown', onend) - function onend () { - if (ended) return - ended = true - self.emit('childEnd', entry) - self.emit('entryEnd', entry) - self._currentEntry = null - if (!self._paused) { - self._read() - } - } - - // XXX Remove this. Works in node as of 0.6.2 or so. - // Long filenames should not break stuff. - entry.on('error', function (er) { - if (entry._swallowErrors) { - self.warn(er) - entry.emit('end') - entry.emit('close') - } else { - self.emit('error', er) - } - }) +/** Used to infer the `Object` constructor. */ +var objectCtorString = funcToString.call(Object); - // proxy up some events. - ;[ - 'child', - 'childEnd', - 'warn' - ].forEach(function (ev) { - entry.on(ev, self.emit.bind(self, ev)) - }) - }) -} +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; -DirReader.prototype.disown = function (entry) { - entry.emit('beforeDisown') - entry._disowned = true - entry.parent = entry.root = null - if (entry === this._currentEntry) { - this._currentEntry = null - } - entry.emit('disown') -} +/** Built-in value references. */ +var getPrototype = overArg(Object.getPrototypeOf, Object); -DirReader.prototype.getChildProps = function () { - return { - depth: this.depth + 1, - root: this.root || this, - parent: this, - follow: this.follow, - filter: this.filter, - sort: this.props.sort, - hardlinks: this.props.hardlinks - } +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; } -DirReader.prototype.pause = function (who) { - var self = this - if (self._paused) return - who = who || self - self._paused = true - if (self._currentEntry && self._currentEntry.pause) { - self._currentEntry.pause(who) +/** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ +function isPlainObject(value) { + if (!isObjectLike(value) || + objectToString.call(value) != objectTag || isHostObject(value)) { + return false; } - self.emit('pause', who) -} - -DirReader.prototype.resume = function (who) { - var self = this - if (!self._paused) return - who = who || self - - self._paused = false - // console.error('DR Emit Resume', self._path) - self.emit('resume', who) - if (self._paused) { - // console.error('DR Re-paused', self._path) - return + var proto = getPrototype(value); + if (proto === null) { + return true; } - - if (self._currentEntry) { - if (self._currentEntry.resume) self._currentEntry.resume(who) - } else self._read() + var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + return (typeof Ctor == 'function' && + Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); } -DirReader.prototype.emitEntry = function (entry) { - this.emit('entry', entry) - this.emit('child', entry) -} +module.exports = isPlainObject; /***/ }), -/***/ 39359: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -// It is expected that, when .add() returns false, the consumer -// of the DirWriter will pause until a "drain" event occurs. Note -// that this is *almost always going to be the case*, unless the -// thing being written is some sort of unsupported type, and thus -// skipped over. +/***/ 28651: +/***/ ((module) => { -module.exports = DirWriter +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ -var Writer = __nccwpck_require__(36210) -var inherits = __nccwpck_require__(42991) -var mkdir = __nccwpck_require__(19927) -var path = __nccwpck_require__(71017) -var collect = __nccwpck_require__(48324) +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE = 200; -inherits(DirWriter, Writer) +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; -function DirWriter (props) { - var self = this - if (!(self instanceof DirWriter)) { - self.error('DirWriter must be called as constructor.', null, true) - } +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991; - // should already be established as a Directory type - if (props.type !== 'Directory' || !props.Directory) { - self.error('Non-directory type ' + props.type + ' ' + - JSON.stringify(props), null, true) - } +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]'; - Writer.call(this, props) -} +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; -DirWriter.prototype._create = function () { - var self = this - mkdir(self._path, Writer.dirmode, function (er) { - if (er) return self.error(er) - // ready to start getting entries! - self.ready = true - self.emit('ready') - self._process() - }) -} +/** Used to detect host constructors (Safari). */ +var reIsHostCtor = /^\[object .+?Constructor\]$/; -// a DirWriter has an add(entry) method, but its .write() doesn't -// do anything. Why a no-op rather than a throw? Because this -// leaves open the door for writing directory metadata for -// gnu/solaris style dumpdirs. -DirWriter.prototype.write = function () { - return true -} +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; -DirWriter.prototype.end = function () { - this._ended = true - this._process() -} +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; -DirWriter.prototype.add = function (entry) { - var self = this +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); - // console.error('\tadd', entry._path, '->', self._path) - collect(entry) - if (!self.ready || self._currentEntry) { - self._buffer.push(entry) - return false - } - - // create a new writer, and pipe the incoming entry into it. - if (self._ended) { - return self.error('add after end') +/** + * 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]); } - - self._buffer.push(entry) - self._process() - - return this._buffer.length === 0 + return func.apply(thisArg, args); } -DirWriter.prototype._process = function () { - var self = this - - // console.error('DW Process p=%j', self._processing, self.basename) - - if (self._processing) return - - var entry = self._buffer.shift() - if (!entry) { - // console.error("DW Drain") - self.emit('drain') - if (self._ended) self._finish() - return - } - - self._processing = true - // console.error("DW Entry", entry._path) - - self.emit('entry', entry) - - // ok, add this entry - // - // don't allow recursive copying - var p = entry - var pp - do { - pp = p._path || p.path - if (pp === self.root._path || pp === self._path || - (pp && pp.indexOf(self._path) === 0)) { - // console.error('DW Exit (recursive)', entry.basename, self._path) - self._processing = false - if (entry._collected) entry.pipe() - return self._process() - } - p = p.parent - } while (p) - - // console.error("DW not recursive") - - // chop off the entry's root dir, replace with ours - var props = { - parent: self, - root: self.root || self, - type: entry.type, - depth: self.depth + 1 - } - - pp = entry._path || entry.path || entry.props.path - if (entry.parent) { - pp = pp.substr(entry.parent._path.length + 1) - } - // get rid of any ../../ shenanigans - props.path = path.join(self.path, path.join('/', pp)) - - // if i have a filter, the child should inherit it. - props.filter = self.filter - - // all the rest of the stuff, copy over from the source. - Object.keys(entry.props).forEach(function (k) { - if (!props.hasOwnProperty(k)) { - props[k] = entry.props[k] - } - }) +/** + * 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 ? array.length : 0; + return !!length && baseIndexOf(array, value, 0) > -1; +} - // not sure at this point what kind of writer this is. - var child = self._currentChild = new Writer(props) - child.on('ready', function () { - // console.error("DW Child Ready", child.type, child._path) - // console.error(" resuming", entry._path) - entry.pipe(child) - entry.resume() - }) +/** + * 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 ? array.length : 0; - // XXX Make this work in node. - // Long filenames should not break stuff. - child.on('error', function (er) { - if (child._swallowErrors) { - self.warn(er) - child.emit('end') - child.emit('close') - } else { - self.emit('error', er) + while (++index < length) { + if (comparator(value, array[index])) { + return true; } - }) - - // we fire _end internally *after* end, so that we don't move on - // until any "end" listeners have had their chance to do stuff. - child.on('close', onend) - var ended = false - function onend () { - if (ended) return - ended = true - // console.error("* DW Child end", child.basename) - self._currentChild = null - self._processing = false - self._process() } + return false; } +/** + * 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; -/***/ }), - -/***/ 33238: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -// Basically just a wrapper around an fs.ReadStream - -module.exports = FileReader - -var fs = __nccwpck_require__(91468) -var inherits = __nccwpck_require__(42991) -var Reader = __nccwpck_require__(54707) -var EOF = {EOF: true} -var CLOSE = {CLOSE: true} - -inherits(FileReader, Reader) - -function FileReader (props) { - // console.error(" FR create", props.path, props.size, new Error().stack) - var self = this - if (!(self instanceof FileReader)) { - throw new Error('FileReader must be called as constructor.') - } - - // should already be established as a File type - // XXX Todo: preserve hardlinks by tracking dev+inode+nlink, - // with a HardLinkReader class. - if (!((props.type === 'Link' && props.Link) || - (props.type === 'File' && props.File))) { - throw new Error('Non-file type ' + props.type) + while (++index < length) { + array[offset + index] = values[index]; } - - self._buffer = [] - self._bytesEmitted = 0 - Reader.call(self, props) + return array; } -FileReader.prototype._getStream = function () { - var self = this - var stream = self._stream = fs.createReadStream(self._path, self.props) - - if (self.props.blksize) { - stream.bufferSize = self.props.blksize - } - - stream.on('open', self.emit.bind(self, 'open')) - - stream.on('data', function (c) { - // console.error('\t\t%d %s', c.length, self.basename) - self._bytesEmitted += c.length - // no point saving empty chunks - if (!c.length) { - return - } else if (self._paused || self._buffer.length) { - self._buffer.push(c) - self._read() - } else self.emit('data', c) - }) - - stream.on('end', function () { - if (self._paused || self._buffer.length) { - // console.error('FR Buffering End', self._path) - self._buffer.push(EOF) - self._read() - } else { - self.emit('end') - } - - if (self._bytesEmitted !== self.props.size) { - self.error("Didn't get expected byte count\n" + - 'expect: ' + self.props.size + '\n' + - 'actual: ' + self._bytesEmitted) - } - }) +/** + * 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); - stream.on('close', function () { - if (self._paused || self._buffer.length) { - // console.error('FR Buffering Close', self._path) - self._buffer.push(CLOSE) - self._read() - } else { - // console.error('FR close 1', self._path) - self.emit('close') + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; } - }) - - stream.on('error', function (e) { - self.emit('error', e) - }) - - self._read() -} - -FileReader.prototype._read = function () { - var self = this - // console.error('FR _read', self._path) - if (self._paused) { - // console.error('FR _read paused', self._path) - return } + return -1; +} - if (!self._stream) { - // console.error('FR _getStream calling', self._path) - return self._getStream() +/** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseIndexOf(array, value, fromIndex) { + if (value !== value) { + return baseFindIndex(array, baseIsNaN, fromIndex); } + var index = fromIndex - 1, + length = array.length; - // clear out the buffer, if there is one. - if (self._buffer.length) { - // console.error('FR _read has buffer', self._buffer.length, self._path) - var buf = self._buffer - for (var i = 0, l = buf.length; i < l; i++) { - var c = buf[i] - if (c === EOF) { - // console.error('FR Read emitting buffered end', self._path) - self.emit('end') - } else if (c === CLOSE) { - // console.error('FR Read emitting buffered close', self._path) - self.emit('close') - } else { - // console.error('FR Read emitting buffered data', self._path) - self.emit('data', c) - } - - if (self._paused) { - // console.error('FR Read Re-pausing at '+i, self._path) - self._buffer = buf.slice(i) - return - } + while (++index < length) { + if (array[index] === value) { + return index; } - self._buffer.length = 0 } -// console.error("FR _read done") -// that's about all there is to it. + return -1; } -FileReader.prototype.pause = function (who) { - var self = this - // console.error('FR Pause', self._path) - if (self._paused) return - who = who || self - self._paused = true - if (self._stream) self._stream.pause() - self.emit('pause', who) +/** + * 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; } -FileReader.prototype.resume = function (who) { - var self = this - // console.error('FR Resume', self._path) - if (!self._paused) return - who = who || self - self.emit('resume', who) - self._paused = false - if (self._stream) self._stream.resume() - self._read() +/** + * 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); } +/** + * 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]; +} -/***/ }), - -/***/ 23604: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = FileWriter - -var fs = __nccwpck_require__(91468) -var Writer = __nccwpck_require__(36210) -var inherits = __nccwpck_require__(42991) -var EOF = {} - -inherits(FileWriter, Writer) - -function FileWriter (props) { - var self = this - if (!(self instanceof FileWriter)) { - throw new Error('FileWriter must be called as constructor.') - } - - // should already be established as a File type - if (props.type !== 'File' || !props.File) { - throw new Error('Non-file type ' + props.type) +/** + * Checks if `value` is a host object in IE < 9. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a host object, else `false`. + */ +function isHostObject(value) { + // Many host objects are `Object` objects that can coerce to strings + // despite having improperly defined `toString` methods. + var result = false; + if (value != null && typeof value.toString != 'function') { + try { + result = !!(value + ''); + } catch (e) {} } + return result; +} - self._buffer = [] - self._bytesWritten = 0 +/** + * 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); - Writer.call(this, props) + set.forEach(function(value) { + result[++index] = value; + }); + return result; } -FileWriter.prototype._create = function () { - var self = this - if (self._stream) return +/** Used for built-in method references. */ +var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; - var so = {} - if (self.props.flags) so.flags = self.props.flags - so.mode = Writer.filemode - if (self._old && self._old.blksize) so.bufferSize = self._old.blksize +/** Used to detect overreaching core-js shims. */ +var coreJsData = root['__core-js_shared__']; - self._stream = fs.createWriteStream(self._path, so) +/** 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) : ''; +}()); - self._stream.on('open', function () { - // console.error("FW open", self._buffer, self._path) - self.ready = true - self._buffer.forEach(function (c) { - if (c === EOF) self._stream.end() - else self._stream.write(c) - }) - self.emit('ready') - // give this a kick just in case it needs it. - self.emit('drain') - }) +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; - self._stream.on('error', function (er) { self.emit('error', er) }) +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - self._stream.on('drain', function () { self.emit('drain') }) +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - self._stream.on('close', function () { - // console.error('\n\nFW Stream Close', self._path, self.size) - self._finish() - }) -} +/** Used to detect if a method is native. */ +var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' +); -FileWriter.prototype.write = function (c) { - var self = this +/** Built-in value references. */ +var Symbol = root.Symbol, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; - self._bytesWritten += c.length +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; - if (!self.ready) { - if (!Buffer.isBuffer(c) && typeof c !== 'string') { - throw new Error('invalid write data') - } - self._buffer.push(c) - return false - } +/* Built-in method references that are verified to be native. */ +var Map = getNative(root, 'Map'), + Set = getNative(root, 'Set'), + nativeCreate = getNative(Object, 'create'); - var ret = self._stream.write(c) - // console.error('\t-- fw wrote, _stream says', ret, self._stream._queue.length) +/** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Hash(entries) { + var index = -1, + length = entries ? entries.length : 0; - // allow 2 buffered writes, because otherwise there's just too - // much stop and go bs. - if (ret === false && self._stream._queue) { - return self._stream._queue.length <= 2 - } else { - return ret + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); } } -FileWriter.prototype.end = function (c) { - var self = this - - if (c) self.write(c) - - if (!self.ready) { - self._buffer.push(EOF) - return false - } - - return self._stream.end() +/** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ +function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; } -FileWriter.prototype._finish = function () { - var self = this - if (typeof self.size === 'number' && self._bytesWritten !== self.size) { - self.error( - 'Did not get expected byte count.\n' + - 'expect: ' + self.size + '\n' + - 'actual: ' + self._bytesWritten) - } - Writer.prototype._finish.call(self) +/** + * 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) { + return this.has(key) && delete this.__data__[key]; } - -/***/ }), - -/***/ 53494: -/***/ ((module) => { - -module.exports = getType - -function getType (st) { - var types = [ - 'Directory', - 'File', - 'SymbolicLink', - 'Link', // special for hardlinks from tarballs - 'BlockDevice', - 'CharacterDevice', - 'FIFO', - 'Socket' - ] - var type - - if (st.type && types.indexOf(st.type) !== -1) { - st[st.type] = true - return st.type - } - - for (var i = 0, l = types.length; i < l; i++) { - type = types[i] - var is = st[type] || st['is' + type] - if (typeof is === 'function') is = is.call(st) - if (is) { - st[type] = true - st.type = type - return type - } +/** + * 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 null + return hasOwnProperty.call(data, key) ? data[key] : undefined; } +/** + * 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); +} -/***/ }), - -/***/ 52919: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -// Basically just a wrapper around an fs.readlink -// -// XXX: Enhance this to support the Link type, by keeping -// a lookup table of {:}, so that hardlinks -// can be preserved in tarballs. - -module.exports = LinkReader - -var fs = __nccwpck_require__(91468) -var inherits = __nccwpck_require__(42991) -var Reader = __nccwpck_require__(54707) +/** + * 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__; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; +} -inherits(LinkReader, Reader) +// Add methods to `Hash`. +Hash.prototype.clear = hashClear; +Hash.prototype['delete'] = hashDelete; +Hash.prototype.get = hashGet; +Hash.prototype.has = hashHas; +Hash.prototype.set = hashSet; -function LinkReader (props) { - var self = this - if (!(self instanceof LinkReader)) { - throw new Error('LinkReader must be called as constructor.') - } +/** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function ListCache(entries) { + var index = -1, + length = entries ? entries.length : 0; - if (!((props.type === 'Link' && props.Link) || - (props.type === 'SymbolicLink' && props.SymbolicLink))) { - throw new Error('Non-link type ' + props.type) + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); } - - Reader.call(self, props) } -// When piping a LinkReader into a LinkWriter, we have to -// already have the linkpath property set, so that has to -// happen *before* the "ready" event, which means we need to -// override the _stat method. -LinkReader.prototype._stat = function (currentStat) { - var self = this - fs.readlink(self._path, function (er, linkpath) { - if (er) return self.error(er) - self.linkpath = self.props.linkpath = linkpath - self.emit('linkpath', linkpath) - Reader.prototype._stat.call(self, currentStat) - }) -} - -LinkReader.prototype._read = function () { - var self = this - if (self._paused) return - // basically just a no-op, since we got all the info we need - // from the _stat method - if (!self._ended) { - self.emit('end') - self.emit('close') - self._ended = true - } +/** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ +function listCacheClear() { + this.__data__ = []; } +/** + * 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); -/***/ }), - -/***/ 97876: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = LinkWriter - -var fs = __nccwpck_require__(91468) -var Writer = __nccwpck_require__(36210) -var inherits = __nccwpck_require__(42991) -var path = __nccwpck_require__(71017) -var rimraf = __nccwpck_require__(9651) - -inherits(LinkWriter, Writer) - -function LinkWriter (props) { - var self = this - if (!(self instanceof LinkWriter)) { - throw new Error('LinkWriter must be called as constructor.') - } - - // should already be established as a Link type - if (!((props.type === 'Link' && props.Link) || - (props.type === 'SymbolicLink' && props.SymbolicLink))) { - throw new Error('Non-link type ' + props.type) + if (index < 0) { + return false; } - - if (props.linkpath === '') props.linkpath = '.' - if (!props.linkpath) { - self.error('Need linkpath property to create ' + props.type) + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); } - - Writer.call(this, props) + return true; } -LinkWriter.prototype._create = function () { - // console.error(" LW _create") - var self = this - var hard = self.type === 'Link' || process.platform === 'win32' - var link = hard ? 'link' : 'symlink' - var lp = hard ? path.resolve(self.dirname, self.linkpath) : self.linkpath - - // can only change the link path by clobbering - // For hard links, let's just assume that's always the case, since - // there's no good way to read them if we don't already know. - if (hard) return clobber(self, lp, link) - - fs.readlink(self._path, function (er, p) { - // only skip creation if it's exactly the same link - if (p && p === lp) return finish(self) - clobber(self, lp, link) - }) -} +/** + * 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); -function clobber (self, lp, link) { - rimraf(self._path, function (er) { - if (er) return self.error(er) - create(self, lp, link) - }) + return index < 0 ? undefined : data[index][1]; } -function create (self, lp, link) { - fs[link](lp, self._path, function (er) { - // if this is a hard link, and we're in the process of writing out a - // directory, it's very possible that the thing we're linking to - // doesn't exist yet (especially if it was intended as a symlink), - // so swallow ENOENT errors here and just soldier in. - // Additionally, an EPERM or EACCES can happen on win32 if it's trying - // to make a link to a directory. Again, just skip it. - // A better solution would be to have fs.symlink be supported on - // windows in some nice fashion. - if (er) { - if ((er.code === 'ENOENT' || - er.code === 'EACCES' || - er.code === 'EPERM') && process.platform === 'win32') { - self.ready = true - self.emit('ready') - self.emit('end') - self.emit('close') - self.end = self._finish = function () {} - } else return self.error(er) - } - finish(self) - }) +/** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; } -function finish (self) { - self.ready = true - self.emit('ready') - if (self._ended && !self._finished) self._finish() -} +/** + * 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); -LinkWriter.prototype.end = function () { - // console.error("LW finish in end") - this._ended = true - if (this.ready) { - this._finished = true - this._finish() + if (index < 0) { + data.push([key, value]); + } else { + data[index][1] = value; } + return this; } +// Add methods to `ListCache`. +ListCache.prototype.clear = listCacheClear; +ListCache.prototype['delete'] = listCacheDelete; +ListCache.prototype.get = listCacheGet; +ListCache.prototype.has = listCacheHas; +ListCache.prototype.set = listCacheSet; -/***/ }), - -/***/ 40233: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -// A reader for when we don't yet know what kind of thing -// the thing is. - -module.exports = ProxyReader - -var Reader = __nccwpck_require__(54707) -var getType = __nccwpck_require__(53494) -var inherits = __nccwpck_require__(42991) -var fs = __nccwpck_require__(91468) - -inherits(ProxyReader, Reader) +/** + * 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 ? entries.length : 0; -function ProxyReader (props) { - var self = this - if (!(self instanceof ProxyReader)) { - throw new Error('ProxyReader must be called as constructor.') + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); } - - self.props = props - self._buffer = [] - self.ready = false - - Reader.call(self, props) -} - -ProxyReader.prototype._stat = function () { - var self = this - var props = self.props - // stat the thing to see what the proxy should be. - var stat = props.follow ? 'stat' : 'lstat' - - fs[stat](props.path, function (er, current) { - var type - if (er || !current) { - type = 'File' - } else { - type = getType(current) - } - - props[type] = true - props.type = self.type = type - - self._old = current - self._addProxy(Reader(props, current)) - }) } -ProxyReader.prototype._addProxy = function (proxy) { - var self = this - if (self._proxyTarget) { - return self.error('proxy already set') - } - - self._proxyTarget = proxy - proxy._proxy = self - - ;[ - 'error', - 'data', - 'end', - 'close', - 'linkpath', - 'entry', - 'entryEnd', - 'child', - 'childEnd', - 'warn', - 'stat' - ].forEach(function (ev) { - // console.error('~~ proxy event', ev, self.path) - proxy.on(ev, self.emit.bind(self, ev)) - }) - - self.emit('proxy', proxy) - - proxy.on('ready', function () { - // console.error("~~ proxy is ready!", self.path) - self.ready = true - self.emit('ready') - }) - - var calls = self._buffer - self._buffer.length = 0 - calls.forEach(function (c) { - proxy[c[0]].apply(proxy, c[1]) - }) +/** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ +function mapCacheClear() { + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; } -ProxyReader.prototype.pause = function () { - return this._proxyTarget ? this._proxyTarget.pause() : false +/** + * 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) { + return getMapData(this, key)['delete'](key); } -ProxyReader.prototype.resume = function () { - return this._proxyTarget ? this._proxyTarget.resume() : false +/** + * 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); } - -/***/ }), - -/***/ 29485: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -// A writer for when we don't know what kind of thing -// the thing is. That is, it's not explicitly set, -// so we're going to make it whatever the thing already -// is, or "File" -// -// Until then, collect all events. - -module.exports = ProxyWriter - -var Writer = __nccwpck_require__(36210) -var getType = __nccwpck_require__(53494) -var inherits = __nccwpck_require__(42991) -var collect = __nccwpck_require__(48324) -var fs = __nccwpck_require__(57147) - -inherits(ProxyWriter, Writer) - -function ProxyWriter (props) { - var self = this - if (!(self instanceof ProxyWriter)) { - throw new Error('ProxyWriter must be called as constructor.') - } - - self.props = props - self._needDrain = false - - Writer.call(self, props) +/** + * 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); } -ProxyWriter.prototype._stat = function () { - var self = this - var props = self.props - // stat the thing to see what the proxy should be. - var stat = props.follow ? 'stat' : 'lstat' - - fs[stat](props.path, function (er, current) { - var type - if (er || !current) { - type = 'File' - } else { - type = getType(current) - } - - props[type] = true - props.type = self.type = type - - self._old = current - self._addProxy(Writer(props, current)) - }) +/** + * 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) { + getMapData(this, key).set(key, value); + return this; } -ProxyWriter.prototype._addProxy = function (proxy) { - // console.error("~~ set proxy", this.path) - var self = this - if (self._proxy) { - return self.error('proxy already set') - } - - self._proxy = proxy - ;[ - 'ready', - 'error', - 'close', - 'pipe', - 'drain', - 'warn' - ].forEach(function (ev) { - proxy.on(ev, self.emit.bind(self, ev)) - }) - - self.emit('proxy', proxy) - - var calls = self._buffer - calls.forEach(function (c) { - // console.error("~~ ~~ proxy buffered call", c[0], c[1]) - proxy[c[0]].apply(proxy, c[1]) - }) - self._buffer.length = 0 - if (self._needsDrain) self.emit('drain') -} +// Add methods to `MapCache`. +MapCache.prototype.clear = mapCacheClear; +MapCache.prototype['delete'] = mapCacheDelete; +MapCache.prototype.get = mapCacheGet; +MapCache.prototype.has = mapCacheHas; +MapCache.prototype.set = mapCacheSet; -ProxyWriter.prototype.add = function (entry) { - // console.error("~~ proxy add") - collect(entry) +/** + * + * 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 ? values.length : 0; - if (!this._proxy) { - this._buffer.push(['add', [entry]]) - this._needDrain = true - return false + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); } - return this._proxy.add(entry) } -ProxyWriter.prototype.write = function (c) { - // console.error('~~ proxy write') - if (!this._proxy) { - this._buffer.push(['write', [c]]) - this._needDrain = true - return false - } - return this._proxy.write(c) +/** + * 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; } -ProxyWriter.prototype.end = function (c) { - // console.error('~~ proxy end') - if (!this._proxy) { - this._buffer.push(['end', [c]]) - return false - } - return this._proxy.end(c) +/** + * 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); } +// Add methods to `SetCache`. +SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; +SetCache.prototype.has = setCacheHas; -/***/ }), - -/***/ 54707: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = Reader - -var fs = __nccwpck_require__(91468) -var Stream = (__nccwpck_require__(12781).Stream) -var inherits = __nccwpck_require__(42991) -var path = __nccwpck_require__(71017) -var getType = __nccwpck_require__(53494) -var hardLinks = Reader.hardLinks = {} -var Abstract = __nccwpck_require__(32705) - -// Must do this *before* loading the child classes -inherits(Reader, Abstract) - -var LinkReader = __nccwpck_require__(52919) - -function Reader (props, currentStat) { - var self = this - if (!(self instanceof Reader)) return new Reader(props, currentStat) - - if (typeof props === 'string') { - props = { path: props } - } - - // polymorphism. - // call fstream.Reader(dir) to get a DirReader object, etc. - // Note that, unlike in the Writer case, ProxyReader is going - // to be the *normal* state of affairs, since we rarely know - // the type of a file prior to reading it. - - var type - var ClassType - - if (props.type && typeof props.type === 'function') { - type = props.type - ClassType = type - } else { - type = getType(props) - ClassType = Reader - } - - if (currentStat && !type) { - type = getType(currentStat) - props[type] = true - props.type = type - } - - switch (type) { - case 'Directory': - ClassType = __nccwpck_require__(55069) - break - - case 'Link': - // XXX hard links are just files. - // However, it would be good to keep track of files' dev+inode - // and nlink values, and create a HardLinkReader that emits - // a linkpath value of the original copy, so that the tar - // writer can preserve them. - // ClassType = HardLinkReader - // break - - case 'File': - ClassType = __nccwpck_require__(33238) - break - - case 'SymbolicLink': - ClassType = LinkReader - break - - case 'Socket': - ClassType = __nccwpck_require__(68557) - break - - case null: - ClassType = __nccwpck_require__(40233) - break - } - - if (!(self instanceof ClassType)) { - return new ClassType(props) - } - - Abstract.call(self) - - if (!props.path) { - self.error('Must provide a path', null, true) +/** + * 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; +} - self.readable = true - self.writable = false +/** + * 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; - self.type = type - self.props = props - self.depth = props.depth = props.depth || 0 - self.parent = props.parent || null - self.root = props.root || (props.parent && props.parent.root) || self + predicate || (predicate = isFlattenable); + result || (result = []); - self._path = self.path = path.resolve(props.path) - if (process.platform === 'win32') { - self.path = self._path = self.path.replace(/\?/g, '_') - if (self._path.length >= 260) { - // how DOES one create files on the moon? - // if the path has spaces in it, then UNC will fail. - self._swallowErrors = true - // if (self._path.indexOf(" ") === -1) { - self._path = '\\\\?\\' + self.path.replace(/\//g, '\\') - // } + 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; } } - self.basename = props.basename = path.basename(self.path) - self.dirname = props.dirname = path.dirname(self.path) - - // these have served their purpose, and are now just noisy clutter - props.parent = props.root = null - - // console.error("\n\n\n%s setting size to", props.path, props.size) - self.size = props.size - self.filter = typeof props.filter === 'function' ? props.filter : null - if (props.sort === 'alpha') props.sort = alphasort - - // start the ball rolling. - // this will stat the thing, and then call self._read() - // to start reading whatever it is. - // console.error("calling stat", props.path, currentStat) - self._stat(currentStat) + return result; } -function alphasort (a, b) { - return a === b ? 0 - : a.toLowerCase() > b.toLowerCase() ? 1 - : a.toLowerCase() < b.toLowerCase() ? -1 - : a > b ? 1 - : -1 +/** + * 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) || isHostObject(value)) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); } -Reader.prototype._stat = function (currentStat) { - var self = this - var props = self.props - var stat = props.follow ? 'stat' : 'lstat' - // console.error("Reader._stat", self._path, currentStat) - if (currentStat) process.nextTick(statCb.bind(null, null, currentStat)) - else fs[stat](self._path, statCb) - - function statCb (er, props_) { - // console.error("Reader._stat, statCb", self._path, props_, props_.nlink) - if (er) return self.error(er) - - Object.keys(props_).forEach(function (k) { - props[k] = props_[k] - }) +/** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ +function baseRest(func, start) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); - // if it's not the expected size, then abort here. - if (undefined !== self.size && props.size !== self.size) { - return self.error('incorrect size') + while (++index < length) { + array[index] = args[start + index]; } - self.size = props.size - - var type = getType(props) - var handleHardlinks = props.hardlinks !== false - - // special little thing for handling hardlinks. - if (handleHardlinks && type !== 'Directory' && props.nlink && props.nlink > 1) { - var k = props.dev + ':' + props.ino - // console.error("Reader has nlink", self._path, k) - if (hardLinks[k] === self._path || !hardLinks[k]) { - hardLinks[k] = self._path - } else { - // switch into hardlink mode. - type = self.type = self.props.type = 'Link' - self.Link = self.props.Link = true - self.linkpath = self.props.linkpath = hardLinks[k] - // console.error("Hardlink detected, switching mode", self._path, self.linkpath) - // Setting __proto__ would arguably be the "correct" - // approach here, but that just seems too wrong. - self._stat = self._read = LinkReader.prototype._read - } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; } + otherArgs[start] = array; + return apply(func, this, otherArgs); + }; +} - if (self.type && self.type !== type) { - self.error('Unexpected type: ' + type) - } +/** + * 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; - // if the filter doesn't pass, then just skip over this one. - // still have to emit end so that dir-walking can move on. - if (self.filter) { - var who = self._proxy || self - // special handling for ProxyReaders - if (!self.filter.call(who, who, props)) { - if (!self._disowned) { - self.abort() - self.emit('end') - self.emit('close') - } - return - } + 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; - // last chance to abort or disown before the flow starts! - var events = ['_stat', 'stat', 'ready'] - var e = 0 - ;(function go () { - if (self._aborted) { - self.emit('end') - self.emit('close') - return + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } } - - if (self._paused && self.type !== 'Directory') { - self.once('resume', go) - return + if (iteratee) { + seen.push(computed); } - - var ev = events[e++] - if (!ev) { - return self._read() + result.push(value); + } + else if (!includes(seen, computed, comparator)) { + if (seen !== result) { + seen.push(computed); } - self.emit(ev, props) - go() - })() + result.push(value); + } } + return result; } -Reader.prototype.pipe = function (dest) { - var self = this - if (typeof dest.add === 'function') { - // piping to a multi-compatible, and we've got directory entries. - self.on('entry', function (entry) { - var ret = dest.add(entry) - if (ret === false) { - self.pause() - } - }) - } +/** + * 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); +}; - // console.error("R Pipe apply Stream Pipe") - return Stream.prototype.pipe.apply(this, arguments) +/** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ +function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; } -Reader.prototype.pause = function (who) { - this._paused = true - who = who || this - this.emit('pause', who) - if (this._stream) this._stream.pause(who) +/** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ +function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; } -Reader.prototype.resume = function (who) { - this._paused = false - who = who || this - this.emit('resume', who) - if (this._stream) this._stream.resume(who) - this._read() +/** + * 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]); } -Reader.prototype._read = function () { - this.error('Cannot read unknown type: ' + this.type) +/** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ +function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); } - -/***/ }), - -/***/ 68557: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -// Just get the stats, and then don't do anything. -// You can't really "read" from a socket. You "connect" to it. -// Mostly, this is here so that reading a dir with a socket in it -// doesn't blow up. - -module.exports = SocketReader - -var inherits = __nccwpck_require__(42991) -var Reader = __nccwpck_require__(54707) - -inherits(SocketReader, Reader) - -function SocketReader (props) { - var self = this - if (!(self instanceof SocketReader)) { - throw new Error('SocketReader must be called as constructor.') - } - - if (!(props.type === 'Socket' && props.Socket)) { - throw new Error('Non-socket type ' + props.type) - } - - Reader.call(self, props) +/** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ +function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); } -SocketReader.prototype._read = function () { - var self = this - if (self._paused) return - // basically just a no-op, since we got all the info we have - // from the _stat method - if (!self._ended) { - self.emit('end') - self.emit('close') - self._ended = true +/** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to process. + * @returns {string} Returns the source code. + */ +function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} } + return ''; } +/** + * 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 + * + * _.union([2], [1, 2]); + * // => [2, 1] + */ +var union = baseRest(function(arrays) { + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); +}); -/***/ }), - -/***/ 36210: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = Writer - -var fs = __nccwpck_require__(91468) -var inherits = __nccwpck_require__(42991) -var rimraf = __nccwpck_require__(9651) -var mkdir = __nccwpck_require__(19927) -var path = __nccwpck_require__(71017) -var umask = process.platform === 'win32' ? 0 : process.umask() -var getType = __nccwpck_require__(53494) -var Abstract = __nccwpck_require__(32705) - -// Must do this *before* loading the child classes -inherits(Writer, Abstract) - -Writer.dirmode = parseInt('0777', 8) & (~umask) -Writer.filemode = parseInt('0666', 8) & (~umask) - -var DirWriter = __nccwpck_require__(39359) -var LinkWriter = __nccwpck_require__(97876) -var FileWriter = __nccwpck_require__(23604) -var ProxyWriter = __nccwpck_require__(29485) - -// props is the desired state. current is optionally the current stat, -// provided here so that subclasses can avoid statting the target -// more than necessary. -function Writer (props, current) { - var self = this - - if (typeof props === 'string') { - props = { path: props } - } - - // polymorphism. - // call fstream.Writer(dir) to get a DirWriter object, etc. - var type = getType(props) - var ClassType = Writer - - switch (type) { - case 'Directory': - ClassType = DirWriter - break - case 'File': - ClassType = FileWriter - break - case 'Link': - case 'SymbolicLink': - ClassType = LinkWriter - break - case null: - default: - // Don't know yet what type to create, so we wrap in a proxy. - ClassType = ProxyWriter - break - } +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); +} - if (!(self instanceof ClassType)) return new ClassType(props) +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} - // now get down to business. +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; - Abstract.call(self) +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} - if (!props.path) self.error('Must provide a path', null, true) +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} - // props is what we want to set. - // set some convenience properties as well. - self.type = props.type - self.props = props - self.depth = props.depth || 0 - self.clobber = props.clobber === false ? props.clobber : true - self.parent = props.parent || null - self.root = props.root || (props.parent && props.parent.root) || self +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} - self._path = self.path = path.resolve(props.path) - if (process.platform === 'win32') { - self.path = self._path = self.path.replace(/\?/g, '_') - if (self._path.length >= 260) { - self._swallowErrors = true - self._path = '\\\\?\\' + self.path.replace(/\//g, '\\') - } - } - self.basename = path.basename(props.path) - self.dirname = path.dirname(props.path) - self.linkpath = props.linkpath || null +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} - props.parent = props.root = null +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} - // console.error("\n\n\n%s setting size to", props.path, props.size) - self.size = props.size +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - if (typeof props.mode === 'string') { - props.mode = parseInt(props.mode, 8) - } +/** + * This method returns `undefined`. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Util + * @example + * + * _.times(2, _.noop); + * // => [undefined, undefined] + */ +function noop() { + // No operation performed. +} - self.readable = false - self.writable = true +module.exports = union; - // buffer until ready, or while handling another entry - self._buffer = [] - self.ready = false - self.filter = typeof props.filter === 'function' ? props.filter : null +/***/ }), - // start the ball rolling. - // this checks what's there already, and then calls - // self._create() to call the impl-specific creation stuff. - self._stat(current) -} +/***/ 47426: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Calling this means that it's something we can't create. -// Just assert that it's already there, otherwise raise a warning. -Writer.prototype._create = function () { - var self = this - fs[self.props.follow ? 'stat' : 'lstat'](self._path, function (er) { - if (er) { - return self.warn('Cannot create ' + self._path + '\n' + - 'Unsupported type: ' + self.type, 'ENOTSUP') - } - self._finish() - }) -} +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015-2022 Douglas Christopher Wilson + * MIT Licensed + */ -Writer.prototype._stat = function (current) { - var self = this - var props = self.props - var stat = props.follow ? 'stat' : 'lstat' - var who = self._proxy || self - - if (current) statCb(null, current) - else fs[stat](self._path, statCb) - - function statCb (er, current) { - if (self.filter && !self.filter.call(who, who, current)) { - self._aborted = true - self.emit('end') - self.emit('close') - return - } +/** + * Module exports. + */ - // if it's not there, great. We'll just create it. - // if it is there, then we'll need to change whatever differs - if (er || !current) { - return create(self) - } +module.exports = __nccwpck_require__(53765) - self._old = current - var currentType = getType(current) - // if it's a type change, then we need to clobber or error. - // if it's not a type change, then let the impl take care of it. - if (currentType !== self.type || self.type === 'File' && current.nlink > 1) { - return rimraf(self._path, function (er) { - if (er) return self.error(er) - self._old = null - create(self) - }) - } +/***/ }), - // otherwise, just handle in the app-specific way - // this creates a fs.WriteStream, or mkdir's, or whatever - create(self) - } -} +/***/ 43583: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function create (self) { - // console.error("W create", self._path, Writer.dirmode) +"use strict"; +/*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ - // XXX Need to clobber non-dirs that are in the way, - // unless { clobber: false } in the props. - mkdir(path.dirname(self._path), Writer.dirmode, function (er, made) { - // console.error("W created", path.dirname(self._path), er) - if (er) return self.error(er) - // later on, we have to set the mode and owner for these - self._madeDir = made - return self._create() - }) -} -function endChmod (self, want, current, path, cb) { - var wantMode = want.mode - var chmod = want.follow || self.type !== 'SymbolicLink' - ? 'chmod' : 'lchmod' +/** + * Module dependencies. + * @private + */ - if (!fs[chmod]) return cb() - if (typeof wantMode !== 'number') return cb() +var db = __nccwpck_require__(47426) +var extname = (__nccwpck_require__(71017).extname) - var curMode = current.mode & parseInt('0777', 8) - wantMode = wantMode & parseInt('0777', 8) - if (wantMode === curMode) return cb() +/** + * Module variables. + * @private + */ - fs[chmod](path, wantMode, cb) -} +var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ +var TEXT_TYPE_REGEXP = /^text\//i -function endChown (self, want, current, path, cb) { - // Don't even try it unless root. Too easy to EPERM. - if (process.platform === 'win32') return cb() - if (!process.getuid || process.getuid() !== 0) return cb() - if (typeof want.uid !== 'number' && - typeof want.gid !== 'number') return cb() +/** + * Module exports. + * @public + */ - if (current.uid === want.uid && - current.gid === want.gid) return cb() +exports.charset = charset +exports.charsets = { lookup: charset } +exports.contentType = contentType +exports.extension = extension +exports.extensions = Object.create(null) +exports.lookup = lookup +exports.types = Object.create(null) - var chown = (self.props.follow || self.type !== 'SymbolicLink') - ? 'chown' : 'lchown' - if (!fs[chown]) return cb() +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) - if (typeof want.uid !== 'number') want.uid = current.uid - if (typeof want.gid !== 'number') want.gid = current.gid +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ - fs[chown](path, want.uid, want.gid, cb) -} +function charset (type) { + if (!type || typeof type !== 'string') { + return false + } -function endUtimes (self, want, current, path, cb) { - if (!fs.utimes || process.platform === 'win32') return cb() + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + var mime = match && db[match[1].toLowerCase()] - var utimes = (want.follow || self.type !== 'SymbolicLink') - ? 'utimes' : 'lutimes' + if (mime && mime.charset) { + return mime.charset + } - if (utimes === 'lutimes' && !fs[utimes]) { - utimes = 'utimes' + // default text/* to utf-8 + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return 'UTF-8' } - if (!fs[utimes]) return cb() + return false +} + +/** + * Create a full Content-Type header given a MIME type or extension. + * + * @param {string} str + * @return {boolean|string} + */ - var curA = current.atime - var curM = current.mtime - var meA = want.atime - var meM = want.mtime +function contentType (str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false + } - if (meA === undefined) meA = curA - if (meM === undefined) meM = curM + var mime = str.indexOf('/') === -1 + ? exports.lookup(str) + : str - if (!isDate(meA)) meA = new Date(meA) - if (!isDate(meM)) meA = new Date(meM) + if (!mime) { + return false + } - if (meA.getTime() === curA.getTime() && - meM.getTime() === curM.getTime()) return cb() + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime) + if (charset) mime += '; charset=' + charset.toLowerCase() + } - fs[utimes](path, meA, meM, cb) + return mime } -// XXX This function is beastly. Break it up! -Writer.prototype._finish = function () { - var self = this +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ - if (self._finishing) return - self._finishing = true - - // console.error(" W Finish", self._path, self.size) - - // set up all the things. - // At this point, we're already done writing whatever we've gotta write, - // adding files to the dir, etc. - var todo = 0 - var errState = null - var done = false - - if (self._old) { - // the times will almost *certainly* have changed. - // adds the utimes syscall, but remove another stat. - self._old.atime = new Date(0) - self._old.mtime = new Date(0) - // console.error(" W Finish Stale Stat", self._path, self.size) - setProps(self._old) - } else { - var stat = self.props.follow ? 'stat' : 'lstat' - // console.error(" W Finish Stating", self._path, self.size) - fs[stat](self._path, function (er, current) { - // console.error(" W Finish Stated", self._path, self.size, current) - if (er) { - // if we're in the process of writing out a - // directory, it's very possible that the thing we're linking to - // doesn't exist yet (especially if it was intended as a symlink), - // so swallow ENOENT errors here and just soldier on. - if (er.code === 'ENOENT' && - (self.type === 'Link' || self.type === 'SymbolicLink') && - process.platform === 'win32') { - self.ready = true - self.emit('ready') - self.emit('end') - self.emit('close') - self.end = self._finish = function () {} - return - } else return self.error(er) - } - setProps(self._old = current) - }) +function extension (type) { + if (!type || typeof type !== 'string') { + return false } - return + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()] - function setProps (current) { - todo += 3 - endChmod(self, self.props, current, self._path, next('chmod')) - endChown(self, self.props, current, self._path, next('chown')) - endUtimes(self, self.props, current, self._path, next('utimes')) + if (!exts || !exts.length) { + return false } - function next (what) { - return function (er) { - // console.error(" W Finish", what, todo) - if (errState) return - if (er) { - er.fstream_finish_call = what - return self.error(errState = er) - } - if (--todo > 0) return - if (done) return - done = true + return exts[0] +} - // we may still need to set the mode/etc. on some parent dirs - // that were created previously. delay end/close until then. - if (!self._madeDir) return end() - else endMadeDir(self, self._path, end) +/** + * Lookup the MIME type for a file path/extension. + * + * @param {string} path + * @return {boolean|string} + */ - function end (er) { - if (er) { - er.fstream_finish_call = 'setupMadeDir' - return self.error(er) - } - // all the props have been set, so we're completely done. - self.emit('end') - self.emit('close') - } - } +function lookup (path) { + if (!path || typeof path !== 'string') { + return false } -} -function endMadeDir (self, p, cb) { - var made = self._madeDir - // everything *between* made and path.dirname(self._path) - // needs to be set up. Note that this may just be one dir. - var d = path.dirname(p) + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .substr(1) - endMadeDir_(self, d, function (er) { - if (er) return cb(er) - if (d === made) { - return cb() - } - endMadeDir(self, d, cb) - }) + if (!extension) { + return false + } + + return exports.types[extension] || false } -function endMadeDir_ (self, p, cb) { - var dirProps = {} - Object.keys(self.props).forEach(function (k) { - dirProps[k] = self.props[k] +/** + * Populate the extensions and types maps. + * @private + */ - // only make non-readable dirs if explicitly requested. - if (k === 'mode' && self.type !== 'Directory') { - dirProps[k] = dirProps[k] | parseInt('0111', 8) - } - }) +function populateMaps (extensions, types) { + // source preference (least -> most) + var preference = ['nginx', 'apache', undefined, 'iana'] - var todo = 3 - var errState = null - fs.stat(p, function (er, current) { - if (er) return cb(errState = er) - endChmod(self, dirProps, current, p, next) - endChown(self, dirProps, current, p, next) - endUtimes(self, dirProps, current, p, next) - }) + Object.keys(db).forEach(function forEachMimeType (type) { + var mime = db[type] + var exts = mime.extensions - function next (er) { - if (errState) return - if (er) return cb(errState = er) - if (--todo === 0) return cb() - } -} + if (!exts || !exts.length) { + return + } -Writer.prototype.pipe = function () { - this.error("Can't pipe from writable stream") -} + // mime -> extensions + extensions[type] = exts -Writer.prototype.add = function () { - this.error("Can't add to non-Directory type") -} + // extension -> mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i] -Writer.prototype.write = function () { - return true -} + if (types[extension]) { + var from = preference.indexOf(db[types[extension]].source) + var to = preference.indexOf(mime.source) -function objectToString (d) { - return Object.prototype.toString.call(d) -} + if (types[extension] !== 'application/octet-stream' && + (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { + // skip the remapping + continue + } + } -function isDate (d) { - return typeof d === 'object' && objectToString(d) === '[object Date]' + // set the extension -> mime + types[extension] = type + } + }) } /***/ }), -/***/ 38603: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 83973: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -exports.setopts = setopts -exports.ownProp = ownProp -exports.makeAbs = makeAbs -exports.finish = finish -exports.mark = mark -exports.isIgnored = isIgnored -exports.childrenIgnored = childrenIgnored +module.exports = minimatch +minimatch.Minimatch = Minimatch -function ownProp (obj, field) { - return Object.prototype.hasOwnProperty.call(obj, field) +var path = (function () { try { return __nccwpck_require__(71017) } catch (e) {}}()) || { + sep: '/' } +minimatch.sep = path.sep -var fs = __nccwpck_require__(57147) -var path = __nccwpck_require__(71017) -var minimatch = __nccwpck_require__(4989) -var isAbsolute = __nccwpck_require__(72934) -var Minimatch = minimatch.Minimatch +var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} +var expand = __nccwpck_require__(33717) -function alphasort (a, b) { - return a.localeCompare(b, 'en') +var plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } } -function setupIgnores (self, options) { - self.ignore = options.ignore || [] +// any single thing other than / +// don't need to escape / when using new RegExp() +var qmark = '[^/]' - if (!Array.isArray(self.ignore)) - self.ignore = [self.ignore] +// * => any number of characters +var star = qmark + '*?' - if (self.ignore.length) { - self.ignore = self.ignore.map(ignoreMap) - } -} +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' -// ignore patterns are always in dot:true mode. -function ignoreMap (pattern) { - var gmatcher = null - if (pattern.slice(-3) === '/**') { - var gpattern = pattern.replace(/(\/\*\*)+$/, '') - gmatcher = new Minimatch(gpattern, { dot: true }) - } +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' - return { - matcher: new Minimatch(pattern, { dot: true }), - gmatcher: gmatcher - } +// characters that need to be escaped in RegExp. +var reSpecials = charSet('().*{}+?[]^$\\!') + +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split('').reduce(function (set, c) { + set[c] = true + return set + }, {}) } -function setopts (self, pattern, options) { - if (!options) - options = {} +// normalizes slashes. +var slashSplit = /\/+/ - // base-matching: just use globstar for that. - if (options.matchBase && -1 === pattern.indexOf("/")) { - if (options.noglobstar) { - throw new Error("base matching requires globstar") - } - pattern = "**/" + pattern +minimatch.filter = filter +function filter (pattern, options) { + options = options || {} + return function (p, i, list) { + return minimatch(p, pattern, options) } +} - self.silent = !!options.silent - self.pattern = pattern - self.strict = options.strict !== false - self.realpath = !!options.realpath - self.realpathCache = options.realpathCache || Object.create(null) - self.follow = !!options.follow - self.dot = !!options.dot - self.mark = !!options.mark - self.nodir = !!options.nodir - if (self.nodir) - self.mark = true - self.sync = !!options.sync - self.nounique = !!options.nounique - self.nonull = !!options.nonull - self.nosort = !!options.nosort - self.nocase = !!options.nocase - self.stat = !!options.stat - self.noprocess = !!options.noprocess - self.absolute = !!options.absolute - self.fs = options.fs || fs - - self.maxLength = options.maxLength || Infinity - self.cache = options.cache || Object.create(null) - self.statCache = options.statCache || Object.create(null) - self.symlinks = options.symlinks || Object.create(null) - - setupIgnores(self, options) +function ext (a, b) { + b = b || {} + var t = {} + Object.keys(a).forEach(function (k) { + t[k] = a[k] + }) + Object.keys(b).forEach(function (k) { + t[k] = b[k] + }) + return t +} - self.changedCwd = false - var cwd = process.cwd() - if (!ownProp(options, "cwd")) - self.cwd = cwd - else { - self.cwd = path.resolve(options.cwd) - self.changedCwd = self.cwd !== cwd +minimatch.defaults = function (def) { + if (!def || typeof def !== 'object' || !Object.keys(def).length) { + return minimatch } - self.root = options.root || path.resolve(self.cwd, "/") - self.root = path.resolve(self.root) - if (process.platform === "win32") - self.root = self.root.replace(/\\/g, "/") - - // TODO: is an absolute `cwd` supposed to be resolved against `root`? - // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') - self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) - if (process.platform === "win32") - self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") - self.nomount = !!options.nomount + var orig = minimatch - // disable comments and negation in Minimatch. - // Note that they are not supported in Glob itself anyway. - options.nonegate = true - options.nocomment = true - // always treat \ in patterns as escapes, not path separators - options.allowWindowsEscape = false + var m = function minimatch (p, pattern, options) { + return orig(p, pattern, ext(def, options)) + } - self.minimatch = new Minimatch(pattern, options) - self.options = self.minimatch.options -} + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) + } + m.Minimatch.defaults = function defaults (options) { + return orig.defaults(ext(def, options)).Minimatch + } -function finish (self) { - var nou = self.nounique - var all = nou ? [] : Object.create(null) + m.filter = function filter (pattern, options) { + return orig.filter(pattern, ext(def, options)) + } - for (var i = 0, l = self.matches.length; i < l; i ++) { - var matches = self.matches[i] - if (!matches || Object.keys(matches).length === 0) { - if (self.nonull) { - // do like the shell, and spit out the literal glob - var literal = self.minimatch.globSet[i] - if (nou) - all.push(literal) - else - all[literal] = true - } - } else { - // had matches - var m = Object.keys(matches) - if (nou) - all.push.apply(all, m) - else - m.forEach(function (m) { - all[m] = true - }) - } + m.defaults = function defaults (options) { + return orig.defaults(ext(def, options)) } - if (!nou) - all = Object.keys(all) + m.makeRe = function makeRe (pattern, options) { + return orig.makeRe(pattern, ext(def, options)) + } - if (!self.nosort) - all = all.sort(alphasort) + m.braceExpand = function braceExpand (pattern, options) { + return orig.braceExpand(pattern, ext(def, options)) + } - // at *some* point we statted all of these - if (self.mark) { - for (var i = 0; i < all.length; i++) { - all[i] = self._mark(all[i]) - } - if (self.nodir) { - all = all.filter(function (e) { - var notDir = !(/\/$/.test(e)) - var c = self.cache[e] || self.cache[makeAbs(self, e)] - if (notDir && c) - notDir = c !== 'DIR' && !Array.isArray(c) - return notDir - }) - } + m.match = function (list, pattern, options) { + return orig.match(list, pattern, ext(def, options)) } - if (self.ignore.length) - all = all.filter(function(m) { - return !isIgnored(self, m) - }) + return m +} - self.found = all +Minimatch.defaults = function (def) { + return minimatch.defaults(def).Minimatch } -function mark (self, p) { - var abs = makeAbs(self, p) - var c = self.cache[abs] - var m = p - if (c) { - var isDir = c === 'DIR' || Array.isArray(c) - var slash = p.slice(-1) === '/' +function minimatch (p, pattern, options) { + assertValidPattern(pattern) - if (isDir && !slash) - m += '/' - else if (!isDir && slash) - m = m.slice(0, -1) + if (!options) options = {} - if (m !== p) { - var mabs = makeAbs(self, m) - self.statCache[mabs] = self.statCache[abs] - self.cache[mabs] = self.cache[abs] - } + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false } - return m + return new Minimatch(pattern, options).match(p) } -// lotta situps... -function makeAbs (self, f) { - var abs = f - if (f.charAt(0) === '/') { - abs = path.join(self.root, f) - } else if (isAbsolute(f) || f === '') { - abs = f - } else if (self.changedCwd) { - abs = path.resolve(self.cwd, f) - } else { - abs = path.resolve(f) +function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options) } - if (process.platform === 'win32') - abs = abs.replace(/\\/g, '/') - - return abs -} + assertValidPattern(pattern) + if (!options) options = {} -// Return true, if pattern ends with globstar '**', for the accompanying parent directory. -// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents -function isIgnored (self, path) { - if (!self.ignore.length) - return false + pattern = pattern.trim() - return self.ignore.some(function(item) { - return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) - }) -} + // windows support: need to use /, not \ + if (!options.allowWindowsEscape && path.sep !== '/') { + pattern = pattern.split(path.sep).join('/') + } -function childrenIgnored (self, path) { - if (!self.ignore.length) - return false + this.options = options + this.set = [] + this.pattern = pattern + this.regexp = null + this.negate = false + this.comment = false + this.empty = false + this.partial = !!options.partial - return self.ignore.some(function(item) { - return !!(item.gmatcher && item.gmatcher.match(path)) - }) + // make the set of regexps etc. + this.make() } +Minimatch.prototype.debug = function () {} -/***/ }), +Minimatch.prototype.make = make +function make () { + var pattern = this.pattern + var options = this.options -/***/ 3661: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return + } -// Approach: -// -// 1. Get the minimatch set -// 2. For each pattern in the set, PROCESS(pattern, false) -// 3. Store matches per-set, then uniq them -// -// PROCESS(pattern, inGlobStar) -// Get the first [n] items from pattern that are all strings -// Join these together. This is PREFIX. -// If there is no more remaining, then stat(PREFIX) and -// add to matches if it succeeds. END. -// -// If inGlobStar and PREFIX is symlink and points to dir -// set ENTRIES = [] -// else readdir(PREFIX) as ENTRIES -// If fail, END -// -// with ENTRIES -// If pattern[n] is GLOBSTAR -// // handle the case where the globstar match is empty -// // by pruning it out, and testing the resulting pattern -// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) -// // handle other cases. -// for ENTRY in ENTRIES (not dotfiles) -// // attach globstar + tail onto the entry -// // Mark that this entry is a globstar match -// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) -// -// else // not globstar -// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) -// Test ENTRY against pattern[n] -// If fails, continue -// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) -// -// Caveat: -// Cache all stats and readdirs results to minimize syscall. Since all -// we ever care about is existence and directory-ness, we can just keep -// `true` for files, and [children,...] for directories, or `false` for -// things that don't exist. + // step 1: figure out negation, etc. + this.parseNegate() -module.exports = glob + // step 2: expand braces + var set = this.globSet = this.braceExpand() -var rp = __nccwpck_require__(54421) -var minimatch = __nccwpck_require__(4989) -var Minimatch = minimatch.Minimatch -var inherits = __nccwpck_require__(42991) -var EE = (__nccwpck_require__(82361).EventEmitter) -var path = __nccwpck_require__(71017) -var assert = __nccwpck_require__(39491) -var isAbsolute = __nccwpck_require__(72934) -var globSync = __nccwpck_require__(25102) -var common = __nccwpck_require__(38603) -var setopts = common.setopts -var ownProp = common.ownProp -var inflight = __nccwpck_require__(77505) -var util = __nccwpck_require__(73837) -var childrenIgnored = common.childrenIgnored -var isIgnored = common.isIgnored + if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) } -var once = __nccwpck_require__(58203) + this.debug(this.pattern, set) -function glob (pattern, options, cb) { - if (typeof options === 'function') cb = options, options = {} - if (!options) options = {} + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(function (s) { + return s.split(slashSplit) + }) - if (options.sync) { - if (cb) - throw new TypeError('callback provided to sync glob') - return globSync(pattern, options) - } + this.debug(this.pattern, set) - return new Glob(pattern, options, cb) -} + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this) -glob.sync = globSync -var GlobSync = glob.GlobSync = globSync.GlobSync + this.debug(this.pattern, set) -// old api surface -glob.glob = glob + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 + }) -function extend (origin, add) { - if (add === null || typeof add !== 'object') { - return origin - } + this.debug(this.pattern, set) - var keys = Object.keys(add) - var i = keys.length - while (i--) { - origin[keys[i]] = add[keys[i]] - } - return origin + this.set = set } -glob.hasMagic = function (pattern, options_) { - var options = extend({}, options_) - options.noprocess = true - - var g = new Glob(pattern, options) - var set = g.minimatch.set - - if (!pattern) - return false +Minimatch.prototype.parseNegate = parseNegate +function parseNegate () { + var pattern = this.pattern + var negate = false + var options = this.options + var negateOffset = 0 - if (set.length > 1) - return true + if (options.nonegate) return - for (var j = 0; j < set[0].length; j++) { - if (typeof set[0][j] !== 'string') - return true + for (var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === '!' + ; i++) { + negate = !negate + negateOffset++ } - return false + if (negateOffset) this.pattern = pattern.substr(negateOffset) + this.negate = negate } -glob.Glob = Glob -inherits(Glob, EE) -function Glob (pattern, options, cb) { - if (typeof options === 'function') { - cb = options - options = null - } - - if (options && options.sync) { - if (cb) - throw new TypeError('callback provided to sync glob') - return new GlobSync(pattern, options) - } - - if (!(this instanceof Glob)) - return new Glob(pattern, options, cb) - - setopts(this, pattern, options) - this._didRealPath = false - - // process each pattern in the minimatch set - var n = this.minimatch.set.length +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = function (pattern, options) { + return braceExpand(pattern, options) +} - // The matches are stored as {: true,...} so that - // duplicates are automagically pruned. - // Later, we do an Object.keys() on these. - // Keep them as a list so we can fill in when nonull is set. - this.matches = new Array(n) +Minimatch.prototype.braceExpand = braceExpand - if (typeof cb === 'function') { - cb = once(cb) - this.on('error', cb) - this.on('end', function (matches) { - cb(null, matches) - }) +function braceExpand (pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options + } else { + options = {} + } } - var self = this - this._processing = 0 + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern - this._emitQueue = [] - this._processQueue = [] - this.paused = false + assertValidPattern(pattern) - if (this.noprocess) - return this + // Thanks to Yeting Li for + // improving this regexp to avoid a ReDOS vulnerability. + if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { + // shortcut. no need to expand. + return [pattern] + } - if (n === 0) - return done() + return expand(pattern) +} - var sync = true - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false, done) +var MAX_PATTERN_LENGTH = 1024 * 64 +var assertValidPattern = function (pattern) { + if (typeof pattern !== 'string') { + throw new TypeError('invalid pattern') } - sync = false - function done () { - --self._processing - if (self._processing <= 0) { - if (sync) { - process.nextTick(function () { - self._finish() - }) - } else { - self._finish() - } - } + if (pattern.length > MAX_PATTERN_LENGTH) { + throw new TypeError('pattern is too long') } } -Glob.prototype._finish = function () { - assert(this instanceof Glob) - if (this.aborted) - return - - if (this.realpath && !this._didRealpath) - return this._realpath() - - common.finish(this) - this.emit('end', this.found) -} - -Glob.prototype._realpath = function () { - if (this._didRealpath) - return +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +Minimatch.prototype.parse = parse +var SUBPARSE = {} +function parse (pattern, isSub) { + assertValidPattern(pattern) - this._didRealpath = true + var options = this.options - var n = this.matches.length - if (n === 0) - return this._finish() + // shortcuts + if (pattern === '**') { + if (!options.noglobstar) + return GLOBSTAR + else + pattern = '*' + } + if (pattern === '') return '' + var re = '' + var hasMagic = !!options.nocase + var escaping = false + // ? => one single character + var patternListStack = [] + var negativeLists = [] + var stateChar + var inClass = false + var reClassStart = -1 + var classStart = -1 + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + var patternStart = pattern.charAt(0) === '.' ? '' // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' + : '(?!\\.)' var self = this - for (var i = 0; i < this.matches.length; i++) - this._realpathSet(i, next) - function next () { - if (--n === 0) - self._finish() + function clearStateChar () { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star + hasMagic = true + break + case '?': + re += qmark + hasMagic = true + break + default: + re += '\\' + stateChar + break + } + self.debug('clearStateChar %j %j', stateChar, re) + stateChar = false + } } -} - -Glob.prototype._realpathSet = function (index, cb) { - var matchset = this.matches[index] - if (!matchset) - return cb() - - var found = Object.keys(matchset) - var self = this - var n = found.length - if (n === 0) - return cb() + for (var i = 0, len = pattern.length, c + ; (i < len) && (c = pattern.charAt(i)) + ; i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) - var set = this.matches[index] = Object.create(null) - found.forEach(function (p, i) { - // If there's a problem with the stat, then it means that - // one or more of the links in the realpath couldn't be - // resolved. just return the abs value in that case. - p = self._makeAbs(p) - rp.realpath(p, self.realpathCache, function (er, real) { - if (!er) - set[real] = true - else if (er.syscall === 'stat') - set[p] = true - else - self.emit('error', er) // srsly wtf right here + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += '\\' + c + escaping = false + continue + } - if (--n === 0) { - self.matches[index] = set - cb() + switch (c) { + /* istanbul ignore next */ + case '/': { + // completely not allowed, even escaped. + // Should already be path-split by now. + return false } - }) - }) -} - -Glob.prototype._mark = function (p) { - return common.mark(this, p) -} -Glob.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) -} + case '\\': + clearStateChar() + escaping = true + continue -Glob.prototype.abort = function () { - this.aborted = true - this.emit('abort') -} + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) -Glob.prototype.pause = function () { - if (!this.paused) { - this.paused = true - this.emit('pause') - } -} + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === '!' && i === classStart + 1) c = '^' + re += c + continue + } -Glob.prototype.resume = function () { - if (this.paused) { - this.emit('resume') - this.paused = false - if (this._emitQueue.length) { - var eq = this._emitQueue.slice(0) - this._emitQueue.length = 0 - for (var i = 0; i < eq.length; i ++) { - var e = eq[i] - this._emitMatch(e[0], e[1]) - } - } - if (this._processQueue.length) { - var pq = this._processQueue.slice(0) - this._processQueue.length = 0 - for (var i = 0; i < pq.length; i ++) { - var p = pq[i] - this._processing-- - this._process(p[0], p[1], p[2], p[3]) - } - } - } -} + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + self.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue -Glob.prototype._process = function (pattern, index, inGlobStar, cb) { - assert(this instanceof Glob) - assert(typeof cb === 'function') + case '(': + if (inClass) { + re += '(' + continue + } - if (this.aborted) - return + if (!stateChar) { + re += '\\(' + continue + } - this._processing++ - if (this.paused) { - this._processQueue.push([pattern, index, inGlobStar, cb]) - return - } + patternListStack.push({ + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close + }) + // negation is (?:(?!js)[^/]*) + re += stateChar === '!' ? '(?:(?!(?:' : '(?:' + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue - //console.error('PROCESS %d', this._processing, pattern) + case ')': + if (inClass || !patternListStack.length) { + re += '\\)' + continue + } - // Get the first [n] parts of pattern that are all strings. - var n = 0 - while (typeof pattern[n] === 'string') { - n ++ - } - // now n is the index of the first one that is *not* a string. + clearStateChar() + hasMagic = true + var pl = patternListStack.pop() + // negation is (?:(?!js)[^/]*) + // The others are (?:) + re += pl.close + if (pl.type === '!') { + negativeLists.push(pl) + } + pl.reEnd = re.length + continue - // see if there's anything else - var prefix - switch (n) { - // if not, then this is rather simple - case pattern.length: - this._processSimple(pattern.join('/'), index, cb) - return + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|' + escaping = false + continue + } - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null - break + clearStateChar() + re += '|' + continue - default: - // pattern has some string bits in the front. - // whatever it starts with, whether that's 'absolute' like /foo/bar, - // or 'relative' like '../baz' - prefix = pattern.slice(0, n).join('/') - break - } + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() - var remain = pattern.slice(n) + if (inClass) { + re += '\\' + c + continue + } - // get the list of entries. - var read - if (prefix === null) - read = '.' - else if (isAbsolute(prefix) || - isAbsolute(pattern.map(function (p) { - return typeof p === 'string' ? p : '[*]' - }).join('/'))) { - if (!prefix || !isAbsolute(prefix)) - prefix = '/' + prefix - read = prefix - } else - read = prefix + inClass = true + classStart = i + reClassStart = re.length + re += c + continue - var abs = this._makeAbs(read) + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c + escaping = false + continue + } - //if ignored, skip _processing - if (childrenIgnored(this, read)) - return cb() + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + var cs = pattern.substring(classStart + 1, i) + try { + RegExp('[' + cs + ']') + } catch (er) { + // not a valid class! + var sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' + hasMagic = hasMagic || sp[1] + inClass = false + continue + } - var isGlobStar = remain[0] === minimatch.GLOBSTAR - if (isGlobStar) - this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) - else - this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) -} + // finish up the class. + hasMagic = true + inClass = false + re += c + continue -Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { - var self = this - this._readdir(abs, inGlobStar, function (er, entries) { - return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) - }) -} + default: + // swallow any state char that wasn't consumed + clearStateChar() -Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + if (escaping) { + // no need + escaping = false + } else if (reSpecials[c] + && !(c === '^' && inClass)) { + re += '\\' + } - // if the abs isn't a dir, then nothing can match! - if (!entries) - return cb() + re += c - // It will only match dot entries if it starts with a dot, or if - // dot is set. Stuff like @(.foo|.bar) isn't allowed. - var pn = remain[0] - var negate = !!this.minimatch.negate - var rawGlob = pn._glob - var dotOk = this.dot || rawGlob.charAt(0) === '.' + } // switch + } // for - var matchedEntries = [] - for (var i = 0; i < entries.length; i++) { - var e = entries[i] - if (e.charAt(0) !== '.' || dotOk) { - var m - if (negate && !prefix) { - m = !e.match(pn) - } else { - m = e.match(pn) - } - if (m) - matchedEntries.push(e) - } + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.substr(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + hasMagic = hasMagic || sp[1] } - //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) - - var len = matchedEntries.length - // If there are no matched entries, then nothing matches. - if (len === 0) - return cb() - - // if this is the last remaining pattern bit, then no need for - // an additional stat *unless* the user has specified mark or - // stat explicitly. We know they exist, since readdir returned - // them. + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + pl.open.length) + this.debug('setting tail', re, pl) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\' + } - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null) + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }) - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - if (prefix) { - if (prefix !== '/') - e = prefix + '/' + e - else - e = prefix + e - } + this.debug('tail=%j\n %s', tail, tail, pl, re) + var t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type - if (e.charAt(0) === '/' && !this.nomount) { - e = path.join(this.root, e) - } - this._emitMatch(index, e) - } - // This was the last one, and no stats were needed - return cb() + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail } - // now test all matched entries as stand-ins for that part - // of the pattern. - remain.shift() - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - var newPattern - if (prefix) { - if (prefix !== '/') - e = prefix + '/' + e - else - e = prefix + e - } - this._process([e].concat(remain), index, inGlobStar, cb) + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' } - cb() -} - -Glob.prototype._emitMatch = function (index, e) { - if (this.aborted) - return - - if (isIgnored(this, e)) - return - if (this.paused) { - this._emitQueue.push([index, e]) - return + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + var addPatternStart = false + switch (re.charAt(0)) { + case '[': case '.': case '(': addPatternStart = true } - var abs = isAbsolute(e) ? e : this._makeAbs(e) + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (var n = negativeLists.length - 1; n > -1; n--) { + var nl = negativeLists[n] - if (this.mark) - e = this._mark(e) + var nlBefore = re.slice(0, nl.reStart) + var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) + var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + var nlAfter = re.slice(nl.reEnd) - if (this.absolute) - e = abs + nlLast += nlAfter - if (this.matches[index][e]) - return + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + var openParensBefore = nlBefore.split('(').length - 1 + var cleanAfter = nlAfter + for (i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') + } + nlAfter = cleanAfter - if (this.nodir) { - var c = this.cache[abs] - if (c === 'DIR' || Array.isArray(c)) - return + var dollar = '' + if (nlAfter === '' && isSub !== SUBPARSE) { + dollar = '$' + } + var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast + re = newRe } - this.matches[index][e] = true + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re + } - var st = this.statCache[abs] - if (st) - this.emit('stat', e, st) + if (addPatternStart) { + re = patternStart + re + } - this.emit('match', e) -} + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } -Glob.prototype._readdirInGlobStar = function (abs, cb) { - if (this.aborted) - return + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } - // follow all symlinked directories forever - // just proceed as if this is a non-globstar situation - if (this.follow) - return this._readdir(abs, false, cb) + var flags = options.nocase ? 'i' : '' + try { + var regExp = new RegExp('^' + re + '$', flags) + } catch (er) /* istanbul ignore next - should be impossible */ { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.') + } - var lstatkey = 'lstat\0' + abs - var self = this - var lstatcb = inflight(lstatkey, lstatcb_) + regExp._glob = pattern + regExp._src = re - if (lstatcb) - self.fs.lstat(abs, lstatcb) + return regExp +} - function lstatcb_ (er, lstat) { - if (er && er.code === 'ENOENT') - return cb() +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() +} - var isSym = lstat && lstat.isSymbolicLink() - self.symlinks[abs] = isSym +Minimatch.prototype.makeRe = makeRe +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp - // If it's not a symlink or a dir, then it's definitely a regular file. - // don't bother doing a readdir in that case. - if (!isSym && lstat && !lstat.isDirectory()) { - self.cache[abs] = 'FILE' - cb() - } else - self._readdir(abs, false, cb) + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + var set = this.set + + if (!set.length) { + this.regexp = false + return this.regexp } -} + var options = this.options -Glob.prototype._readdir = function (abs, inGlobStar, cb) { - if (this.aborted) - return + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + var flags = options.nocase ? 'i' : '' - cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) - if (!cb) - return + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === 'string') ? regExpEscape(p) + : p._src + }).join('\\\/') + }).join('|') - //console.error('RD %j %j', +inGlobStar, abs) - if (inGlobStar && !ownProp(this.symlinks, abs)) - return this._readdirInGlobStar(abs, cb) + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' - if (ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (!c || c === 'FILE') - return cb() + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' - if (Array.isArray(c)) - return cb(null, c) + try { + this.regexp = new RegExp(re, flags) + } catch (ex) /* istanbul ignore next - should be impossible */ { + this.regexp = false } - - var self = this - self.fs.readdir(abs, readdirCb(this, abs, cb)) + return this.regexp } -function readdirCb (self, abs, cb) { - return function (er, entries) { - if (er) - self._readdirError(abs, er, cb) - else - self._readdirEntries(abs, entries, cb) +minimatch.match = function (list, pattern, options) { + options = options || {} + var mm = new Minimatch(pattern, options) + list = list.filter(function (f) { + return mm.match(f) + }) + if (mm.options.nonull && !list.length) { + list.push(pattern) } + return list } -Glob.prototype._readdirEntries = function (abs, entries, cb) { - if (this.aborted) - return +Minimatch.prototype.match = function match (f, partial) { + if (typeof partial === 'undefined') partial = this.partial + this.debug('match', f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' - // if we haven't asked to stat everything, then just - // assume that everything in there exists, so we can avoid - // having to stat it a second time. - if (!this.mark && !this.stat) { - for (var i = 0; i < entries.length; i ++) { - var e = entries[i] - if (abs === '/') - e = abs + e - else - e = abs + '/' + e - this.cache[e] = true - } - } + if (f === '/' && partial) return true - this.cache[abs] = entries - return cb(null, entries) -} + var options = this.options -Glob.prototype._readdirError = function (f, er, cb) { - if (this.aborted) - return + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') + } - // handle errors, and cache the information - switch (er.code) { - case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 - case 'ENOTDIR': // totally normal. means it *does* exist. - var abs = this._makeAbs(f) - this.cache[abs] = 'FILE' - if (abs === this.cwdAbs) { - var error = new Error(er.code + ' invalid cwd ' + this.cwd) - error.path = this.cwd - error.code = er.code - this.emit('error', error) - this.abort() - } - break + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) - case 'ENOENT': // not terribly unusual - case 'ELOOP': - case 'ENAMETOOLONG': - case 'UNKNOWN': - this.cache[this._makeAbs(f)] = false - break + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. - default: // some unusual error. Treat as failure. - this.cache[this._makeAbs(f)] = false - if (this.strict) { - this.emit('error', er) - // If the error is handled, then we abort - // if not, we threw out of here - this.abort() - } - if (!this.silent) - console.error('glob error', er) - break + var set = this.set + this.debug(this.pattern, 'set', set) + + // Find the basename of the path by looking for the last non-empty segment + var filename + var i + for (i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break } - return cb() -} + for (i = 0; i < set.length; i++) { + var pattern = set[i] + var file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] + } + var hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate + } + } -Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { - var self = this - this._readdir(abs, inGlobStar, function (er, entries) { - self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) - }) + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate } +// set partial to true to test if, for example, +// "/a/b" matches the start of "/*/b/*/d" +// Partial means, if you run out of file before you run +// out of pattern, then that's fine, as long as all +// the parts match. +Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options -Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { - //console.error('pgs2', prefix, remain[0], entries) - - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return cb() - - // test without the globstar, and with every child both below - // and replacing the globstar. - var remainWithoutGlobStar = remain.slice(1) - var gspref = prefix ? [ prefix ] : [] - var noGlobStar = gspref.concat(remainWithoutGlobStar) + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) - // the noGlobStar pattern exits the inGlobStar state - this._process(noGlobStar, index, false, cb) + this.debug('matchOne', file.length, pattern.length) - var isSym = this.symlinks[abs] - var len = entries.length + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) - return cb() + this.debug(pattern, p, f) - for (var i = 0; i < len; i++) { - var e = entries[i] - if (e.charAt(0) === '.' && !this.dot) - continue + // should be impossible. + // some invalid regexp stuff in the set. + /* istanbul ignore if */ + if (p === false) return false - // these two cases enter the inGlobStar state - var instead = gspref.concat(entries[i], remainWithoutGlobStar) - this._process(instead, index, true, cb) + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) - var below = gspref.concat(entries[i], remain) - this._process(below, index, true, cb) - } + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + var pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } - cb() -} + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] -Glob.prototype._processSimple = function (prefix, index, cb) { - // XXX review this. Shouldn't it be doing the mounting etc - // before doing stat? kinda weird? - var self = this - this._stat(prefix, function (er, exists) { - self._processSimple2(prefix, index, er, exists, cb) - }) -} -Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) - //console.error('ps2', prefix, exists) + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr) + break + } - if (!this.matches[index]) - this.matches[index] = Object.create(null) + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } + } - // If it doesn't exist, then just mark the lack of results - if (!exists) - return cb() + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + /* istanbul ignore if */ + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true + } + return false + } - if (prefix && isAbsolute(prefix) && !this.nomount) { - var trail = /[\/\\]$/.test(prefix) - if (prefix.charAt(0) === '/') { - prefix = path.join(this.root, prefix) + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === 'string') { + hit = f === p + this.debug('string match', p, f, hit) } else { - prefix = path.resolve(this.root, prefix) - if (trail) - prefix += '/' + hit = f.match(p) + this.debug('pattern match', p, f, hit) } + + if (!hit) return false } - if (process.platform === 'win32') - prefix = prefix.replace(/\\/g, '/') + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* - // Mark this as a match - this._emitMatch(index, prefix) - cb() + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else /* istanbul ignore else */ if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + return (fi === fl - 1) && (file[fi] === '') + } + + // should be unreachable. + /* istanbul ignore next */ + throw new Error('wtf?') } -// Returns either 'DIR', 'FILE', or false -Glob.prototype._stat = function (f, cb) { - var abs = this._makeAbs(f) - var needDir = f.slice(-1) === '/' +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, '$1') +} - if (f.length > this.maxLength) - return cb() +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +} - if (!this.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (Array.isArray(c)) - c = 'DIR' +/***/ }), - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return cb(null, c) +/***/ 66186: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (needDir && c === 'FILE') - return cb() +var path = __nccwpck_require__(71017); +var fs = __nccwpck_require__(57147); +var _0777 = parseInt('0777', 8); - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. - } +module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; - var exists - var stat = this.statCache[abs] - if (stat !== undefined) { - if (stat === false) - return cb(null, stat) - else { - var type = stat.isDirectory() ? 'DIR' : 'FILE' - if (needDir && type === 'FILE') - return cb() - else - return cb(null, type, stat) +function mkdirP (p, opts, f, made) { + if (typeof opts === 'function') { + f = opts; + opts = {}; } - } - - var self = this - var statcb = inflight('stat\0' + abs, lstatcb_) - if (statcb) - self.fs.lstat(abs, statcb) - - function lstatcb_ (er, lstat) { - if (lstat && lstat.isSymbolicLink()) { - // If it's a symlink, then treat it as the target, unless - // the target does not exist, then treat it as a file. - return self.fs.stat(abs, function (er, stat) { - if (er) - self._stat2(f, abs, null, lstat, cb) - else - self._stat2(f, abs, er, stat, cb) - }) - } else { - self._stat2(f, abs, er, lstat, cb) + else if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; } - } -} - -Glob.prototype._stat2 = function (f, abs, er, stat, cb) { - if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { - this.statCache[abs] = false - return cb() - } - - var needDir = f.slice(-1) === '/' - this.statCache[abs] = stat - - if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) - return cb(null, false, stat) - - var c = true - if (stat) - c = stat.isDirectory() ? 'DIR' : 'FILE' - this.cache[abs] = this.cache[abs] || c - - if (needDir && c === 'FILE') - return cb() + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 + } + if (!made) made = null; + + var cb = f || /* istanbul ignore next */ function () {}; + p = path.resolve(p); + + xfs.mkdir(p, mode, function (er) { + if (!er) { + made = made || p; + return cb(null, made); + } + switch (er.code) { + case 'ENOENT': + /* istanbul ignore if */ + if (path.dirname(p) === p) return cb(er); + mkdirP(path.dirname(p), opts, function (er, made) { + /* istanbul ignore if */ + if (er) cb(er, made); + else mkdirP(p, opts, cb, made); + }); + break; - return cb(null, c, stat) + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + xfs.stat(p, function (er2, stat) { + // if the stat fails, then that's super weird. + // let the original error be the failure reason. + if (er2 || !stat.isDirectory()) cb(er, made) + else cb(null, made); + }); + break; + } + }); } +mkdirP.sync = function sync (p, opts, made) { + if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 + } + if (!made) made = null; -/***/ }), - -/***/ 25102: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + p = path.resolve(p); -module.exports = globSync -globSync.GlobSync = GlobSync + try { + xfs.mkdirSync(p, mode); + made = made || p; + } + catch (err0) { + switch (err0.code) { + case 'ENOENT' : + made = sync(path.dirname(p), opts, made); + sync(p, opts, made); + break; -var rp = __nccwpck_require__(54421) -var minimatch = __nccwpck_require__(4989) -var Minimatch = minimatch.Minimatch -var Glob = (__nccwpck_require__(3661).Glob) -var util = __nccwpck_require__(73837) -var path = __nccwpck_require__(71017) -var assert = __nccwpck_require__(39491) -var isAbsolute = __nccwpck_require__(72934) -var common = __nccwpck_require__(38603) -var setopts = common.setopts -var ownProp = common.ownProp -var childrenIgnored = common.childrenIgnored -var isIgnored = common.isIgnored + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + var stat; + try { + stat = xfs.statSync(p); + } + catch (err1) /* istanbul ignore next */ { + throw err0; + } + /* istanbul ignore if */ + if (!stat.isDirectory()) throw err0; + break; + } + } -function globSync (pattern, options) { - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') + return made; +}; - return new GlobSync(pattern, options).found -} -function GlobSync (pattern, options) { - if (!pattern) - throw new Error('must provide pattern') +/***/ }), - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') +/***/ 80467: +/***/ ((module, exports, __nccwpck_require__) => { - if (!(this instanceof GlobSync)) - return new GlobSync(pattern, options) +"use strict"; - setopts(this, pattern, options) - if (this.noprocess) - return this +Object.defineProperty(exports, "__esModule", ({ value: true })); - var n = this.minimatch.set.length - this.matches = new Array(n) - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false) - } - this._finish() -} +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -GlobSync.prototype._finish = function () { - assert.ok(this instanceof GlobSync) - if (this.realpath) { - var self = this - this.matches.forEach(function (matchset, index) { - var set = self.matches[index] = Object.create(null) - for (var p in matchset) { - try { - p = self._makeAbs(p) - var real = rp.realpathSync(p, self.realpathCache) - set[real] = true - } catch (er) { - if (er.syscall === 'stat') - set[self._makeAbs(p)] = true - else - throw er - } - } - }) - } - common.finish(this) -} +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)); +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js -GlobSync.prototype._process = function (pattern, index, inGlobStar) { - assert.ok(this instanceof GlobSync) +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; - // Get the first [n] parts of pattern that are all strings. - var n = 0 - while (typeof pattern[n] === 'string') { - n ++ - } - // now n is the index of the first one that is *not* a string. +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); - // See if there's anything else - var prefix - switch (n) { - // if not, then this is rather simple - case pattern.length: - this._processSimple(pattern.join('/'), index) - return +class Blob { + constructor() { + this[TYPE] = ''; - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null - break + const blobParts = arguments[0]; + const options = arguments[1]; - default: - // pattern has some string bits in the front. - // whatever it starts with, whether that's 'absolute' like /foo/bar, - // or 'relative' like '../baz' - prefix = pattern.slice(0, n).join('/') - break - } + const buffers = []; + let size = 0; - var remain = pattern.slice(n) + 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); + } + } - // get the list of entries. - var read - if (prefix === null) - read = '.' - else if (isAbsolute(prefix) || - isAbsolute(pattern.map(function (p) { - return typeof p === 'string' ? p : '[*]' - }).join('/'))) { - if (!prefix || !isAbsolute(prefix)) - prefix = '/' + prefix - read = prefix - } else - read = prefix + this[BUFFER] = Buffer.concat(buffers); - var abs = this._makeAbs(read) + 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 ignored, skip processing - if (childrenIgnored(this, read)) - return + 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); - var isGlobStar = remain[0] === minimatch.GLOBSTAR - if (isGlobStar) - this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) - else - this._processReaddir(prefix, read, abs, remain, index, inGlobStar) + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } } +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); -GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { - var entries = this._readdir(abs, inGlobStar) - - // if the abs isn't a dir, then nothing can match! - if (!entries) - return - - // It will only match dot entries if it starts with a dot, or if - // dot is set. Stuff like @(.foo|.bar) isn't allowed. - var pn = remain[0] - var negate = !!this.minimatch.negate - var rawGlob = pn._glob - var dotOk = this.dot || rawGlob.charAt(0) === '.' - - var matchedEntries = [] - for (var i = 0; i < entries.length; i++) { - var e = entries[i] - if (e.charAt(0) !== '.' || dotOk) { - var m - if (negate && !prefix) { - m = !e.match(pn) - } else { - m = e.match(pn) - } - if (m) - matchedEntries.push(e) - } - } - - var len = matchedEntries.length - // If there are no matched entries, then nothing matches. - if (len === 0) - return +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); - // if this is the last remaining pattern bit, then no need for - // an additional stat *unless* the user has specified mark or - // stat explicitly. We know they exist, since readdir returned - // them. +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null) +/** + * 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); - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - if (prefix) { - if (prefix.slice(-1) !== '/') - e = prefix + '/' + e - else - e = prefix + e - } + this.message = message; + this.type = type; - if (e.charAt(0) === '/' && !this.nomount) { - e = path.join(this.root, e) - } - this._emitMatch(index, e) - } - // This was the last one, and no stats were needed - return + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; } - // now test all matched entries as stand-ins for that part - // of the pattern. - remain.shift() - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - var newPattern - if (prefix) - newPattern = [prefix, e] - else - newPattern = [e] - this._process(newPattern.concat(remain), index, inGlobStar) - } + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); } +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; -GlobSync.prototype._emitMatch = function (index, e) { - if (isIgnored(this, e)) - return +let convert; +try { + convert = (__nccwpck_require__(22877).convert); +} catch (e) {} - var abs = this._makeAbs(e) +const INTERNALS = Symbol('Body internals'); - if (this.mark) - e = this._mark(e) +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; - if (this.absolute) { - e = abs - } +/** + * 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; - if (this.matches[index][e]) - return + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; - if (this.nodir) { - var c = this.cache[abs] - if (c === 'DIR' || Array.isArray(c)) - return - } + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; - this.matches[index][e] = true + 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 (this.stat) - this._stat(e) + 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; + }); + } } +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, -GlobSync.prototype._readdirInGlobStar = function (abs) { - // follow all symlinked directories forever - // just proceed as if this is a non-globstar situation - if (this.follow) - return this._readdir(abs, false) + get bodyUsed() { + return this[INTERNALS].disturbed; + }, - var entries - var lstat - var stat - try { - lstat = this.fs.lstatSync(abs) - } catch (er) { - if (er.code === 'ENOENT') { - // lstat failed, doesn't exist - return null - } - } - - var isSym = lstat && lstat.isSymbolicLink() - this.symlinks[abs] = isSym - - // If it's not a symlink or a dir, then it's definitely a regular file. - // don't bother doing a readdir in that case. - if (!isSym && lstat && !lstat.isDirectory()) - this.cache[abs] = 'FILE' - else - entries = this._readdir(abs, false) + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, - return entries -} + /** + * 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 + }); + }); + }, -GlobSync.prototype._readdir = function (abs, inGlobStar) { - var entries + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; - if (inGlobStar && !ownProp(this.symlinks, abs)) - return this._readdirInGlobStar(abs) + 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')); + } + }); + }, - if (ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (!c || c === 'FILE') - return null + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, - if (Array.isArray(c)) - return c - } + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, - try { - return this._readdirEntries(abs, this.fs.readdirSync(abs)) - } catch (er) { - this._readdirError(abs, er) - return null - } -} + /** + * 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; -GlobSync.prototype._readdirEntries = function (abs, entries) { - // if we haven't asked to stat everything, then just - // assume that everything in there exists, so we can avoid - // having to stat it a second time. - if (!this.mark && !this.stat) { - for (var i = 0; i < entries.length; i ++) { - var e = entries[i] - if (abs === '/') - e = abs + e - else - e = abs + '/' + e - this.cache[e] = true - } - } + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; - this.cache[abs] = entries +// 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 } +}); - // mark and cache dir-ness - return entries -} +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); + } + } +}; -GlobSync.prototype._readdirError = function (f, er) { - // handle errors, and cache the information - switch (er.code) { - case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 - case 'ENOTDIR': // totally normal. means it *does* exist. - var abs = this._makeAbs(f) - this.cache[abs] = 'FILE' - if (abs === this.cwdAbs) { - var error = new Error(er.code + ' invalid cwd ' + this.cwd) - error.path = this.cwd - error.code = er.code - throw error - } - break +/** + * 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; - case 'ENOENT': // not terribly unusual - case 'ELOOP': - case 'ENAMETOOLONG': - case 'UNKNOWN': - this.cache[this._makeAbs(f)] = false - break + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } - default: // some unusual error. Treat as failure. - this.cache[this._makeAbs(f)] = false - if (this.strict) - throw er - if (!this.silent) - console.error('glob error', er) - break - } -} + this[INTERNALS].disturbed = true; -GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } - var entries = this._readdir(abs, inGlobStar) + let body = this.body; - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } - // test without the globstar, and with every child both below - // and replacing the globstar. - var remainWithoutGlobStar = remain.slice(1) - var gspref = prefix ? [ prefix ] : [] - var noGlobStar = gspref.concat(remainWithoutGlobStar) + // body is blob + if (isBlob(body)) { + body = body.stream(); + } - // the noGlobStar pattern exits the inGlobStar state - this._process(noGlobStar, index, false) + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } - var len = entries.length - var isSym = this.symlinks[abs] + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) - return + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; - for (var i = 0; i < len; i++) { - var e = entries[i] - if (e.charAt(0) === '.' && !this.dot) - continue + return new Body.Promise(function (resolve, reject) { + let resTimeout; - // these two cases enter the inGlobStar state - var instead = gspref.concat(entries[i], remainWithoutGlobStar) - this._process(instead, index, true) + // 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); + } - var below = gspref.concat(entries[i], remain) - this._process(below, index, true) - } -} + // 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)); + } + }); -GlobSync.prototype._processSimple = function (prefix, index) { - // XXX review this. Shouldn't it be doing the mounting etc - // before doing stat? kinda weird? - var exists = this._stat(prefix) + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } - if (!this.matches[index]) - this.matches[index] = Object.create(null) + 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 it doesn't exist, then just mark the lack of results - if (!exists) - return + accumBytes += chunk.length; + accum.push(chunk); + }); - if (prefix && isAbsolute(prefix) && !this.nomount) { - var trail = /[\/\\]$/.test(prefix) - if (prefix.charAt(0) === '/') { - prefix = path.join(this.root, prefix) - } else { - prefix = path.resolve(this.root, prefix) - if (trail) - prefix += '/' - } - } + body.on('end', function () { + if (abort) { + return; + } - if (process.platform === 'win32') - prefix = prefix.replace(/\\/g, '/') + clearTimeout(resTimeout); - // Mark this as a match - this._emitMatch(index, prefix) + 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)); + } + }); + }); } -// Returns either 'DIR', 'FILE', or false -GlobSync.prototype._stat = function (f) { - var abs = this._makeAbs(f) - var needDir = f.slice(-1) === '/' - - if (f.length > this.maxLength) - return false - - if (!this.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs] - - if (Array.isArray(c)) - c = 'DIR' +/** + * 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'); + } - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return c + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; - if (needDir && c === 'FILE') - return false + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. - } + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); - var exists - var stat = this.statCache[abs] - if (!stat) { - var lstat - try { - lstat = this.fs.lstatSync(abs) - } catch (er) { - if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { - this.statCache[abs] = false - return false - } - } + // html5 + if (!res && str) { + res = / { - -"use strict"; - - -module.exports = clone - -var getPrototypeOf = Object.getPrototypeOf || function (obj) { - return obj.__proto__ +/** + * 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]); } -function clone (obj) { - if (obj === null || typeof obj !== 'object') - return obj +/** + * 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; - if (obj instanceof Object) - var copy = { __proto__: getPrototypeOf(obj) } - else - var copy = Object.create(null) + // don't allow cloning a used body + if (instance.bodyUsed) { + throw new Error('cannot clone body after it is used'); + } - Object.getOwnPropertyNames(obj).forEach(function (key) { - Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) - }) + // 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; + } - return copy + return body; } - -/***/ }), - -/***/ 91468: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var fs = __nccwpck_require__(57147) -var polyfills = __nccwpck_require__(99283) -var legacy = __nccwpck_require__(74465) -var clone = __nccwpck_require__(38612) - -var util = __nccwpck_require__(73837) - -/* istanbul ignore next - node 0.x polyfill */ -var gracefulQueue -var previousSymbol - -/* istanbul ignore else - node 0.x polyfill */ -if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { - gracefulQueue = Symbol.for('graceful-fs.queue') - // This is used in testing by future versions - previousSymbol = Symbol.for('graceful-fs.previous') -} else { - gracefulQueue = '___graceful-fs.queue' - previousSymbol = '___graceful-fs.previous' +/** + * 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'; + } } -function noop () {} +/** + * 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; -function publishQueue(context, queue) { - Object.defineProperty(context, gracefulQueue, { - get: function() { - return queue - } - }) -} -var debug = noop -if (util.debuglog) - debug = util.debuglog('gfs4') -else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) - debug = function() { - var m = util.format.apply(util, arguments) - m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') - console.error(m) - } + 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; + } +} -// Once time initialization -if (!fs[gracefulQueue]) { - // This queue can be shared by multiple loaded instances - var queue = global[gracefulQueue] || [] - publishQueue(fs, queue) +/** + * 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; - // Patch fs.close/closeSync to shared queue version, because we need - // to retry() whenever a close happens *anywhere* in the program. - // This is essential when multiple graceful-fs instances are - // in play at the same time. - fs.close = (function (fs$close) { - function close (fd, cb) { - return fs$close.call(fs, fd, function (err) { - // This function uses the graceful-fs shared queue - if (!err) { - resetQueue() - } - if (typeof cb === 'function') - cb.apply(this, arguments) - }) - } + 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); + } +} - Object.defineProperty(close, previousSymbol, { - value: fs$close - }) - return close - })(fs.close) +// expose Promise +Body.Promise = global.Promise; - fs.closeSync = (function (fs$closeSync) { - function closeSync (fd) { - // This function uses the graceful-fs shared queue - fs$closeSync.apply(fs, arguments) - resetQueue() - } +/** + * headers.js + * + * Headers class offers convenient helpers + */ - Object.defineProperty(closeSync, previousSymbol, { - value: fs$closeSync - }) - return closeSync - })(fs.closeSync) +const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/; +const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/; - if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { - process.on('exit', function() { - debug(fs[gracefulQueue]) - __nccwpck_require__(39491).equal(fs[gracefulQueue].length, 0) - }) - } +function validateName(name) { + name = `${name}`; + if (invalidTokenRegex.test(name) || name === '') { + throw new TypeError(`${name} is not a legal HTTP header name`); + } } -if (!global[gracefulQueue]) { - publishQueue(global, fs[gracefulQueue]); +function validateValue(value) { + value = `${value}`; + if (invalidHeaderCharRegex.test(value)) { + throw new TypeError(`${value} is not a legal HTTP header value`); + } } -module.exports = patch(clone(fs)) -if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { - module.exports = patch(fs) - fs.__patched = true; +/** + * 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; } -function patch (fs) { - // Everything that references the open() function needs to be in here - polyfills(fs) - fs.gracefulify = patch +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; - fs.createReadStream = createReadStream - fs.createWriteStream = createWriteStream - var fs$readFile = fs.readFile - fs.readFile = readFile - function readFile (path, options, cb) { - if (typeof options === 'function') - cb = options, options = null + this[MAP] = Object.create(null); - return go$readFile(path, options, cb) + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); - function go$readFile (path, options, cb, startTime) { - return fs$readFile(path, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } - var fs$writeFile = fs.writeFile - fs.writeFile = writeFile - function writeFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null + return; + } - return go$writeFile(path, data, options, cb) + // 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'); + } - function go$writeFile (path, data, options, cb, startTime) { - return fs$writeFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } + // 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)); + } - var fs$appendFile = fs.appendFile - if (fs$appendFile) - fs.appendFile = appendFile - function appendFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null + 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'); + } + } - return go$appendFile(path, data, options, cb) + /** + * 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; + } - function go$appendFile (path, data, options, cb, startTime) { - return fs$appendFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } + return this[MAP][key].join(', '); + } - var fs$copyFile = fs.copyFile - if (fs$copyFile) - fs.copyFile = copyFile - function copyFile (src, dest, flags, cb) { - if (typeof flags === 'function') { - cb = flags - flags = 0 - } - return go$copyFile(src, dest, flags, cb) + /** + * 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; - function go$copyFile (src, dest, flags, cb, startTime) { - return fs$copyFile(src, dest, flags, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } + 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]; - var fs$readdir = fs.readdir - fs.readdir = readdir - var noReaddirOptionVersions = /^v[0-5]\./ - function readdir (path, options, cb) { - if (typeof options === 'function') - cb = options, options = null + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } - var go$readdir = noReaddirOptionVersions.test(process.version) - ? function go$readdir (path, options, cb, startTime) { - return fs$readdir(path, fs$readdirCallback( - path, options, cb, startTime - )) - } - : function go$readdir (path, options, cb, startTime) { - return fs$readdir(path, options, fs$readdirCallback( - path, options, cb, startTime - )) - } + /** + * 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]; + } - return go$readdir(path, options, cb) + /** + * 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]; + } + } - function fs$readdirCallback (path, options, cb, startTime) { - return function (err, files) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([ - go$readdir, - [path, options, cb], - err, - startTime || Date.now(), - Date.now() - ]) - else { - if (files && files.sort) - files.sort() + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } - if (typeof cb === 'function') - cb.call(this, err, files) - } - } - } - } + /** + * 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]; + } + } - if (process.version.substr(0, 4) === 'v0.8') { - var legStreams = legacy(fs) - ReadStream = legStreams.ReadStream - WriteStream = legStreams.WriteStream - } + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } - var fs$ReadStream = fs.ReadStream - if (fs$ReadStream) { - ReadStream.prototype = Object.create(fs$ReadStream.prototype) - ReadStream.prototype.open = ReadStream$open - } + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } - var fs$WriteStream = fs.WriteStream - if (fs$WriteStream) { - WriteStream.prototype = Object.create(fs$WriteStream.prototype) - WriteStream.prototype.open = WriteStream$open - } + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } - Object.defineProperty(fs, 'ReadStream', { - get: function () { - return ReadStream - }, - set: function (val) { - ReadStream = val - }, - enumerable: true, - configurable: true - }) - Object.defineProperty(fs, 'WriteStream', { - get: function () { - return WriteStream - }, - set: function (val) { - WriteStream = val - }, - enumerable: true, - configurable: true - }) + /** + * 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]; - // legacy names - var FileReadStream = ReadStream - Object.defineProperty(fs, 'FileReadStream', { - get: function () { - return FileReadStream - }, - set: function (val) { - FileReadStream = val - }, - enumerable: true, - configurable: true - }) - var FileWriteStream = WriteStream - Object.defineProperty(fs, 'FileWriteStream', { - get: function () { - return FileWriteStream - }, - set: function (val) { - FileWriteStream = val - }, - enumerable: true, - configurable: true - }) +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); - function ReadStream (path, options) { - if (this instanceof ReadStream) - return fs$ReadStream.apply(this, arguments), this - else - return ReadStream.apply(Object.create(ReadStream.prototype), arguments) - } +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 } +}); - function ReadStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - if (that.autoClose) - that.destroy() +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - that.read() - } - }) - } + 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(', ')]; + }); +} - function WriteStream (path, options) { - if (this instanceof WriteStream) - return fs$WriteStream.apply(this, arguments), this - else - return WriteStream.apply(Object.create(WriteStream.prototype), arguments) - } +const INTERNAL = Symbol('internal'); - function WriteStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - that.destroy() - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - } - }) - } +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} - function createReadStream (path, options) { - return new fs.ReadStream(path, options) - } +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } - function createWriteStream (path, options) { - return new fs.WriteStream(path, options) - } + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; - var fs$open = fs.open - fs.open = open - function open (path, flags, mode, cb) { - if (typeof mode === 'function') - cb = mode, mode = null + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } - return go$open(path, flags, mode, cb) + this[INTERNAL].index = index + 1; - function go$open (path, flags, mode, cb, startTime) { - return fs$open(path, flags, mode, function (err, fd) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); - return fs -} +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); -function enqueue (elem) { - debug('ENQUEUE', elem[0].name, elem[1]) - fs[gracefulQueue].push(elem) - retry() -} +/** + * 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]); -// keep track of the timeout between retry() calls -var retryTimer + // 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]; + } -// reset the startTime and lastTime to now -// this resets the start of the 60 second overall timeout as well as the -// delay between attempts so that we'll retry these jobs sooner -function resetQueue () { - var now = Date.now() - for (var i = 0; i < fs[gracefulQueue].length; ++i) { - // entries that are only a length of 2 are from an older version, don't - // bother modifying those since they'll be retried anyway. - if (fs[gracefulQueue][i].length > 2) { - fs[gracefulQueue][i][3] = now // startTime - fs[gracefulQueue][i][4] = now // lastTime - } - } - // call retry to make sure we're actively processing the queue - retry() + return obj; } -function retry () { - // clear the timer and remove it to help prevent unintended concurrency - clearTimeout(retryTimer) - retryTimer = undefined +/** + * 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; +} - if (fs[gracefulQueue].length === 0) - return +const INTERNALS$1 = Symbol('Response internals'); - var elem = fs[gracefulQueue].shift() - var fn = elem[0] - var args = elem[1] - // these items may be unset if they were added by an older graceful-fs - var err = elem[2] - var startTime = elem[3] - var lastTime = elem[4] +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; - // if we don't have a startTime we have no way of knowing if we've waited - // long enough, so go ahead and retry this item now - if (startTime === undefined) { - debug('RETRY', fn.name, args) - fn.apply(null, args) - } else if (Date.now() - startTime >= 60000) { - // it's been more than 60 seconds total, bail now - debug('TIMEOUT', fn.name, args) - var cb = args.pop() - if (typeof cb === 'function') - cb.call(null, err) - } else { - // the amount of time between the last attempt and right now - var sinceAttempt = Date.now() - lastTime - // the amount of time between when we first tried, and when we last tried - // rounded up to at least 1 - var sinceStart = Math.max(lastTime - startTime, 1) - // backoff. wait longer than the total time we've been retrying, but only - // up to a maximum of 100ms - var desiredDelay = Math.min(sinceStart * 1.2, 100) - // it's been long enough since the last retry, do it again - if (sinceAttempt >= desiredDelay) { - debug('RETRY', fn.name, args) - fn.apply(null, args.concat([startTime])) - } else { - // if we can't do this job yet, push it to the end of the queue - // and let the next iteration check again - fs[gracefulQueue].push(elem) - } - } +/** + * 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] : {}; - // schedule our next run if one isn't already scheduled - if (retryTimer === undefined) { - retryTimer = setTimeout(retry, 0) - } -} + Body.call(this, body, opts); + const status = opts.status || 200; + const headers = new Headers(opts.headers); -/***/ }), + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } -/***/ 74465: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } -var Stream = (__nccwpck_require__(12781).Stream) + get url() { + return this[INTERNALS$1].url || ''; + } -module.exports = legacy + get status() { + return this[INTERNALS$1].status; + } -function legacy (fs) { - return { - ReadStream: ReadStream, - WriteStream: WriteStream - } + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } - function ReadStream (path, options) { - if (!(this instanceof ReadStream)) return new ReadStream(path, options); + get redirected() { + return this[INTERNALS$1].counter > 0; + } - Stream.call(this); + get statusText() { + return this[INTERNALS$1].statusText; + } - var self = this; + get headers() { + return this[INTERNALS$1].headers; + } - this.path = path; - this.fd = null; - this.readable = true; - this.paused = false; + /** + * 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 + }); + } +} - this.flags = 'r'; - this.mode = 438; /*=0666*/ - this.bufferSize = 64 * 1024; +Body.mixIn(Response.prototype); - options = options || {}; +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 } +}); - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); - if (this.encoding) this.setEncoding(this.encoding); +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.end === undefined) { - this.end = Infinity; - } else if ('number' !== typeof this.end) { - throw TypeError('end must be a Number'); - } +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; - if (this.start > this.end) { - throw new Error('start must be <= end'); - } +/** + * 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(); + } - this.pos = this.start; - } + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} - if (this.fd !== null) { - process.nextTick(function() { - self._read(); - }); - return; - } +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; - fs.open(this.path, this.flags, this.mode, function (err, fd) { - if (err) { - self.emit('error', err); - self.readable = false; - return; - } +/** + * 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'; +} - self.fd = fd; - self.emit('open', fd); - self._read(); - }) - } +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} - function WriteStream (path, options) { - if (!(this instanceof WriteStream)) return new WriteStream(path, options); +/** + * 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] : {}; - Stream.call(this); + let parsedURL; - this.path = path; - this.fd = null; - this.writable = true; + // 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); + } - this.flags = 'w'; - this.encoding = 'binary'; - this.mode = 438; /*=0666*/ - this.bytesWritten = 0; + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); - options = options || {}; + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.start < 0) { - throw new Error('start must be >= zero'); - } + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); - this.pos = this.start; - } + const headers = new Headers(init.headers || input.headers || {}); - this.busy = false; - this._queue = []; + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } - if (this.fd === null) { - this._open = fs.open; - this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); - this.flush(); - } - } -} + 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 + }; -/***/ 99283: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 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; + } -var constants = __nccwpck_require__(22057) + get method() { + return this[INTERNALS$2].method; + } -var origCwd = process.cwd -var cwd = null + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } -var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform + get headers() { + return this[INTERNALS$2].headers; + } -process.cwd = function() { - if (!cwd) - cwd = origCwd.call(process) - return cwd -} -try { - process.cwd() -} catch (er) {} + get redirect() { + return this[INTERNALS$2].redirect; + } -// This check is needed until node.js 12 is required -if (typeof process.chdir === 'function') { - var chdir = process.chdir - process.chdir = function (d) { - cwd = null - chdir.call(process, d) - } - if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir) + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } } -module.exports = patch +Body.mixIn(Request.prototype); -function patch (fs) { - // (re-)implement some things that are known busted or missing. +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); - // lchmod, broken prior to 0.6.2 - // back-port the fix here. - if (constants.hasOwnProperty('O_SYMLINK') && - process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { - patchLchmod(fs) - } +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); - // lutimes implementation, or no-op - if (!fs.lutimes) { - patchLutimes(fs) - } +/** + * 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); - // https://github.com/isaacs/node-graceful-fs/issues/4 - // Chown should not fail on einval or eperm if non-root. - // It should not fail on enosys ever, as this just indicates - // that a fs doesn't support the intended operation. + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } - fs.chown = chownFix(fs.chown) - fs.fchown = chownFix(fs.fchown) - fs.lchown = chownFix(fs.lchown) + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } - fs.chmod = chmodFix(fs.chmod) - fs.fchmod = chmodFix(fs.fchmod) - fs.lchmod = chmodFix(fs.lchmod) + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } - fs.chownSync = chownFixSync(fs.chownSync) - fs.fchownSync = chownFixSync(fs.fchownSync) - fs.lchownSync = chownFixSync(fs.lchownSync) + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } - fs.chmodSync = chmodFixSync(fs.chmodSync) - fs.fchmodSync = chmodFixSync(fs.fchmodSync) - fs.lchmodSync = chmodFixSync(fs.lchmodSync) + // 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); + } - fs.stat = statFix(fs.stat) - fs.fstat = statFix(fs.fstat) - fs.lstat = statFix(fs.lstat) + // 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)'); + } - fs.statSync = statFixSync(fs.statSync) - fs.fstatSync = statFixSync(fs.fstatSync) - fs.lstatSync = statFixSync(fs.lstatSync) + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } - // if lchmod/lchown do not exist, then make them no-ops - if (fs.chmod && !fs.lchmod) { - fs.lchmod = function (path, mode, cb) { - if (cb) process.nextTick(cb) - } - fs.lchmodSync = function () {} - } - if (fs.chown && !fs.lchown) { - fs.lchown = function (path, uid, gid, cb) { - if (cb) process.nextTick(cb) - } - fs.lchownSync = function () {} - } + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } - // on Windows, A/V software can lock the directory, causing this - // to fail with an EACCES or EPERM if the directory contains newly - // created files. Try again on failure, for up to 60 seconds. + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js - // Set the timeout this long because some Windows Anti-Virus, such as Parity - // bit9, may lock files for up to a minute, causing npm package install - // failures. Also, take care to yield the scheduler. Windows scheduling gives - // CPU to a busy looping process, which can cause the program causing the lock - // contention to be starved of CPU by node, so the contention doesn't resolve. - if (platform === "win32") { - fs.rename = typeof fs.rename !== 'function' ? fs.rename - : (function (fs$rename) { - function rename (from, to, cb) { - var start = Date.now() - var backoff = 0; - fs$rename(from, to, function CB (er) { - if (er - && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") - && Date.now() - start < 60000) { - setTimeout(function() { - fs.stat(to, function (stater, st) { - if (stater && stater.code === "ENOENT") - fs$rename(from, to, CB); - else - cb(er) - }) - }, backoff) - if (backoff < 100) - backoff += 10; - return; - } - if (cb) cb(er) - }) - } - if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename) - return rename - })(fs.rename) - } + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} - // if read() returns EAGAIN, then just try it again. - fs.read = typeof fs.read !== 'function' ? fs.read - : (function (fs$read) { - function read (fd, buffer, offset, length, position, callback_) { - var callback - if (callback_ && typeof callback_ === 'function') { - var eagCounter = 0 - callback = function (er, _, __) { - if (er && er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } - callback_.apply(this, arguments) - } - } - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ - // This ensures `util.promisify` works as it does for native `fs.read`. - if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read) - return read - })(fs.read) +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); - fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync - : (function (fs$readSync) { return function (fd, buffer, offset, length, position) { - var eagCounter = 0 - while (true) { - try { - return fs$readSync.call(fs, fd, buffer, offset, length, position) - } catch (er) { - if (er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - continue - } - throw er - } - } - }})(fs.readSync) + this.type = 'aborted'; + this.message = message; - function patchLchmod (fs) { - fs.lchmod = function (path, mode, callback) { - fs.open( path - , constants.O_WRONLY | constants.O_SYMLINK - , mode - , function (err, fd) { - if (err) { - if (callback) callback(err) - return - } - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - fs.fchmod(fd, mode, function (err) { - fs.close(fd, function(err2) { - if (callback) callback(err || err2) - }) - }) - }) - } + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} - fs.lchmodSync = function (path, mode) { - var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - var threw = true - var ret - try { - ret = fs.fchmodSync(fd, mode) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } - } +const URL$1 = Url.URL || whatwgUrl.URL; - function patchLutimes (fs) { - if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) { - fs.lutimes = function (path, at, mt, cb) { - fs.open(path, constants.O_SYMLINK, function (er, fd) { - if (er) { - if (cb) cb(er) - return - } - fs.futimes(fd, at, mt, function (er) { - fs.close(fd, function (er2) { - if (cb) cb(er || er2) - }) - }) - }) - } +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; - fs.lutimesSync = function (path, at, mt) { - var fd = fs.openSync(path, constants.O_SYMLINK) - var ret - var threw = true - try { - ret = fs.futimesSync(fd, at, mt) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; - } else if (fs.futimes) { - fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } - fs.lutimesSync = function () {} - } - } + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); +}; - function chmodFix (orig) { - if (!orig) return orig - return function (target, mode, cb) { - return orig.call(fs, target, mode, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } +/** + * 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; - function chmodFixSync (orig) { - if (!orig) return orig - return function (target, mode) { - try { - return orig.call(fs, target, mode) - } catch (er) { - if (!chownErOk(er)) throw er - } - } - } + return orig === dest; +}; +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { - function chownFix (orig) { - if (!orig) return orig - return function (target, uid, gid, cb) { - return orig.call(fs, target, uid, gid, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } - function chownFixSync (orig) { - if (!orig) return orig - return function (target, uid, gid) { - try { - return orig.call(fs, target, uid, gid) - } catch (er) { - if (!chownErOk(er)) throw er - } - } - } + Body.Promise = fetch.Promise; - function statFix (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options, cb) { - if (typeof options === 'function') { - cb = options - options = null - } - function callback (er, stats) { - if (stats) { - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - } - if (cb) cb.apply(this, arguments) - } - return options ? orig.call(fs, target, options, callback) - : orig.call(fs, target, callback) - } - } + // 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); - function statFixSync (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options) { - var stats = options ? orig.call(fs, target, options) - : orig.call(fs, target) - if (stats) { - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - } - return stats; - } - } + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; - // ENOSYS means that the fs doesn't support the op. Just ignore - // that, because it doesn't matter. - // - // if there's no getuid, or if getuid() is something other - // than 0, and the error is EINVAL or EPERM, then just ignore - // it. - // - // This specific case is a silent failure in cp, install, tar, - // and most other unix tools that manage permissions. - // - // When running as root, or if other types of errors are - // encountered, then it's strict. - function chownErOk (er) { - if (!er) - return true + let response = null; - if (er.code === "ENOSYS") - return true + 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); + }; - var nonroot = !process.getuid || process.getuid() !== 0 - if (nonroot) { - if (er.code === "EINVAL" || er.code === "EPERM") - return true - } + if (signal && signal.aborted) { + abort(); + return; + } - return false - } -} + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + // send request + const req = send(options); + let reqTimeout; -/***/ }), + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } -/***/ 77505: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } -var wrappy = __nccwpck_require__(39148) -var reqs = Object.create(null) -var once = __nccwpck_require__(58203) + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } -module.exports = wrappy(inflight) + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); -function inflight (key, cb) { - if (reqs[key]) { - reqs[key].push(cb) - return null - } else { - reqs[key] = [cb] - return makeres(key) - } -} + if (response && response.body) { + destroyStream(response.body, err); + } -function makeres (key) { - return once(function RES () { - var cbs = reqs[key] - var len = cbs.length - var args = slice(arguments) + finalize(); + }); - // XXX It's somewhat ambiguous whether a new callback added in this - // pass should be queued for later execution if something in the - // list of callbacks throws, or if it should just be discarded. - // However, it's such an edge case that it hardly matters, and either - // choice is likely as surprising as the other. - // As it happens, we do go ahead and schedule it for later execution. - try { - for (var i = 0; i < len; i++) { - cbs[i].apply(null, args) - } - } finally { - if (cbs.length > len) { - // added more in the interim. - // de-zalgo, just in case, but don't call again. - cbs.splice(0, len) - process.nextTick(function () { - RES.apply(null, args) - }) - } else { - delete reqs[key] - } - } - }) -} + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } -function slice (args) { - var length = args.length - var array = [] + if (response && response.body) { + destroyStream(response.body, err); + } + }); - for (var i = 0; i < length; i++) array[i] = args[i] - return array -} + /* 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; + // 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); + } + }); + }); + } -/***/ }), + req.on('response', function (res) { + clearTimeout(reqTimeout); -/***/ 42991: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const headers = createHeadersLenient(res.headers); -try { - var util = __nccwpck_require__(73837); - /* istanbul ignore next */ - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; -} catch (e) { - /* istanbul ignore next */ - module.exports = __nccwpck_require__(38624); -} + // HTTP fetch step 5 + if (fetch.isRedirect(res.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$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; + } + } -/***/ }), + // 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; + } -/***/ 38624: -/***/ ((module) => { + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } -} + // 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 + }; + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } -/***/ }), + // 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; + } -/***/ 54132: -/***/ ((__unused_webpack_module, exports) => { + // 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'); + } -"use strict"; + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); -Object.defineProperty(exports, "__esModule", ({ value: true })); + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; -/*! - * is-plain-object - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); -function isObject(o) { - return Object.prototype.toString.call(o) === '[object Object]'; -} + // HTTP-network fetch step 12.1.1.4: handle content codings -function isPlainObject(o) { - var ctor,prot; + // 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 (isObject(o) === false) return false; + // 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 + }; - // If has modified constructor - ctor = o.constructor; - if (ctor === undefined) return true; + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } - // If has modified prototype - prot = ctor.prototype; - if (isObject(prot) === false) return false; + // 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; + } - // If constructor does not have an Object-specific method - if (prot.hasOwnProperty('isPrototypeOf') === false) { - return false; - } + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } - // Most likely a plain Object - return true; + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); } +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; -exports.isPlainObject = isPlainObject; + request.on('socket', function (s) { + socket = s; + }); + request.on('response', function (response) { + const headers = response.headers; -/***/ }), + 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; -/***/ 80456: -/***/ ((module) => { + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} -var toString = {}.toString; +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; +/** + * 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; }; +// expose Promise +fetch.Promise = global.Promise; + +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; + /***/ }), -/***/ 25582: +/***/ 55388: /***/ ((module) => { -"use strict"; -function e(e){this.message=e}e.prototype=new Error,e.prototype.name="InvalidCharacterError";var r="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(r){var t=String(r).replace(/=+$/,"");if(t.length%4==1)throw new e("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,o,a=0,i=0,c="";o=t.charAt(i++);~o&&(n=a%4?64*n+o:o,a++%4)?c+=String.fromCharCode(255&n>>(-2*a&6)):0)o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(o);return c};function t(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(r(e).replace(/(.)/g,(function(e,r){var t=r.charCodeAt(0).toString(16).toUpperCase();return t.length<2&&(t="0"+t),"%"+t})))}(t)}catch(e){return r(t)}}function n(e){this.message=e}function o(e,r){if("string"!=typeof e)throw new n("Invalid token specified");var o=!0===(r=r||{}).header?0:1;try{return JSON.parse(t(e.split(".")[o]))}catch(e){throw new n("Invalid token specified: "+e.message)}}n.prototype=new Error,n.prototype.name="InvalidTokenError";const a=o;a.default=o,a.InvalidTokenError=n,module.exports=a; -//# sourceMappingURL=jwt-decode.cjs.js.map +/*! + * normalize-path + * + * Copyright (c) 2014-2018, Jon Schlinkert. + * Released under the MIT License. + */ +module.exports = function(path, stripTrailing) { + if (typeof path !== 'string') { + throw new TypeError('expected path to be a string'); + } -/***/ }), + if (path === '\\' || path === '/') return '/'; -/***/ 9936: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var len = path.length; + if (len <= 1) return path; -var util = __nccwpck_require__(73837); -var PassThrough = __nccwpck_require__(8873); + // ensure that win32 namespaces has two leading slashes, so that the path is + // handled properly by the win32 version of path.parse() after being normalized + // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces + var prefix = ''; + if (len > 4 && path[3] === '\\') { + var ch = path[2]; + if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') { + path = path.slice(2); + prefix = '//'; + } + } -module.exports = { - Readable: Readable, - Writable: Writable + var segs = path.split(/[/\\]+/); + if (stripTrailing !== false && segs[segs.length - 1] === '') { + segs.pop(); + } + return prefix + segs.join('/'); }; -util.inherits(Readable, PassThrough); -util.inherits(Writable, PassThrough); - -// Patch the given method of instance so that the callback -// is executed once, before the actual method is called the -// first time. -function beforeFirstCall(instance, method, callback) { - instance[method] = function() { - delete instance[method]; - callback.apply(this, arguments); - return this[method].apply(this, arguments); - }; -} -function Readable(fn, options) { - if (!(this instanceof Readable)) - return new Readable(fn, options); +/***/ }), - PassThrough.call(this, options); +/***/ 1223: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - beforeFirstCall(this, '_read', function() { - var source = fn.call(this, options); - var emit = this.emit.bind(this, 'error'); - source.on('error', emit); - source.pipe(this); - }); +var wrappy = __nccwpck_require__(62940) +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) - this.emit('readable'); -} +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) -function Writable(fn, options) { - if (!(this instanceof Writable)) - return new Writable(fn, options); + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) - PassThrough.call(this, options); +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f +} - beforeFirstCall(this, '_write', function() { - var destination = fn.call(this, options); - var emit = this.emit.bind(this, 'error'); - destination.on('error', emit); - this.pipe(destination); - }); +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) + } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f +} - this.emit('writable'); + +/***/ }), + +/***/ 38714: +/***/ ((module) => { + +"use strict"; + + +function posix(path) { + return path.charAt(0) === '/'; +} + +function win32(path) { + // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 + var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; + var result = splitDeviceRe.exec(path); + var device = result[1] || ''; + var isUnc = Boolean(device && device.charAt(1) !== ':'); + + // UNC paths are always absolute + return Boolean(result[2] || isUnc); +} + +module.exports = process.platform === 'win32' ? win32 : posix; +module.exports.posix = posix; +module.exports.win32 = win32; + + +/***/ }), + +/***/ 47810: +/***/ ((module) => { + +"use strict"; + + +if (typeof process === 'undefined' || + !process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = { nextTick: nextTick }; +} else { + module.exports = process +} + +function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== 'function') { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); + } +} + + + +/***/ }), + +/***/ 67214: +/***/ ((module) => { + +"use strict"; + + +const codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error + } + + function getMessage (arg1, arg2, arg3) { + if (typeof message === 'string') { + return message + } else { + return message(arg1, arg2, arg3) + } + } + + class NodeError extends Base { + constructor (arg1, arg2, arg3) { + super(getMessage(arg1, arg2, arg3)); + } + } + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + + codes[code] = NodeError; +} + +// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + const len = expected.length; + expected = expected.map((i) => String(i)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; + } else { + return `of ${thing} ${expected[0]}`; + } + } else { + return `of ${thing} ${String(expected)}`; + } +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } } +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"' +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + let determiner; + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + let msg; + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; + } else { + const type = includes(name, '.') ? 'property' : 'argument'; + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + } + + msg += `. Received type ${typeof actual}`; + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented' +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + +module.exports.q = codes; /***/ }), -/***/ 28409: +/***/ 41359: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -85100,90 +80735,92 @@ function Writable(fn, options) { -/**/ - -var pna = __nccwpck_require__(13817); -/**/ - /**/ var objectKeys = Object.keys || function (obj) { var keys = []; - for (var key in obj) { - keys.push(key); - }return keys; + for (var key in obj) keys.push(key); + return keys; }; /**/ module.exports = Duplex; - -/**/ -var util = Object.create(__nccwpck_require__(32137)); -util.inherits = __nccwpck_require__(42991); -/**/ - -var Readable = __nccwpck_require__(90708); -var Writable = __nccwpck_require__(32383); - -util.inherits(Duplex, Readable); - +var Readable = __nccwpck_require__(51433); +var Writable = __nccwpck_require__(26993); +__nccwpck_require__(44124)(Duplex, Readable); { - // avoid scope creep, the keys array can then be collected + // Allow the keys array to be GC'ed. var keys = objectKeys(Writable.prototype); for (var v = 0; v < keys.length; v++) { var method = keys[v]; if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } } - function Duplex(options) { if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); Writable.call(this, options); - - if (options && options.readable === false) this.readable = false; - - if (options && options.writable === false) this.writable = false; - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; - - this.once('end', onend); + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); + } + } } - Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, - get: function () { + get: function get() { return this._writableState.highWaterMark; } }); +Object.defineProperty(Duplex.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +Object.defineProperty(Duplex.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); // the no-half-open enforcer function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; // no more data can be written. // But allow more writes to happen in this tick. - pna.nextTick(onEndNT, this); + process.nextTick(onEndNT, this); } - function onEndNT(self) { self.end(); } - Object.defineProperty(Duplex.prototype, 'destroyed', { - get: function () { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { if (this._readableState === undefined || this._writableState === undefined) { return false; } return this._readableState.destroyed && this._writableState.destroyed; }, - set: function (value) { + set: function set(value) { // we ignore the value if the stream // has not been initialized yet if (this._readableState === undefined || this._writableState === undefined) { @@ -85197,16 +80834,9 @@ Object.defineProperty(Duplex.prototype, 'destroyed', { } }); -Duplex.prototype._destroy = function (err, cb) { - this.push(null); - this.end(); - - pna.nextTick(cb, err); -}; - /***/ }), -/***/ 65285: +/***/ 81542: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -85238,29 +80868,19 @@ Duplex.prototype._destroy = function (err, cb) { module.exports = PassThrough; - -var Transform = __nccwpck_require__(60927); - -/**/ -var util = Object.create(__nccwpck_require__(32137)); -util.inherits = __nccwpck_require__(42991); -/**/ - -util.inherits(PassThrough, Transform); - +var Transform = __nccwpck_require__(34415); +__nccwpck_require__(44124)(PassThrough, Transform); function PassThrough(options) { if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform.call(this, options); } - PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); }; /***/ }), -/***/ 90708: +/***/ 51433: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -85287,17 +80907,8 @@ PassThrough.prototype._transform = function (chunk, encoding, cb) { -/**/ - -var pna = __nccwpck_require__(13817); -/**/ - module.exports = Readable; -/**/ -var isArray = __nccwpck_require__(80456); -/**/ - /**/ var Duplex; /**/ @@ -85306,19 +80917,16 @@ Readable.ReadableState = ReadableState; /**/ var EE = (__nccwpck_require__(82361).EventEmitter); - -var EElistenerCount = function (emitter, type) { +var EElistenerCount = function EElistenerCount(emitter, type) { return emitter.listeners(type).length; }; /**/ /**/ -var Stream = __nccwpck_require__(77660); +var Stream = __nccwpck_require__(62387); /**/ -/**/ - -var Buffer = (__nccwpck_require__(63997).Buffer); +var Buffer = (__nccwpck_require__(14300).Buffer); var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); @@ -85327,31 +80935,33 @@ function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } -/**/ - -/**/ -var util = Object.create(__nccwpck_require__(32137)); -util.inherits = __nccwpck_require__(42991); -/**/ - /**/ var debugUtil = __nccwpck_require__(73837); -var debug = void 0; +var debug; if (debugUtil && debugUtil.debuglog) { debug = debugUtil.debuglog('stream'); } else { - debug = function () {}; + debug = function debug() {}; } /**/ -var BufferList = __nccwpck_require__(78490); -var destroyImpl = __nccwpck_require__(11434); -var StringDecoder; - -util.inherits(Readable, Stream); +var BufferList = __nccwpck_require__(52746); +var destroyImpl = __nccwpck_require__(97049); +var _require = __nccwpck_require__(39948), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = (__nccwpck_require__(67214)/* .codes */ .q), + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; +// Lazy loaded to improve the startup performance. +var StringDecoder; +var createReadableStreamAsyncIterator; +var from; +__nccwpck_require__(44124)(Readable, Stream); +var errorOrDestroy = destroyImpl.errorOrDestroy; var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - function prependListener(emitter, event, fn) { // Sadly this is not cacheable as some libraries bundle their own // event emitter implementation with them. @@ -85361,12 +80971,10 @@ function prependListener(emitter, event, fn) { // userland ones. NEVER DO THIS. This is here only because this code needs // to continue to work with older versions of Node.js that do not include // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; } - -function ReadableState(options, stream) { - Duplex = Duplex || __nccwpck_require__(28409); - +function ReadableState(options, stream, isDuplex) { + Duplex = Duplex || __nccwpck_require__(41359); options = options || {}; // Duplex streams are both readable and writable, but share @@ -85374,24 +80982,16 @@ function ReadableState(options, stream) { // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. - var isDuplex = stream instanceof Duplex; + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to // make all the buffer merging and length checks go away this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var readableHwm = options.readableHighWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - - if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; - - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the // linked list can remove elements from the beginning faster than @@ -85417,6 +81017,13 @@ function ReadableState(options, stream) { this.emittedReadable = false; this.readableListening = false; this.resumeScheduled = false; + this.paused = true; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // Should .destroy() be called after 'end' (and potentially 'finish') + this.autoDestroy = !!options.autoDestroy; // has it been destroyed this.destroyed = false; @@ -85431,43 +81038,43 @@ function ReadableState(options, stream) { // if true, a maybeReadMore has been scheduled this.readingMore = false; - this.decoder = null; this.encoding = null; if (options.encoding) { - if (!StringDecoder) StringDecoder = (__nccwpck_require__(91843)/* .StringDecoder */ .s); + if (!StringDecoder) StringDecoder = (__nccwpck_require__(94841)/* .StringDecoder */ .s); this.decoder = new StringDecoder(options.encoding); this.encoding = options.encoding; } } - function Readable(options) { - Duplex = Duplex || __nccwpck_require__(28409); - + Duplex = Duplex || __nccwpck_require__(41359); if (!(this instanceof Readable)) return new Readable(options); - this._readableState = new ReadableState(options, this); + // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options, this, isDuplex); // legacy this.readable = true; - if (options) { if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; } - Stream.call(this); } - Object.defineProperty(Readable.prototype, 'destroyed', { - get: function () { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { if (this._readableState === undefined) { return false; } return this._readableState.destroyed; }, - set: function (value) { + set: function set(value) { // we ignore the value if the stream // has not been initialized yet if (!this._readableState) { @@ -85479,11 +81086,9 @@ Object.defineProperty(Readable.prototype, 'destroyed', { this._readableState.destroyed = value; } }); - Readable.prototype.destroy = destroyImpl.destroy; Readable.prototype._undestroy = destroyImpl.undestroy; Readable.prototype._destroy = function (err, cb) { - this.push(null); cb(err); }; @@ -85494,7 +81099,6 @@ Readable.prototype._destroy = function (err, cb) { Readable.prototype.push = function (chunk, encoding) { var state = this._readableState; var skipChunkCheck; - if (!state.objectMode) { if (typeof chunk === 'string') { encoding = encoding || state.defaultEncoding; @@ -85507,7 +81111,6 @@ Readable.prototype.push = function (chunk, encoding) { } else { skipChunkCheck = true; } - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); }; @@ -85515,8 +81118,8 @@ Readable.prototype.push = function (chunk, encoding) { Readable.prototype.unshift = function (chunk) { return readableAddChunk(this, chunk, null, true, false); }; - function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug('readableAddChunk', chunk); var state = stream._readableState; if (chunk === null) { state.reading = false; @@ -85525,16 +81128,17 @@ function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { var er; if (!skipChunkCheck) er = chunkInvalid(state, chunk); if (er) { - stream.emit('error', er); + errorOrDestroy(stream, er); } else if (state.objectMode || chunk && chunk.length > 0) { if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { chunk = _uint8ArrayToBuffer(chunk); } - if (addToFront) { - if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); } else if (state.ended) { - stream.emit('error', new Error('stream.push() after EOF')); + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; } else { state.reading = false; if (state.decoder && !encoding) { @@ -85546,61 +81150,64 @@ function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { } } else if (!addToFront) { state.reading = false; + maybeReadMore(stream, state); } } - return needMoreData(state); + // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. + return !state.ended && (state.length < state.highWaterMark || state.length === 0); } - function addChunk(stream, state, chunk, addToFront) { if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; stream.emit('data', chunk); - stream.read(0); } else { // update the buffer info. state.length += state.objectMode ? 1 : chunk.length; if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream); } maybeReadMore(stream, state); } - function chunkInvalid(state, chunk) { var er; if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); } return er; } - -// if it's past the high water mark, we can push in some more. -// Also, if we have no data yet, we can stand some -// more bytes. This is to work around cases where hwm=0, -// such as the repl. Also, if the push() triggered a -// readable event, and the user called read(largeNumber) such that -// needReadable was set, then we ought to push more, so that another -// 'readable' event will be triggered. -function needMoreData(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); -} - Readable.prototype.isPaused = function () { return this._readableState.flowing === false; }; // backwards compatibility. Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = (__nccwpck_require__(91843)/* .StringDecoder */ .s); - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; + if (!StringDecoder) StringDecoder = (__nccwpck_require__(94841)/* .StringDecoder */ .s); + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; + // If setEncoding(null), decoder.encoding equals utf8 + this._readableState.encoding = this._readableState.decoder.encoding; + + // Iterate over current buffer to convert already stored Buffers: + var p = this._readableState.buffer.head; + var content = ''; + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } + this._readableState.buffer.clear(); + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; return this; }; -// Don't raise the hwm > 8MB -var MAX_HWM = 0x800000; +// Don't raise the hwm > 1GB +var MAX_HWM = 0x40000000; function computeNewHighWaterMark(n) { if (n >= MAX_HWM) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. n = MAX_HWM; } else { // Get the next highest power of 2 to prevent increasing hwm excessively in @@ -85642,18 +81249,16 @@ Readable.prototype.read = function (n) { n = parseInt(n, 10); var state = this._readableState; var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we // already have a bunch of data in the buffer, then just trigger // the 'readable' event and move on. - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { debug('read: emitReadable', state.length, state.ended); if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); return null; } - n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. @@ -85712,17 +81317,15 @@ Readable.prototype.read = function (n) { // and we need to re-evaluate how much data we can return to the user. if (!state.reading) n = howMuchToRead(nOrig, state); } - var ret; if (n > 0) ret = fromList(n, state);else ret = null; - if (ret === null) { - state.needReadable = true; + state.needReadable = state.length <= state.highWaterMark; n = 0; } else { state.length -= n; + state.awaitDrain = 0; } - if (state.length === 0) { // If we have nothing in the buffer, then we want to know // as soon as we *do* get something into the buffer. @@ -85731,13 +81334,11 @@ Readable.prototype.read = function (n) { // If we tried to read() past the EOF, then emit end on the next tick. if (nOrig !== n && state.ended) endReadable(this); } - if (ret !== null) this.emit('data', ret); - return ret; }; - function onEofChunk(stream, state) { + debug('onEofChunk'); if (state.ended) return; if (state.decoder) { var chunk = state.decoder.end(); @@ -85747,9 +81348,19 @@ function onEofChunk(stream, state) { } } state.ended = true; - - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); + } + } } // Don't emit readable right away in sync mode, because this can trigger @@ -85757,17 +81368,29 @@ function onEofChunk(stream, state) { // a nextTick recursion warning, but that's not so bad. function emitReadable(stream) { var state = stream._readableState; + debug('emitReadable', state.needReadable, state.emittedReadable); state.needReadable = false; if (!state.emittedReadable) { debug('emitReadable', state.flowing); state.emittedReadable = true; - if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); + process.nextTick(emitReadable_, stream); } } - function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); + var state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } + + // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; flow(stream); } @@ -85780,18 +81403,40 @@ function emitReadable_(stream) { function maybeReadMore(stream, state) { if (!state.readingMore) { state.readingMore = true; - pna.nextTick(maybeReadMore_, stream, state); + process.nextTick(maybeReadMore_, stream, state); } } - function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; debug('maybeReadMore read 0'); stream.read(0); if (len === state.length) // didn't get any data, stop spinning. - break;else len = state.length; + break; } state.readingMore = false; } @@ -85801,13 +81446,11 @@ function maybeReadMore_(stream, state) { // for virtual (non-string, non-buffer) streams, "length" is somewhat // arbitrary, and perhaps not very meaningful. Readable.prototype._read = function (n) { - this.emit('error', new Error('_read() is not implemented')); + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); }; - Readable.prototype.pipe = function (dest, pipeOpts) { var src = this; var state = this._readableState; - switch (state.pipesCount) { case 0: state.pipes = dest; @@ -85821,12 +81464,9 @@ Readable.prototype.pipe = function (dest, pipeOpts) { } state.pipesCount += 1; debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); - + if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); dest.on('unpipe', onunpipe); function onunpipe(readable, unpipeInfo) { debug('onunpipe'); @@ -85837,7 +81477,6 @@ Readable.prototype.pipe = function (dest, pipeOpts) { } } } - function onend() { debug('onend'); dest.end(); @@ -85849,7 +81488,6 @@ Readable.prototype.pipe = function (dest, pipeOpts) { // too slow. var ondrain = pipeOnDrain(src); dest.on('drain', ondrain); - var cleanedUp = false; function cleanup() { debug('cleanup'); @@ -85862,7 +81500,6 @@ Readable.prototype.pipe = function (dest, pipeOpts) { src.removeListener('end', onend); src.removeListener('end', unpipe); src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this @@ -85872,18 +81509,12 @@ Readable.prototype.pipe = function (dest, pipeOpts) { // If we don't know, then assume that we are waiting for one. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } - - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; src.on('data', ondata); function ondata(chunk) { debug('ondata'); - increasedAwaitDrain = false; var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { + debug('dest.write', ret); + if (ret === false) { // If the user unpiped during `dest.write()`, it is possible // to get stuck in a permanently paused state if that write // also returned false. @@ -85891,7 +81522,6 @@ Readable.prototype.pipe = function (dest, pipeOpts) { if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { debug('false write response, pause', state.awaitDrain); state.awaitDrain++; - increasedAwaitDrain = true; } src.pause(); } @@ -85903,7 +81533,7 @@ Readable.prototype.pipe = function (dest, pipeOpts) { debug('onerror', er); unpipe(); dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); } // Make sure our error handler is attached before userland ones. @@ -85921,7 +81551,6 @@ Readable.prototype.pipe = function (dest, pipeOpts) { unpipe(); } dest.once('finish', onfinish); - function unpipe() { debug('unpipe'); src.unpipe(dest); @@ -85935,12 +81564,10 @@ Readable.prototype.pipe = function (dest, pipeOpts) { debug('pipe resume'); src.resume(); } - return dest; }; - function pipeOnDrain(src) { - return function () { + return function pipeOnDrainFunctionResult() { var state = src._readableState; debug('pipeOnDrain', state.awaitDrain); if (state.awaitDrain) state.awaitDrain--; @@ -85950,10 +81577,11 @@ function pipeOnDrain(src) { } }; } - Readable.prototype.unpipe = function (dest) { var state = this._readableState; - var unpipeInfo = { hasUnpiped: false }; + var unpipeInfo = { + hasUnpiped: false + }; // if we're not piping anywhere, then do nothing. if (state.pipesCount === 0) return this; @@ -85962,7 +81590,6 @@ Readable.prototype.unpipe = function (dest) { if (state.pipesCount === 1) { // passed in one, but it's not the right one. if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. @@ -85982,22 +81609,19 @@ Readable.prototype.unpipe = function (dest) { state.pipes = null; state.pipesCount = 0; state.flowing = false; - - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { hasUnpiped: false }); - }return this; + for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + return this; } // try to find the right one. var index = indexOf(state.pipes, dest); if (index === -1) return this; - state.pipes.splice(index, 1); state.pipesCount -= 1; if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; }; @@ -86005,27 +81629,69 @@ Readable.prototype.unpipe = function (dest) { // Ensure readable listeners eventually get something Readable.prototype.on = function (ev, fn) { var res = Stream.prototype.on.call(this, ev, fn); - + var state = this._readableState; if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; + + // Try start flowing on next tick if stream isn't explicitly paused + if (state.flowing !== false) this.resume(); } else if (ev === 'readable') { - var state = this._readableState; if (!state.endEmitted && !state.readableListening) { state.readableListening = state.needReadable = true; + state.flowing = false; state.emittedReadable = false; - if (!state.reading) { - pna.nextTick(nReadingNextTick, this); - } else if (state.length) { + debug('on readable', state.length, state.reading); + if (state.length) { emitReadable(this); + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this); } } } - return res; }; Readable.prototype.addListener = Readable.prototype.on; +Readable.prototype.removeListener = function (ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res; +}; +Readable.prototype.removeAllListeners = function (ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res; +}; +function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; + // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } +} function nReadingNextTick(self) { debug('readable nexttick read 0'); self.read(0); @@ -86037,46 +81703,45 @@ Readable.prototype.resume = function () { var state = this._readableState; if (!state.flowing) { debug('resume'); - state.flowing = true; + // we flow only if there is no one listening + // for readable, but we still have to call + // resume() + state.flowing = !state.readableListening; resume(this, state); } + state.paused = false; return this; }; - function resume(stream, state) { if (!state.resumeScheduled) { state.resumeScheduled = true; - pna.nextTick(resume_, stream, state); + process.nextTick(resume_, stream, state); } } - function resume_(stream, state) { + debug('resume', state.reading); if (!state.reading) { - debug('resume read 0'); stream.read(0); } - state.resumeScheduled = false; - state.awaitDrain = 0; stream.emit('resume'); flow(stream); if (state.flowing && !state.reading) stream.read(0); } - Readable.prototype.pause = function () { debug('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { + if (this._readableState.flowing !== false) { debug('pause'); this._readableState.flowing = false; this.emit('pause'); } + this._readableState.paused = true; return this; }; - function flow(stream) { var state = stream._readableState; debug('flow', state.flowing); - while (state.flowing && stream.read() !== null) {} + while (state.flowing && stream.read() !== null); } // wrap an old-style stream as the async data source. @@ -86084,27 +81749,22 @@ function flow(stream) { // It is an ugly unfortunate mess of history. Readable.prototype.wrap = function (stream) { var _this = this; - var state = this._readableState; var paused = false; - stream.on('end', function () { debug('wrapped end'); if (state.decoder && !state.ended) { var chunk = state.decoder.end(); if (chunk && chunk.length) _this.push(chunk); } - _this.push(null); }); - stream.on('data', function (chunk) { debug('wrapped data'); if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - var ret = _this.push(chunk); if (!ret) { paused = true; @@ -86116,8 +81776,8 @@ Readable.prototype.wrap = function (stream) { // important when wrapping filters and duplexes. for (var i in stream) { if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { return stream[method].apply(stream, arguments); }; }(i); @@ -86138,22 +81798,60 @@ Readable.prototype.wrap = function (stream) { stream.resume(); } }; - return this; }; - +if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = __nccwpck_require__(43306); + } + return createReadableStreamAsyncIterator(this); + }; +} Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, - get: function () { + get: function get() { return this._readableState.highWaterMark; } }); +Object.defineProperty(Readable.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } +}); +Object.defineProperty(Readable.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } +}); // exposed for testing purposes only. Readable._fromList = fromList; +Object.defineProperty(Readable.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } +}); // Pluck off n bytes from an array of buffers. // Length is the combined lengths of all the buffers in the list. @@ -86162,121 +81860,51 @@ Readable._fromList = fromList; function fromList(n, state) { // nothing buffered if (state.length === 0) return null; - var ret; if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); state.buffer.clear(); } else { // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); - } - - return ret; -} - -// Extracts only enough buffered data to satisfy the amount requested. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); - } - return ret; -} - -// Copies a specified amount of characters from the list of buffered data -// chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; -} - -// Copies a specified amount of bytes from the list of buffered data chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBuffer(n, list) { - var ret = Buffer.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); - } - break; - } - ++c; + ret = state.buffer.consume(n, state.decoder); } - list.length -= c; return ret; } - function endReadable(stream) { var state = stream._readableState; - - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - + debug('endReadable', state.endEmitted); if (!state.endEmitted) { state.ended = true; - pna.nextTick(endReadableNT, state, stream); + process.nextTick(endReadableNT, state, stream); } } - function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); + // Check that we didn't get one last unshift. if (!state.endEmitted && state.length === 0) { state.endEmitted = true; stream.readable = false; stream.emit('end'); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } } } - +if (typeof Symbol === 'function') { + Readable.from = function (iterable, opts) { + if (from === undefined) { + from = __nccwpck_require__(39082); + } + return from(Readable, iterable, opts); + }; +} function indexOf(xs, x) { for (var i = 0, l = xs.length; i < l; i++) { if (xs[i] === x) return i; @@ -86286,7 +81914,7 @@ function indexOf(xs, x) { /***/ }), -/***/ 60927: +/***/ 34415: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -86356,46 +81984,35 @@ function indexOf(xs, x) { module.exports = Transform; - -var Duplex = __nccwpck_require__(28409); - -/**/ -var util = Object.create(__nccwpck_require__(32137)); -util.inherits = __nccwpck_require__(42991); -/**/ - -util.inherits(Transform, Duplex); - +var _require$codes = (__nccwpck_require__(67214)/* .codes */ .q), + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; +var Duplex = __nccwpck_require__(41359); +__nccwpck_require__(44124)(Transform, Duplex); function afterTransform(er, data) { var ts = this._transformState; ts.transforming = false; - var cb = ts.writecb; - - if (!cb) { - return this.emit('error', new Error('write callback called multiple times')); + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); } - ts.writechunk = null; ts.writecb = null; - - if (data != null) // single equals check for both `null` and `undefined` + if (data != null) + // single equals check for both `null` and `undefined` this.push(data); - cb(er); - var rs = this._readableState; rs.reading = false; if (rs.needReadable || rs.length < rs.highWaterMark) { this._read(rs.highWaterMark); } } - function Transform(options) { if (!(this instanceof Transform)) return new Transform(options); - Duplex.call(this, options); - this._transformState = { afterTransform: afterTransform.bind(this), needTransform: false, @@ -86412,21 +82029,17 @@ function Transform(options) { // that Readable wants before the first _read call, so unset the // sync guard flag. this._readableState.sync = false; - if (options) { if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof options.flush === 'function') this._flush = options.flush; } // When the writable side finishes, then flush out anything remaining. this.on('prefinish', prefinish); } - function prefinish() { var _this = this; - - if (typeof this._flush === 'function') { + if (typeof this._flush === 'function' && !this._readableState.destroyed) { this._flush(function (er, data) { done(_this, er, data); }); @@ -86434,7 +82047,6 @@ function prefinish() { done(this, null, null); } } - Transform.prototype.push = function (chunk, encoding) { this._transformState.needTransform = false; return Duplex.prototype.push.call(this, chunk, encoding); @@ -86451,9 +82063,8 @@ Transform.prototype.push = function (chunk, encoding) { // an error, then that'll put the hurt on the whole operation. If you // never call cb(), then you'll never get another chunk. Transform.prototype._transform = function (chunk, encoding, cb) { - throw new Error('_transform() is not implemented'); + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); }; - Transform.prototype._write = function (chunk, encoding, cb) { var ts = this._transformState; ts.writecb = cb; @@ -86470,8 +82081,7 @@ Transform.prototype._write = function (chunk, encoding, cb) { // That we got here means that the readable side wants more data. Transform.prototype._read = function (n) { var ts = this._transformState; - - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + if (ts.writechunk !== null && !ts.transforming) { ts.transforming = true; this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); } else { @@ -86480,34 +82090,28 @@ Transform.prototype._read = function (n) { ts.needTransform = true; } }; - Transform.prototype._destroy = function (err, cb) { - var _this2 = this; - Duplex.prototype._destroy.call(this, err, function (err2) { cb(err2); - _this2.emit('close'); }); }; - function done(stream, er, data) { if (er) return stream.emit('error', er); - - if (data != null) // single equals check for both `null` and `undefined` + if (data != null) + // single equals check for both `null` and `undefined` stream.push(data); + // TODO(BridgeAR): Write a test for these two error cases // if there's nothing in the write buffer, then that means // that nothing more will ever be provided - if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); - - if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); - + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); return stream.push(null); } /***/ }), -/***/ 32383: +/***/ 26993: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -86538,11 +82142,6 @@ function done(stream, er, data) { -/**/ - -var pna = __nccwpck_require__(13817); -/**/ - module.exports = Writable; /* */ @@ -86557,7 +82156,6 @@ function WriteReq(chunk, encoding, cb) { // there will be only 2 of these for each stream function CorkedRequest(state) { var _this = this; - this.next = null; this.entry = null; this.finish = function () { @@ -86566,34 +82164,23 @@ function CorkedRequest(state) { } /* */ -/**/ -var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; -/**/ - /**/ var Duplex; /**/ Writable.WritableState = WritableState; -/**/ -var util = Object.create(__nccwpck_require__(32137)); -util.inherits = __nccwpck_require__(42991); -/**/ - /**/ var internalUtil = { - deprecate: __nccwpck_require__(98485) + deprecate: __nccwpck_require__(65278) }; /**/ /**/ -var Stream = __nccwpck_require__(77660); +var Stream = __nccwpck_require__(62387); /**/ -/**/ - -var Buffer = (__nccwpck_require__(63997).Buffer); +var Buffer = (__nccwpck_require__(14300).Buffer); var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); @@ -86601,44 +82188,41 @@ function _uint8ArrayToBuffer(chunk) { function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } - -/**/ - -var destroyImpl = __nccwpck_require__(11434); - -util.inherits(Writable, Stream); - +var destroyImpl = __nccwpck_require__(97049); +var _require = __nccwpck_require__(39948), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = (__nccwpck_require__(67214)/* .codes */ .q), + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; +var errorOrDestroy = destroyImpl.errorOrDestroy; +__nccwpck_require__(44124)(Writable, Stream); function nop() {} - -function WritableState(options, stream) { - Duplex = Duplex || __nccwpck_require__(28409); - +function WritableState(options, stream, isDuplex) { + Duplex = Duplex || __nccwpck_require__(41359); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - var isDuplex = stream instanceof Duplex; + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream // contains buffers or objects. this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false // Note: 0 is a valid value, means that we always return false if // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var writableHwm = options.writableHighWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - - if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; - - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called this.finalCalled = false; @@ -86698,7 +82282,6 @@ function WritableState(options, stream) { // the amount that is being written when _write is called. this.writelen = 0; - this.bufferedRequest = null; this.lastBufferedRequest = null; @@ -86713,6 +82296,12 @@ function WritableState(options, stream) { // True if the error was already emitted and should not be thrown again this.errorEmitted = false; + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // Should .destroy() be called after 'finish' (and potentially 'end') + this.autoDestroy = !!options.autoDestroy; + // count buffered requests this.bufferedRequestCount = 0; @@ -86720,7 +82309,6 @@ function WritableState(options, stream) { // one allocated and free to use, and we maintain at most two this.corkedRequestsFree = new CorkedRequest(this); } - WritableState.prototype.getBuffer = function getBuffer() { var current = this.bufferedRequest; var out = []; @@ -86730,11 +82318,10 @@ WritableState.prototype.getBuffer = function getBuffer() { } return out; }; - (function () { try { Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function () { + get: internalUtil.deprecate(function writableStateBufferGetter() { return this.getBuffer(); }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') }); @@ -86747,21 +82334,19 @@ var realHasInstance; if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { realHasInstance = Function.prototype[Symbol.hasInstance]; Object.defineProperty(Writable, Symbol.hasInstance, { - value: function (object) { + value: function value(object) { if (realHasInstance.call(this, object)) return true; if (this !== Writable) return false; - return object && object._writableState instanceof WritableState; } }); } else { - realHasInstance = function (object) { + realHasInstance = function realHasInstance(object) { return object instanceof this; }; } - function Writable(options) { - Duplex = Duplex || __nccwpck_require__(28409); + Duplex = Duplex || __nccwpck_require__(41359); // Writable ctor is applied to Duplexes, too. // `realHasInstance` is necessary because using plain `instanceof` @@ -86770,123 +82355,109 @@ function Writable(options) { // Trying to use the custom `instanceof` for Writable here will also break the // Node.js LazyTransform implementation, which has a non-trivial getter for // `_writableState` that would lead to infinite recursion. - if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { - return new Writable(options); - } - this._writableState = new WritableState(options, this); + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); // legacy. this.writable = true; - if (options) { if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; } - Stream.call(this); } // Otherwise people can pipe Writable streams, which is just wrong. Writable.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); }; - function writeAfterEnd(stream, cb) { - var er = new Error('write after end'); + var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - pna.nextTick(cb, er); + errorOrDestroy(stream, er); + process.nextTick(cb, er); } // Checks that a user-supplied chunk is valid, especially for the particular // mode the stream is in. Currently this means that `null` is never accepted // and undefined/non-string values are only allowed in object mode. function validChunk(stream, state, chunk, cb) { - var valid = true; - var er = false; - + var er; if (chunk === null) { - er = new TypeError('May not write null values to stream'); - } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); } if (er) { - stream.emit('error', er); - pna.nextTick(cb, er); - valid = false; + errorOrDestroy(stream, er); + process.nextTick(cb, er); + return false; } - return valid; + return true; } - Writable.prototype.write = function (chunk, encoding, cb) { var state = this._writableState; var ret = false; var isBuf = !state.objectMode && _isUint8Array(chunk); - if (isBuf && !Buffer.isBuffer(chunk)) { chunk = _uint8ArrayToBuffer(chunk); } - if (typeof encoding === 'function') { cb = encoding; encoding = null; } - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop; - - if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { state.pendingcb++; ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); } - return ret; }; - Writable.prototype.cork = function () { - var state = this._writableState; - - state.corked++; + this._writableState.corked++; }; - Writable.prototype.uncork = function () { var state = this._writableState; - if (state.corked) { state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); } }; - Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { // node::ParseEncoding() requires lower case. if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); this._writableState.defaultEncoding = encoding; return this; }; - +Object.defineProperty(Writable.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { chunk = Buffer.from(chunk, encoding); } return chunk; } - Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, - get: function () { + get: function get() { return this._writableState.highWaterMark; } }); @@ -86904,13 +82475,10 @@ function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { } } var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. if (!ret) state.needDrain = true; - if (state.writing || state.corked) { var last = state.lastBufferedRequest; state.lastBufferedRequest = { @@ -86929,75 +82497,63 @@ function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { } else { doWrite(stream, state, false, len, chunk, encoding, cb); } - return ret; } - function doWrite(stream, state, writev, len, chunk, encoding, cb) { state.writelen = len; state.writecb = cb; state.writing = true; state.sync = true; - if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); state.sync = false; } - function onwriteError(stream, state, sync, er, cb) { --state.pendingcb; - if (sync) { // defer the callback if we are being called synchronously // to avoid piling up things on the stack - pna.nextTick(cb, er); + process.nextTick(cb, er); // this can emit finish, and it will always happen // after error - pna.nextTick(finishMaybe, stream, state); + process.nextTick(finishMaybe, stream, state); stream._writableState.errorEmitted = true; - stream.emit('error', er); + errorOrDestroy(stream, er); } else { // the caller expect this to happen before if // it is async cb(er); stream._writableState.errorEmitted = true; - stream.emit('error', er); + errorOrDestroy(stream, er); // this can emit finish, but finish must // always follow error finishMaybe(stream, state); } } - function onwriteStateUpdate(state) { state.writing = false; state.writecb = null; state.length -= state.writelen; state.writelen = 0; } - function onwrite(stream, er) { var state = stream._writableState; var sync = state.sync; var cb = state.writecb; - + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state); - + var finished = needFinish(state) || stream.destroyed; if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { clearBuffer(stream, state); } - if (sync) { - /**/ - asyncWrite(afterWrite, stream, state, finished, cb); - /**/ + process.nextTick(afterWrite, stream, state, finished, cb); } else { afterWrite(stream, state, finished, cb); } } } - function afterWrite(stream, state, finished, cb) { if (!finished) onwriteDrain(stream, state); state.pendingcb--; @@ -87019,14 +82575,12 @@ function onwriteDrain(stream, state) { function clearBuffer(stream, state) { state.bufferProcessing = true; var entry = state.bufferedRequest; - if (stream._writev && entry && entry.next) { // Fast case, write everything using _writev() var l = state.bufferedRequestCount; var buffer = new Array(l); var holder = state.corkedRequestsFree; holder.entry = entry; - var count = 0; var allBuffers = true; while (entry) { @@ -87036,7 +82590,6 @@ function clearBuffer(stream, state) { count += 1; } buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time @@ -87057,7 +82610,6 @@ function clearBuffer(stream, state) { var encoding = entry.encoding; var cb = entry.callback; var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); entry = entry.next; state.bufferedRequestCount--; @@ -87069,23 +82621,17 @@ function clearBuffer(stream, state) { break; } } - if (entry === null) state.lastBufferedRequest = null; } - state.bufferedRequest = entry; state.bufferProcessing = false; } - Writable.prototype._write = function (chunk, encoding, cb) { - cb(new Error('_write() is not implemented')); + cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); }; - Writable.prototype._writev = null; - Writable.prototype.end = function (chunk, encoding, cb) { var state = this._writableState; - if (typeof chunk === 'function') { cb = chunk; chunk = null; @@ -87094,7 +82640,6 @@ Writable.prototype.end = function (chunk, encoding, cb) { cb = encoding; encoding = null; } - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks @@ -87105,8 +82650,17 @@ Writable.prototype.end = function (chunk, encoding, cb) { // ignore unnecessary end() calls. if (!state.ending) endWritable(this, state, cb); + return this; }; - +Object.defineProperty(Writable.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); function needFinish(state) { return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; } @@ -87114,7 +82668,7 @@ function callFinal(stream, state) { stream._final(function (err) { state.pendingcb--; if (err) { - stream.emit('error', err); + errorOrDestroy(stream, err); } state.prefinished = true; stream.emit('prefinish'); @@ -87123,17 +82677,16 @@ function callFinal(stream, state) { } function prefinish(stream, state) { if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function') { + if (typeof stream._final === 'function' && !state.destroyed) { state.pendingcb++; state.finalCalled = true; - pna.nextTick(callFinal, stream, state); + process.nextTick(callFinal, stream, state); } else { state.prefinished = true; stream.emit('prefinish'); } } } - function finishMaybe(stream, state) { var need = needFinish(state); if (need) { @@ -87141,21 +82694,27 @@ function finishMaybe(stream, state) { if (state.pendingcb === 0) { state.finished = true; stream.emit('finish'); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } } } return need; } - function endWritable(stream, state, cb) { state.ending = true; finishMaybe(stream, state); if (cb) { - if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); + if (state.finished) process.nextTick(cb);else stream.once('finish', cb); } state.ended = true; stream.writable = false; } - function onCorkedFinish(corkReq, state, err) { var entry = corkReq.entry; corkReq.entry = null; @@ -87169,15 +82728,18 @@ function onCorkedFinish(corkReq, state, err) { // reuse the free corkReq. state.corkedRequestsFree.next = corkReq; } - Object.defineProperty(Writable.prototype, 'destroyed', { - get: function () { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { if (this._writableState === undefined) { return false; } return this._writableState.destroyed; }, - set: function (value) { + set: function set(value) { // we ignore the value if the stream // has not been initialized yet if (!this._writableState) { @@ -87189,34553 +82751,40078 @@ Object.defineProperty(Writable.prototype, 'destroyed', { this._writableState.destroyed = value; } }); - Writable.prototype.destroy = destroyImpl.destroy; Writable.prototype._undestroy = destroyImpl.undestroy; Writable.prototype._destroy = function (err, cb) { - this.end(); cb(err); }; /***/ }), -/***/ 78490: +/***/ 43306: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var Buffer = (__nccwpck_require__(63997).Buffer); -var util = __nccwpck_require__(73837); - -function copyBuffer(src, target, offset) { - src.copy(target, offset); -} - -module.exports = function () { - function BufferList() { - _classCallCheck(this, BufferList); - - this.head = null; - this.tail = null; - this.length = 0; - } - - BufferList.prototype.push = function push(v) { - var entry = { data: v, next: null }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - }; - - BufferList.prototype.unshift = function unshift(v) { - var entry = { data: v, next: this.head }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - }; - - BufferList.prototype.shift = function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - }; - - BufferList.prototype.clear = function clear() { - this.head = this.tail = null; - this.length = 0; - }; - - BufferList.prototype.join = function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - while (p = p.next) { - ret += s + p.data; - }return ret; +var _Object$setPrototypeO; +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var finished = __nccwpck_require__(76080); +var kLastResolve = Symbol('lastResolve'); +var kLastReject = Symbol('lastReject'); +var kError = Symbol('error'); +var kEnded = Symbol('ended'); +var kLastPromise = Symbol('lastPromise'); +var kHandlePromise = Symbol('handlePromise'); +var kStream = Symbol('stream'); +function createIterResult(value, done) { + return { + value: value, + done: done }; - - BufferList.prototype.concat = function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; +} +function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + if (resolve !== null) { + var data = iter[kStream].read(); + // we defer if data is null + // we can be expecting either 'end' or + // 'error' + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); } - return ret; - }; - - return BufferList; -}(); - -if (util && util.inspect && util.inspect.custom) { - module.exports.prototype[util.inspect.custom] = function () { - var obj = util.inspect({ length: this.length }); - return this.constructor.name + ' ' + obj; + } +} +function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + process.nextTick(readAndResolve, iter); +} +function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } + iter[kHandlePromise](resolve, reject); + }, reject); }; } +var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); +var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + next: function next() { + var _this = this; + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; + if (error !== null) { + return Promise.reject(error); + } + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + process.nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } -/***/ }), - -/***/ 11434: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -/**/ - -var pna = __nccwpck_require__(13817); -/**/ - -// undocumented cb() API, needed for core, not for public API -function destroy(err, cb) { - var _this = this; - - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - pna.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - pna.nextTick(emitErrorNT, this, err); + // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time + var lastPromise = this[kLastPromise]; + var promise; + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); } + promise = new Promise(this[kHandlePromise]); } - - return this; - } - - // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - if (this._readableState) { - this._readableState.destroyed = true; - } - - // if this is a duplex stream mark the writable part as destroyed as well - if (this._writableState) { - this._writableState.destroyed = true; + this[kLastPromise] = promise; + return promise; } - - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - pna.nextTick(emitErrorNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - pna.nextTick(emitErrorNT, _this, err); +}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; +}), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; } - } else if (cb) { - cb(err); + resolve(createIterResult(undefined, true)); + }); + }); +}), _Object$setPrototypeO), AsyncIteratorPrototype); +var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { + var _Object$create; + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; + // reject if we are waiting for data in the Promise + // returned by next() and store the error + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + iterator[kError] = err; + return; + } + var resolve = iterator[kLastResolve]; + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); } + iterator[kEnded] = true; }); - - return this; -} - -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } -} - -function emitErrorNT(self, err) { - self.emit('error', err); -} - -module.exports = { - destroy: destroy, - undestroy: undestroy + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; }; +module.exports = createReadableStreamAsyncIterator; /***/ }), -/***/ 77660: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = __nccwpck_require__(12781); - - -/***/ }), - -/***/ 8873: +/***/ 52746: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = __nccwpck_require__(86559).PassThrough - - -/***/ }), +"use strict"; -/***/ 86559: -/***/ ((module, exports, __nccwpck_require__) => { -var Stream = __nccwpck_require__(12781); -if (process.env.READABLE_STREAM === 'disable' && Stream) { - module.exports = Stream; - exports = module.exports = Stream.Readable; - exports.Readable = Stream.Readable; - exports.Writable = Stream.Writable; - exports.Duplex = Stream.Duplex; - exports.Transform = Stream.Transform; - exports.PassThrough = Stream.PassThrough; - exports.Stream = Stream; -} else { - exports = module.exports = __nccwpck_require__(90708); - exports.Stream = Stream || exports; - exports.Readable = exports; - exports.Writable = __nccwpck_require__(32383); - exports.Duplex = __nccwpck_require__(28409); - exports.Transform = __nccwpck_require__(60927); - exports.PassThrough = __nccwpck_require__(65285); +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var _require = __nccwpck_require__(14300), + Buffer = _require.Buffer; +var _require2 = __nccwpck_require__(73837), + inspect = _require2.inspect; +var custom = inspect && inspect.custom || 'inspect'; +function copyBuffer(src, target, offset) { + Buffer.prototype.copy.call(src, target, offset); } +module.exports = /*#__PURE__*/function () { + function BufferList() { + _classCallCheck(this, BufferList); + this.head = null; + this.tail = null; + this.length = 0; + } + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) ret += s + p.data; + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + } + + // Consumes a specified amount of bytes or characters from the buffered data. + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } + + // Consumes a specified amount of characters from the buffered data. + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + + // Consumes a specified amount of bytes from the buffered data. + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + // Make sure the linked list only shows the minimal necessary information. + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread(_objectSpread({}, options), {}, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + return BufferList; +}(); /***/ }), -/***/ 63997: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 97049: +/***/ ((module) => { -/* eslint-disable node/no-deprecated-api */ -var buffer = __nccwpck_require__(14300) -var Buffer = buffer.Buffer +"use strict"; -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } + } + return this; + } -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') + if (this._readableState) { + this._readableState.destroyed = true; } - return Buffer(arg, encodingOrOffset, length) -} -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err); + } else { + process.nextTick(emitCloseNT, _this); + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err); } else { - buf.fill(fill) + process.nextTick(emitCloseNT, _this); } - } else { - buf.fill(0) - } - return buf + }); + return this; } - -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) +function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); } - -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') +function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); +} +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; } - return buffer.SlowBuffer(size) + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} +function emitErrorNT(self, err) { + self.emit('error', err); } +function errorOrDestroy(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); +} +module.exports = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy +}; /***/ }), -/***/ 91843: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 76080: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - -/**/ +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). -var Buffer = (__nccwpck_require__(63997).Buffer); -/**/ -var isEncoding = Buffer.isEncoding || function (encoding) { - encoding = '' + encoding; - switch (encoding && encoding.toLowerCase()) { - case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': - return true; - default: - return false; - } -}; -function _normalizeEncoding(enc) { - if (!enc) return 'utf8'; - var retried; - while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; +var ERR_STREAM_PREMATURE_CLOSE = (__nccwpck_require__(67214)/* .codes.ERR_STREAM_PREMATURE_CLOSE */ .q.ERR_STREAM_PREMATURE_CLOSE); +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; } - } -}; - -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; + callback.apply(this, args); + }; } - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.s = StringDecoder; -function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case 'utf16le': - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case 'utf8': - this.fillLast = utf8FillLast; - nb = 4; - break; - case 'base64': - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; +function noop() {} +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} +function eos(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; + var writableEnded = stream._writableState && stream._writableState.finished; + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; + var readableEnded = stream._readableState && stream._readableState.endEmitted; + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; + var onerror = function onerror(err) { + callback.call(stream, err); + }; + var onclose = function onclose() { + var err; + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer.allocUnsafe(nb); + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; } +module.exports = eos; -StringDecoder.prototype.write = function (buf) { - if (buf.length === 0) return ''; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ''; - i = this.lastNeed; - this.lastNeed = 0; - } else { - i = 0; - } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; -}; +/***/ }), -StringDecoder.prototype.end = utf8End; - -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; +/***/ 39082: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; -}; +"use strict"; -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. If an invalid byte is detected, -2 is returned. -function utf8CheckByte(byte) { - if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return byte >> 6 === 0x02 ? -1 : -2; -} -// Checks at most 3 bytes at the end of a Buffer in order to detect an -// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) -// needed to complete the UTF-8 character (if applicable) are returned. -function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var ERR_INVALID_ARG_TYPE = (__nccwpck_require__(67214)/* .codes.ERR_INVALID_ARG_TYPE */ .q.ERR_INVALID_ARG_TYPE); +function from(Readable, iterable, opts) { + var iterator; + if (iterable && typeof iterable.next === 'function') { + iterator = iterable; + } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); + var readable = new Readable(_objectSpread({ + objectMode: true + }, opts)); + // Reading boolean to protect against _read + // being called before last iteration completion. + var reading = false; + readable._read = function () { + if (!reading) { + reading = true; + next(); } - return nb; - } - return 0; -} - -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding -// behavior. The continuation byte check is included three times in the case -// where all of the continuation bytes for a character exist in the same buffer. -// It is also done this way as a slight performance increase instead of using a -// loop. -function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xC0) !== 0x80) { - self.lastNeed = 0; - return '\ufffd'; + }; + function next() { + return _next2.apply(this, arguments); } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'; - } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'; + function _next2() { + _next2 = _asyncToGenerator(function* () { + try { + var _yield$iterator$next = yield iterator.next(), + value = _yield$iterator$next.value, + done = _yield$iterator$next.done; + if (done) { + readable.push(null); + } else if (readable.push(yield value)) { + next(); + } else { + reading = false; + } + } catch (err) { + readable.destroy(err); } - } + }); + return _next2.apply(this, arguments); } + return readable; } +module.exports = from; -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; -} -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -function utf8Text(buf, i) { - var total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString('utf8', i); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString('utf8', i, end); -} +/***/ }), -// For UTF-8, a replacement character is added when ending on a partial -// character. -function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'; - return r; -} +/***/ 76989: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -function utf16Text(buf, i) { - if ((buf.length - i) % 2 === 0) { - var r = buf.toString('utf16le', i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 0xD800 && c <= 0xDBFF) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } - } - return r; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); -} +"use strict"; +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString('utf16le', 0, end); - } - return r; -} -function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString('base64', i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - } - return buf.toString('base64', i, buf.length - n); -} -function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); - return r; +var eos; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; } - -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); +var _require$codes = (__nccwpck_require__(67214)/* .codes */ .q), + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; +function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; +} +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; } +function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = __nccwpck_require__(76080); + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; + // request.destroy just do .end - .abort is what we want + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; +} +function call(fn) { + fn(); +} +function pipe(from, to) { + return from.pipe(to); +} +function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); +} +function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); } +module.exports = pipeline; /***/ }), -/***/ 70891: +/***/ 39948: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var listenerCount = (__nccwpck_require__(82361).listenerCount) -// listenerCount isn't in node 0.10, so here's a basic polyfill -listenerCount = listenerCount || function (ee, event) { - var listeners = ee && ee._events && ee._events[event] - if (Array.isArray(listeners)) { - return listeners.length - } else if (typeof listeners === 'function') { - return 1 - } else { - return 0 - } +var ERR_INVALID_OPT_VALUE = (__nccwpck_require__(67214)/* .codes.ERR_INVALID_OPT_VALUE */ .q.ERR_INVALID_OPT_VALUE); +function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; } +function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + return Math.floor(hwm); + } -module.exports = listenerCount - + // Default value + return state.objectMode ? 16 : 16 * 1024; +} +module.exports = { + getHighWaterMark: getHighWaterMark +}; /***/ }), -/***/ 14285: -/***/ ((module) => { - -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ - -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; +/***/ 62387: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]'; +module.exports = __nccwpck_require__(12781); -/** Used to detect unsigned integer values. */ -var reIsUint = /^(?:0|[1-9]\d*)$/; -/** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ -function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); -} +/***/ }), -/** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ -function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); +/***/ 51642: +/***/ ((module, exports, __nccwpck_require__) => { - while (++index < n) { - result[index] = iteratee(index); - } - return result; +var Stream = __nccwpck_require__(12781); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream.Readable; + Object.assign(module.exports, Stream); + module.exports.Stream = Stream; +} else { + exports = module.exports = __nccwpck_require__(51433); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = __nccwpck_require__(26993); + exports.Duplex = __nccwpck_require__(41359); + exports.Transform = __nccwpck_require__(34415); + exports.PassThrough = __nccwpck_require__(81542); + exports.finished = __nccwpck_require__(76080); + exports.pipeline = __nccwpck_require__(76989); } -/** Used for built-in method references. */ -var objectProto = Object.prototype; -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; +/***/ }), -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; +/***/ 44967: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** Built-in value references. */ -var propertyIsEnumerable = objectProto.propertyIsEnumerable; +module.exports = readdirGlob; -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max; +const fs = __nccwpck_require__(57147); +const { EventEmitter } = __nccwpck_require__(82361); +const { Minimatch } = __nccwpck_require__(27771); +const { resolve } = __nccwpck_require__(71017); -/** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ -function arrayLikeKeys(value, inherited) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - // Safari 9 makes `arguments.length` enumerable in strict mode. - var result = (isArray(value) || isArguments(value)) - ? baseTimes(value.length, String) - : []; +function readdir(dir, strict) { + return new Promise((resolve, reject) => { + fs.readdir(dir, {withFileTypes: true} ,(err, files) => { + if(err) { + switch (err.code) { + case 'ENOTDIR': // Not a directory + if(strict) { + reject(err); + } else { + resolve([]); + } + break; + case 'ENOTSUP': // Operation not supported + case 'ENOENT': // No such file or directory + case 'ENAMETOOLONG': // Filename too long + case 'UNKNOWN': + resolve([]); + break; + case 'ELOOP': // Too many levels of symbolic links + default: + reject(err); + break; + } + } else { + resolve(files); + } + }); + }); +} +function stat(file, followSymlinks) { + return new Promise((resolve, reject) => { + const statFunc = followSymlinks ? fs.stat : fs.lstat; + statFunc(file, (err, stats) => { + if(err) { + switch (err.code) { + case 'ENOENT': + if(followSymlinks) { + // Fallback to lstat to handle broken links as files + resolve(stat(file, false)); + } else { + resolve(null); + } + break; + default: + resolve(null); + break; + } + } else { + resolve(stats); + } + }); + }); +} - var length = result.length, - skipIndexes = !!length; +async function* exploreWalkAsync(dir, path, followSymlinks, useStat, shouldSkip, strict) { + let files = await readdir(path + dir, strict); + for(const file of files) { + let name = file.name; + if(name === undefined) { + // undefined file.name means the `withFileTypes` options is not supported by node + // we have to call the stat function to know if file is directory or not. + name = file; + useStat = true; + } + const filename = dir + '/' + name; + const relative = filename.slice(1); // Remove the leading / + const absolute = path + '/' + relative; + let stats = null; + if(useStat || followSymlinks) { + stats = await stat(absolute, followSymlinks); + } + if(!stats && file.name !== undefined) { + stats = file; + } + if(stats === null) { + stats = { isDirectory: () => false }; + } - for (var key in value) { - if ((inherited || hasOwnProperty.call(value, key)) && - !(skipIndexes && (key == 'length' || isIndex(key, length)))) { - result.push(key); + if(stats.isDirectory()) { + if(!shouldSkip(relative)) { + yield {relative, absolute, stats}; + yield* exploreWalkAsync(filename, path, followSymlinks, useStat, shouldSkip, false); + } + } else { + yield {relative, absolute, stats}; } } - return result; } - -/** - * Used by `_.defaults` to customize its `_.assignIn` use. - * - * @private - * @param {*} objValue The destination value. - * @param {*} srcValue The source value. - * @param {string} key The key of the property to assign. - * @param {Object} object The parent object of `objValue`. - * @returns {*} Returns the value to assign. - */ -function assignInDefaults(objValue, srcValue, key, object) { - if (objValue === undefined || - (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { - return srcValue; - } - return objValue; +async function* explore(path, followSymlinks, useStat, shouldSkip) { + yield* exploreWalkAsync('', path, followSymlinks, useStat, shouldSkip, true); } -/** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ -function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - object[key] = value; - } -} -/** - * The base implementation of `_.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 = []; +function readOptions(options) { + return { + pattern: options.pattern, + dot: !!options.dot, + noglobstar: !!options.noglobstar, + matchBase: !!options.matchBase, + nocase: !!options.nocase, + ignore: options.ignore, + skip: options.skip, - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { - result.push(key); - } - } - return result; + follow: !!options.follow, + stat: !!options.stat, + nodir: !!options.nodir, + mark: !!options.mark, + silent: !!options.silent, + absolute: !!options.absolute + }; } -/** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ -function baseRest(func, start) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); +class ReaddirGlob extends EventEmitter { + constructor(cwd, options, cb) { + super(); + if(typeof options === 'function') { + cb = options; + options = null; + } - while (++index < length) { - array[index] = args[start + index]; + this.options = readOptions(options || {}); + + this.matchers = []; + if(this.options.pattern) { + const matchers = Array.isArray(this.options.pattern) ? this.options.pattern : [this.options.pattern]; + this.matchers = matchers.map( m => + new Minimatch(m, { + dot: this.options.dot, + noglobstar:this.options.noglobstar, + matchBase:this.options.matchBase, + nocase:this.options.nocase + }) + ); } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; + + this.ignoreMatchers = []; + if(this.options.ignore) { + const ignorePatterns = Array.isArray(this.options.ignore) ? this.options.ignore : [this.options.ignore]; + this.ignoreMatchers = ignorePatterns.map( ignore => + new Minimatch(ignore, {dot: true}) + ); + } + + this.skipMatchers = []; + if(this.options.skip) { + const skipPatterns = Array.isArray(this.options.skip) ? this.options.skip : [this.options.skip]; + this.skipMatchers = skipPatterns.map( skip => + new Minimatch(skip, {dot: true}) + ); } - otherArgs[start] = array; - return apply(func, this, otherArgs); - }; -} -/** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ -function copyObject(source, props, object, customizer) { - object || (object = {}); + this.iterator = explore(resolve(cwd || '.'), this.options.follow, this.options.stat, this._shouldSkipDirectory.bind(this)); + this.paused = false; + this.inactive = false; + this.aborted = false; + + if(cb) { + this._matches = []; + this.on('match', match => this._matches.push(this.options.absolute ? match.absolute : match.relative)); + this.on('error', err => cb(err)); + this.on('end', () => cb(null, this._matches)); + } - var index = -1, - length = props.length; + setTimeout( () => this._next(), 0); + } - while (++index < length) { - var key = props[index]; + _shouldSkipDirectory(relative) { + //console.log(relative, this.skipMatchers.some(m => m.match(relative))); + return this.skipMatchers.some(m => m.match(relative)); + } - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; + _fileMatches(relative, isDirectory) { + const file = relative + (isDirectory ? '/' : ''); + return (this.matchers.length === 0 || this.matchers.some(m => m.match(file))) + && !this.ignoreMatchers.some(m => m.match(file)) + && (!this.options.nodir || !isDirectory); + } - assignValue(object, key, newValue === undefined ? source[key] : newValue); + _next() { + if(!this.paused && !this.aborted) { + this.iterator.next() + .then((obj)=> { + if(!obj.done) { + const isDirectory = obj.value.stats.isDirectory(); + if(this._fileMatches(obj.value.relative, isDirectory )) { + let relative = obj.value.relative; + let absolute = obj.value.absolute; + if(this.options.mark && isDirectory) { + relative += '/'; + absolute += '/'; + } + if(this.options.stat) { + this.emit('match', {relative, absolute, stat:obj.value.stats}); + } else { + this.emit('match', {relative, absolute}); + } + } + this._next(this.iterator); + } else { + this.emit('end'); + } + }) + .catch((err) => { + this.abort(); + this.emit('error', err); + if(!err.code && !this.options.silent) { + console.error(err); + } + }); + } else { + this.inactive = true; + } } - return object; -} -/** - * 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; + abort() { + this.aborted = true; + } - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; + pause() { + this.paused = true; + } - 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); - } + resume() { + this.paused = false; + if(this.inactive) { + this.inactive = false; + this._next(); } - return object; - }); + } } -/** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ -function isIndex(value, length) { - length = length == null ? MAX_SAFE_INTEGER : length; - return !!length && - (typeof value == 'number' || reIsUint.test(value)) && - (value > -1 && value % 1 == 0 && value < length); -} -/** - * Checks if the given arguments are from an iteratee call. - * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. - */ -function isIterateeCall(value, index, object) { - if (!isObject(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike(object) && isIndex(index, object.length)) - : (type == 'string' && index in object) - ) { - return eq(object[index], value); - } - return false; +function readdirGlob(pattern, options, cb) { + return new ReaddirGlob(pattern, options, cb); } +readdirGlob.ReaddirGlob = ReaddirGlob; -/** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ -function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; +/***/ }), - return value === proto; +/***/ 80226: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var balanced = __nccwpck_require__(9417); + +module.exports = expandTop; + +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; + +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); } -/** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function nativeKeysIn(object) { - var result = []; - if (object != null) { - for (var key in Object(object)) { - result.push(key); - } - } - return result; +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); } -/** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ -function eq(value, other) { - return value === other || (value !== value && other !== other); +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); } -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); + +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + + var parts = []; + var m = balanced('{', '}', str); + + if (!m) + return str.split(','); + + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } + + parts.push.apply(parts, p); + + return parts; } -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; +function expandTop(str) { + if (!str) + return []; -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } + + return expand(escapeBraces(str), true).map(unescapeBraces); } -/** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ -function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); } -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; +function lte(i, y) { + return i <= y; } - -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +function gte(i, y) { + return i >= y; } -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); -} +function expand(str, isTop) { + var expansions = []; -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} + var m = balanced('{', '}', str); + if (!m) return [str]; -/** - * This method is like `_.assignIn` except that it accepts `customizer` - * which is invoked to produce the assigned values. If `customizer` returns - * `undefined`, assignment is handled by the method instead. The `customizer` - * is invoked with five arguments: (objValue, srcValue, key, object, source). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias extendWith - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @see _.assignWith - * @example - * - * function customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } - * - * var defaults = _.partialRight(_.assignInWith, customizer); - * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ -var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keysIn(source), object, customizer); -}); + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; -/** - * Assigns own and inherited enumerable string keyed properties of source - * objects to the destination object for all destination properties that - * resolve to `undefined`. Source objects are applied from left to right. - * Once a property is set, additional values of the same property are ignored. - * - * **Note:** This method mutates `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaultsDeep - * @example - * - * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ -var defaults = baseRest(function(args) { - args.push(undefined, assignInDefaults); - return apply(assignInWith, undefined, args); -}); + if (/\$$/.test(m.pre)) { + for (var k = 0; k < post.length; k++) { + var expansion = pre+ '{' + m.body + '}' + post[k]; + expansions.push(expansion); + } + } else { + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } -/** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) - */ -function keysIn(object) { - return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = []; + + for (var j = 0; j < n.length; j++) { + N.push.apply(N, expand(n[j], false)); + } + } + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + } + + return expansions; } -module.exports = defaults; /***/ }), -/***/ 23651: +/***/ 79482: /***/ ((module) => { -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ +const isWindows = typeof process === 'object' && + process && + process.platform === 'win32' +module.exports = isWindows ? { sep: '\\' } : { sep: '/' } -/** Used as the size to enable large array optimizations. */ -var LARGE_ARRAY_SIZE = 200; -/** Used to stand-in for `undefined` hash values. */ -var HASH_UNDEFINED = '__lodash_hash_undefined__'; +/***/ }), -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; +/***/ 27771: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]'; +const minimatch = module.exports = (p, pattern, options = {}) => { + assertValidPattern(pattern) -/** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ -var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } -/** Used to detect host constructors (Safari). */ -var reIsHostCtor = /^\[object .+?Constructor\]$/; + return new Minimatch(pattern, options).match(p) +} -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; +module.exports = minimatch -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; +const path = __nccwpck_require__(79482) +minimatch.sep = path.sep -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); +const GLOBSTAR = Symbol('globstar **') +minimatch.GLOBSTAR = GLOBSTAR +const expand = __nccwpck_require__(80226) -/** - * 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); +const plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } } -/** - * 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 ? array.length : 0; - return !!length && baseIndexOf(array, value, 0) > -1; -} +// any single thing other than / +// don't need to escape / when using new RegExp() +const qmark = '[^/]' -/** - * 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 ? array.length : 0; +// * => any number of characters +const star = qmark + '*?' - while (++index < length) { - if (comparator(value, array[index])) { - return true; - } - } - return false; -} +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +const twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' -/** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ -function arrayMap(array, iteratee) { - var index = -1, - length = array ? array.length : 0, - result = Array(length); +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +const twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; -} +// "abc" -> { a:true, b:true, c:true } +const charSet = s => s.split('').reduce((set, c) => { + set[c] = true + return set +}, {}) -/** - * 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; +// characters that need to be escaped in RegExp. +const reSpecials = charSet('().*{}+?[]^$\\!') - while (++index < length) { - array[offset + index] = values[index]; - } - return array; -} +// characters that indicate we have to add the pattern start +const addPatternStartSet = charSet('[.(') -/** - * 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); +// normalizes slashes. +const slashSplit = /\/+/ - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; +minimatch.filter = (pattern, options = {}) => + (p, i, list) => minimatch(p, pattern, options) + +const ext = (a, b = {}) => { + const t = {} + Object.keys(a).forEach(k => t[k] = a[k]) + Object.keys(b).forEach(k => t[k] = b[k]) + return t } -/** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseIndexOf(array, value, fromIndex) { - if (value !== value) { - return baseFindIndex(array, baseIsNaN, fromIndex); +minimatch.defaults = def => { + if (!def || typeof def !== 'object' || !Object.keys(def).length) { + return minimatch } - var index = fromIndex - 1, - length = array.length; - while (++index < length) { - if (array[index] === value) { - return index; + const orig = minimatch + + const m = (p, pattern, options) => orig(p, pattern, ext(def, options)) + m.Minimatch = class Minimatch extends orig.Minimatch { + constructor (pattern, options) { + super(pattern, ext(def, options)) } } - return -1; -} + m.Minimatch.defaults = options => orig.defaults(ext(def, options)).Minimatch + m.filter = (pattern, options) => orig.filter(pattern, ext(def, options)) + m.defaults = options => orig.defaults(ext(def, options)) + m.makeRe = (pattern, options) => orig.makeRe(pattern, ext(def, options)) + m.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext(def, options)) + m.match = (list, pattern, options) => orig.match(list, pattern, ext(def, options)) -/** - * 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 m } -/** - * 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); - }; -} -/** - * 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); -} -/** - * 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]; -} -/** - * Checks if `value` is a host object in IE < 9. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a host object, else `false`. - */ -function isHostObject(value) { - // Many host objects are `Object` objects that can coerce to strings - // despite having improperly defined `toString` methods. - var result = false; - if (value != null && typeof value.toString != 'function') { - try { - result = !!(value + ''); - } catch (e) {} + +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = (pattern, options) => braceExpand(pattern, options) + +const braceExpand = (pattern, options = {}) => { + assertValidPattern(pattern) + + // Thanks to Yeting Li for + // improving this regexp to avoid a ReDOS vulnerability. + if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { + // shortcut. no need to expand. + return [pattern] } - return result; + + return expand(pattern) } -/** Used for built-in method references. */ -var arrayProto = Array.prototype, - funcProto = Function.prototype, - objectProto = Object.prototype; +const MAX_PATTERN_LENGTH = 1024 * 64 +const assertValidPattern = pattern => { + if (typeof pattern !== 'string') { + throw new TypeError('invalid pattern') + } -/** Used to detect overreaching core-js shims. */ -var coreJsData = root['__core-js_shared__']; + if (pattern.length > MAX_PATTERN_LENGTH) { + throw new TypeError('pattern is too long') + } +} -/** 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) : ''; -}()); +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +const SUBPARSE = Symbol('subparse') -/** Used to resolve the decompiled source of functions. */ -var funcToString = funcProto.toString; +minimatch.makeRe = (pattern, options) => + new Minimatch(pattern, options || {}).makeRe() -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; +minimatch.match = (list, pattern, options = {}) => { + const mm = new Minimatch(pattern, options) + list = list.filter(f => mm.match(f)) + if (mm.options.nonull && !list.length) { + list.push(pattern) + } + return list +} -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; +// replace stuff like \* with * +const globUnescape = s => s.replace(/\\(.)/g, '$1') +const charUnescape = s => s.replace(/\\([^-\]])/g, '$1') +const regExpEscape = s => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +const braExpEscape = s => s.replace(/[[\]\\]/g, '\\$&') -/** Used to detect if a method is native. */ -var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' -); +class Minimatch { + constructor (pattern, options) { + assertValidPattern(pattern) -/** Built-in value references. */ -var Symbol = root.Symbol, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - splice = arrayProto.splice, - spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; + if (!options) options = {} -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max; + this.options = options + this.set = [] + this.pattern = pattern + this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || + options.allowWindowsEscape === false + if (this.windowsPathsNoEscape) { + this.pattern = this.pattern.replace(/\\/g, '/') + } + this.regexp = null + this.negate = false + this.comment = false + this.empty = false + this.partial = !!options.partial -/* Built-in method references that are verified to be native. */ -var Map = getNative(root, 'Map'), - nativeCreate = getNative(Object, 'create'); + // make the set of regexps etc. + this.make() + } -/** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function Hash(entries) { - var index = -1, - length = entries ? entries.length : 0; + debug () {} - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} + make () { + const pattern = this.pattern + const options = this.options -/** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ -function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; -} + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return + } -/** - * 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) { - return this.has(key) && delete this.__data__[key]; -} + // step 1: figure out negation, etc. + this.parseNegate() -/** - * 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; -} + // step 2: expand braces + let set = this.globSet = this.braceExpand() -/** - * 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 (options.debug) this.debug = (...args) => console.error(...args) -/** - * 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__; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; - return this; -} + this.debug(this.pattern, set) -// Add methods to `Hash`. -Hash.prototype.clear = hashClear; -Hash.prototype['delete'] = hashDelete; -Hash.prototype.get = hashGet; -Hash.prototype.has = hashHas; -Hash.prototype.set = hashSet; + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(s => s.split(slashSplit)) -/** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function ListCache(entries) { - var index = -1, - length = entries ? entries.length : 0; + this.debug(this.pattern, set) - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} + // glob --> regexps + set = set.map((s, si, set) => s.map(this.parse, this)) -/** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ -function listCacheClear() { - this.__data__ = []; -} + this.debug(this.pattern, set) -/** - * 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); + // filter out everything that didn't compile properly. + set = set.filter(s => s.indexOf(false) === -1) - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - return true; -} + this.debug(this.pattern, set) -/** - * 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); + this.set = set + } - return index < 0 ? undefined : data[index][1]; -} + parseNegate () { + if (this.options.nonegate) return -/** - * 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; -} + const pattern = this.pattern + let negate = false + let negateOffset = 0 -/** - * 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); + for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) { + negate = !negate + negateOffset++ + } - if (index < 0) { - data.push([key, value]); - } else { - data[index][1] = value; + if (negateOffset) this.pattern = pattern.slice(negateOffset) + this.negate = negate } - 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; + // set partial to true to test if, for example, + // "/a/b" matches the start of "/*/b/*/d" + // Partial means, if you run out of file before you run + // out of pattern, then that's fine, as long as all + // the parts match. + matchOne (file, pattern, partial) { + var options = this.options -/** - * 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 ? entries.length : 0; + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} + this.debug('matchOne', file.length, pattern.length) -/** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ -function mapCacheClear() { - this.__data__ = { - 'hash': new Hash, - 'map': new (Map || ListCache), - 'string': new Hash - }; -} + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] -/** - * 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) { - return getMapData(this, key)['delete'](key); -} + this.debug(pattern, p, f) -/** - * 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); -} + // should be impossible. + // some invalid regexp stuff in the set. + /* istanbul ignore if */ + if (p === false) return false -/** - * 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); -} + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) -/** - * 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) { - getMapData(this, key).set(key, value); - return this; -} + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + var pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } -// Add methods to `MapCache`. -MapCache.prototype.clear = mapCacheClear; -MapCache.prototype['delete'] = mapCacheDelete; -MapCache.prototype.get = mapCacheGet; -MapCache.prototype.has = mapCacheHas; -MapCache.prototype.set = mapCacheSet; + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] -/** - * - * 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 ? values.length : 0; + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); - } -} + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr) + break + } -/** - * 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; -} + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } + } -/** - * 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); -} + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + /* istanbul ignore if */ + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true + } + return false + } -// Add methods to `SetCache`. -SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; -SetCache.prototype.has = setCacheHas; + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === 'string') { + hit = f === p + this.debug('string match', p, f, hit) + } else { + hit = f.match(p) + this.debug('pattern match', p, f, hit) + } -/** - * 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; + if (!hit) return false } - } - return -1; -} -/** - * 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; + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* - if (!length) { - return result; - } - if (iteratee) { - values = arrayMap(values, baseUnary(iteratee)); - } - if (comparator) { - includes = arrayIncludesWith; - isCommon = false; + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else /* istanbul ignore else */ if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + return (fi === fl - 1) && (file[fi] === '') + } + + // should be unreachable. + /* istanbul ignore next */ + throw new Error('wtf?') } - else if (values.length >= LARGE_ARRAY_SIZE) { - includes = cacheHas; - isCommon = false; - values = new SetCache(values); + + braceExpand () { + return braceExpand(this.pattern, this.options) } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : 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); + parse (pattern, isSub) { + assertValidPattern(pattern) + + const options = this.options + + // shortcuts + if (pattern === '**') { + if (!options.noglobstar) + return GLOBSTAR + else + pattern = '*' } - } - return result; -} + if (pattern === '') return '' -/** - * 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; + let re = '' + let hasMagic = false + let escaping = false + // ? => one single character + const patternListStack = [] + const negativeLists = [] + let stateChar + let inClass = false + let reClassStart = -1 + let classStart = -1 + let cs + let pl + let sp + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. However, if the pattern + // starts with ., then traversal patterns can match. + let dotTravAllowed = pattern.charAt(0) === '.' + let dotFileAllowed = options.dot || dotTravAllowed + const patternStart = () => + dotTravAllowed + ? '' + : dotFileAllowed + ? '(?!(?:^|\\/)\\.{1,2}(?:$|\\/))' + : '(?!\\.)' + const subPatternStart = (p) => + p.charAt(0) === '.' + ? '' + : options.dot + ? '(?!(?:^|\\/)\\.{1,2}(?:$|\\/))' + : '(?!\\.)' - 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); + const clearStateChar = () => { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star + hasMagic = true + break + case '?': + re += qmark + hasMagic = true + break + default: + re += '\\' + stateChar + break + } + this.debug('clearStateChar %j %j', stateChar, re) + stateChar = false } - } else if (!isStrict) { - result[result.length] = value; } - } - return result; -} -/** - * 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) || isHostObject(value)) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); -} + for (let i = 0, c; (i < pattern.length) && (c = pattern.charAt(i)); i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) -/** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ -function baseRest(func, start) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); + // skip over any that are escaped. + if (escaping) { + /* istanbul ignore next - completely not allowed, even escaped. */ + if (c === '/') { + return false + } - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = array; - return apply(func, this, otherArgs); - }; -} + if (reSpecials[c]) { + re += '\\' + } + re += c + escaping = false + continue + } -/** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ -function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; -} + switch (c) { + /* istanbul ignore next */ + case '/': { + // Should already be path-split by now. + return false + } -/** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ -function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; -} + case '\\': + if (inClass && pattern.charAt(i + 1) === '-') { + re += c + continue + } -/** - * 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]); -} + clearStateChar() + escaping = true + continue -/** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ -function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); -} + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) -/** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ -function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); -} + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === '!' && i === classStart + 1) c = '^' + re += c + continue + } -/** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to process. - * @returns {string} Returns the source code. - */ -function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; -} + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + this.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue -/** - * 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 of result values is determined by the - * order they occur in the first array. - * - * **Note:** Unlike `_.pullAll`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @see _.without, _.xor - * @example - * - * _.difference([2, 1], [2, 3]); - * // => [1] - */ -var difference = baseRest(function(array, values) { - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) - : []; -}); - -/** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ -function eq(value, other) { - return value === other || (value !== value && other !== other); -} + case '(': { + if (inClass) { + re += '(' + continue + } -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); -} + if (!stateChar) { + re += '\\(' + continue + } -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; + const plEntry = { + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close, + } + this.debug(this.pattern, '\t', plEntry) + patternListStack.push(plEntry) + // negation is (?:(?!(?:js)(?:))[^/]*) + re += plEntry.open + // next entry starts with a dot maybe? + if (plEntry.start === 0 && plEntry.type !== '!') { + dotTravAllowed = true + re += subPatternStart(pattern.slice(i + 1)) + } + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue + } -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); -} + case ')': { + const plEntry = patternListStack[patternListStack.length - 1] + if (inClass || !plEntry) { + re += '\\)' + continue + } + patternListStack.pop() -/** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ -function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); -} + // closing an extglob + clearStateChar() + hasMagic = true + pl = plEntry + // negation is (?:(?!js)[^/]*) + // The others are (?:) + re += pl.close + if (pl.type === '!') { + negativeLists.push(Object.assign(pl, { reEnd: re.length })) + } + continue + } -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; -} + case '|': { + const plEntry = patternListStack[patternListStack.length - 1] + if (inClass || !plEntry) { + re += '\\|' + continue + } -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; -} + clearStateChar() + re += '|' + // next subpattern can start with a dot? + if (plEntry.start === 0 && plEntry.type !== '!') { + dotTravAllowed = true + re += subPatternStart(pattern.slice(i + 1)) + } + continue + } -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); -} + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} + if (inClass) { + re += '\\' + c + continue + } -module.exports = difference; + inClass = true + classStart = i + reClassStart = re.length + re += c + continue + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c + continue + } -/***/ }), + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + cs = pattern.substring(classStart + 1, i) + try { + RegExp('[' + braExpEscape(charUnescape(cs)) + ']') + // looks good, finish up the class. + re += c + } catch (er) { + // out of order ranges in JS are errors, but in glob syntax, + // they're just a range that matches nothing. + re = re.substring(0, reClassStart) + '(?:$.)' // match nothing ever + } + hasMagic = true + inClass = false + continue -/***/ 25402: -/***/ ((module) => { + default: + // swallow any state char that wasn't consumed + clearStateChar() -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ + if (reSpecials[c] && !(c === '^' && inClass)) { + re += '\\' + } -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; + re += c + break -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]'; + } // switch + } // for -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.slice(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substring(0, reClassStart) + '\\[' + sp[0] + hasMagic = hasMagic || sp[1] + } -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + let tail + tail = re.slice(pl.reStart + pl.open.length) + this.debug('setting tail', re, pl) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_, $1, $2) => { + /* istanbul ignore else - should already be done */ + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\' + } -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }) -/** - * 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; + this.debug('tail=%j\n %s', tail, tail, pl, re) + const t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type - while (++index < length) { - array[offset + index] = values[index]; - } - return array; -} + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail + } -/** Used for built-in method references. */ -var objectProto = Object.prototype; + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' + } -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + const addPatternStart = addPatternStartSet[re.charAt(0)] -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (let n = negativeLists.length - 1; n > -1; n--) { + const nl = negativeLists[n] -/** Built-in value references. */ -var Symbol = root.Symbol, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; + const nlBefore = re.slice(0, nl.reStart) + const nlFirst = re.slice(nl.reStart, nl.reEnd - 8) + let nlAfter = re.slice(nl.reEnd) + const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter -/** - * 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; + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + const closeParensBefore = nlBefore.split(')').length + const openParensBefore = nlBefore.split('(').length - closeParensBefore + let cleanAfter = nlAfter + for (let i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') + } + nlAfter = cleanAfter - predicate || (predicate = isFlattenable); - result || (result = []); + const dollar = nlAfter === '' && isSub !== SUBPARSE ? '(?:$|\\/)' : '' - 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; + re = nlBefore + nlFirst + nlAfter + dollar + nlLast + } + + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re + } + + if (addPatternStart) { + re = patternStart() + re + } + + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } + + // if it's nocase, and the lcase/uppercase don't match, it's magic + if (options.nocase && !hasMagic) { + hasMagic = pattern.toUpperCase() !== pattern.toLowerCase() + } + + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } + + const flags = options.nocase ? 'i' : '' + try { + return Object.assign(new RegExp('^' + re + '$', flags), { + _glob: pattern, + _src: re, + }) + } catch (er) /* istanbul ignore next - should be impossible */ { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.') } } - return result; -} -/** - * Checks if `value` is a flattenable `arguments` object or array. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. - */ -function isFlattenable(value) { - return isArray(value) || isArguments(value) || - !!(spreadableSymbol && value && value[spreadableSymbol]); -} + makeRe () { + if (this.regexp || this.regexp === false) return this.regexp -/** - * Flattens `array` a single level deep. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example - * - * _.flatten([1, [2, [3, [4]], 5]]); - * // => [1, 2, [3, [4]], 5] - */ -function flatten(array) { - var length = array ? array.length : 0; - return length ? baseFlatten(array, 1) : []; -} + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + const set = this.set -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); -} + if (!set.length) { + this.regexp = false + return this.regexp + } + const options = this.options -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; + const twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + const flags = options.nocase ? 'i' : '' -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); -} + // coalesce globstars and regexpify non-globstar patterns + // if it's the only item, then we just do one twoStar + // if it's the first, and there are more, prepend (\/|twoStar\/)? to next + // if it's the last, append (\/twoStar|) to previous + // if it's in the middle, append (\/|\/twoStar\/) to previous + // then filter out GLOBSTAR symbols + let re = set.map(pattern => { + pattern = pattern.map(p => + typeof p === 'string' ? regExpEscape(p) + : p === GLOBSTAR ? GLOBSTAR + : p._src + ).reduce((set, p) => { + if (!(set[set.length - 1] === GLOBSTAR && p === GLOBSTAR)) { + set.push(p) + } + return set + }, []) + pattern.forEach((p, i) => { + if (p !== GLOBSTAR || pattern[i-1] === GLOBSTAR) { + return + } + if (i === 0) { + if (pattern.length > 1) { + pattern[i+1] = '(?:\\\/|' + twoStar + '\\\/)?' + pattern[i+1] + } else { + pattern[i] = twoStar + } + } else if (i === pattern.length - 1) { + pattern[i-1] += '(?:\\\/|' + twoStar + ')?' + } else { + pattern[i-1] += '(?:\\\/|\\\/' + twoStar + '\\\/)' + pattern[i+1] + pattern[i+1] = GLOBSTAR + } + }) + return pattern.filter(p => p !== GLOBSTAR).join('/') + }).join('|') -/** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ -function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); -} + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; -} + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; -} + try { + this.regexp = new RegExp(re, flags) + } catch (ex) /* istanbul ignore next - should be impossible */ { + this.regexp = false + } + return this.regexp + } -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); -} + match (f, partial = this.partial) { + this.debug('match', f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} + if (f === '/' && partial) return true -module.exports = flatten; + const options = this.options + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') + } -/***/ }), + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) -/***/ 98466: -/***/ ((module) => { + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ + const set = this.set + this.debug(this.pattern, 'set', set) -/** `Object#toString` result references. */ -var objectTag = '[object Object]'; + // Find the basename of the path by looking for the last non-empty segment + let filename + for (let i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break + } -/** - * Checks if `value` is a host object in IE < 9. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a host object, else `false`. - */ -function isHostObject(value) { - // Many host objects are `Object` objects that can coerce to strings - // despite having improperly defined `toString` methods. - var result = false; - if (value != null && typeof value.toString != 'function') { - try { - result = !!(value + ''); - } catch (e) {} + for (let i = 0; i < set.length; i++) { + const pattern = set[i] + let file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] + } + const hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate + } + } + + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate } - return result; -} -/** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ -function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; + static defaults (def) { + return minimatch.defaults(def).Minimatch + } } -/** Used for built-in method references. */ -var funcProto = Function.prototype, - objectProto = Object.prototype; +minimatch.Minimatch = Minimatch -/** 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 infer the `Object` constructor. */ -var objectCtorString = funcToString.call(Object); +/***/ 21867: +/***/ ((module, exports, __nccwpck_require__) => { -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = __nccwpck_require__(14300) +var Buffer = buffer.Buffer -/** Built-in value references. */ -var getPrototype = overArg(Object.getPrototypeOf, Object); +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) } -/** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * @static - * @memberOf _ - * @since 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - * - * _.isPlainObject(Object.create(null)); - * // => true - */ -function isPlainObject(value) { - if (!isObjectLike(value) || - objectToString.call(value) != objectTag || isHostObject(value)) { - return false; - } - var proto = getPrototype(value); - if (proto === null) { - return true; +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') } - var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; - return (typeof Ctor == 'function' && - Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); + return Buffer(arg, encodingOrOffset, length) } -module.exports = isPlainObject; - +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} -/***/ }), +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} -/***/ 76640: -/***/ ((module) => { +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ -/** Used as the size to enable large array optimizations. */ -var LARGE_ARRAY_SIZE = 200; +/***/ }), -/** Used to stand-in for `undefined` hash values. */ -var HASH_UNDEFINED = '__lodash_hash_undefined__'; +/***/ 72043: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0, - MAX_SAFE_INTEGER = 9007199254740991; +;(function (sax) { // wrapper for non-node envs + sax.parser = function (strict, opt) { return new SAXParser(strict, opt) } + sax.SAXParser = SAXParser + sax.SAXStream = SAXStream + sax.createStream = createStream -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]'; + // When we pass the MAX_BUFFER_LENGTH position, start checking for buffer overruns. + // When we check, schedule the next check for MAX_BUFFER_LENGTH - (max(buffer lengths)), + // since that's the earliest that a buffer overrun could occur. This way, checks are + // as rare as required, but as often as necessary to ensure never crossing this bound. + // Furthermore, buffers are only tested at most once per write(), so passing a very + // large string into write() might have undesirable effects, but this is manageable by + // the caller, so it is assumed to be safe. Thus, a call to write() may, in the extreme + // edge case, result in creating at most one complete copy of the string passed in. + // Set to Infinity to have unlimited buffers. + sax.MAX_BUFFER_LENGTH = 64 * 1024 -/** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ -var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + var buffers = [ + 'comment', 'sgmlDecl', 'textNode', 'tagName', 'doctype', + 'procInstName', 'procInstBody', 'entity', 'attribName', + 'attribValue', 'cdata', 'script' + ] -/** Used to detect host constructors (Safari). */ -var reIsHostCtor = /^\[object .+?Constructor\]$/; + sax.EVENTS = [ + 'text', + 'processinginstruction', + 'sgmldeclaration', + 'doctype', + 'comment', + 'opentagstart', + 'attribute', + 'opentag', + 'closetag', + 'opencdata', + 'cdata', + 'closecdata', + 'error', + 'end', + 'ready', + 'script', + 'opennamespace', + 'closenamespace' + ] -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + function SAXParser (strict, opt) { + if (!(this instanceof SAXParser)) { + return new SAXParser(strict, opt) + } -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + var parser = this + clearBuffers(parser) + parser.q = parser.c = '' + parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH + parser.opt = opt || {} + parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags + parser.looseCase = parser.opt.lowercase ? 'toLowerCase' : 'toUpperCase' + parser.tags = [] + parser.closed = parser.closedRoot = parser.sawRoot = false + parser.tag = parser.error = null + parser.strict = !!strict + parser.noscript = !!(strict || parser.opt.noscript) + parser.state = S.BEGIN + parser.strictEntities = parser.opt.strictEntities + parser.ENTITIES = parser.strictEntities ? Object.create(sax.XML_ENTITIES) : Object.create(sax.ENTITIES) + parser.attribList = [] -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); + // namespaces form a prototype chain. + // it always points at the current tag, + // which protos to its parent tag. + if (parser.opt.xmlns) { + parser.ns = Object.create(rootNS) + } -/** - * 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]); + // mostly just for error reporting + parser.trackPosition = parser.opt.position !== false + if (parser.trackPosition) { + parser.position = parser.line = parser.column = 0 + } + emit(parser, 'onready') } - return func.apply(thisArg, args); -} - -/** - * 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 ? array.length : 0; - return !!length && baseIndexOf(array, value, 0) > -1; -} -/** - * 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 ? array.length : 0; + if (!Object.create) { + Object.create = function (o) { + function F () {} + F.prototype = o + var newf = new F() + return newf + } + } - while (++index < length) { - if (comparator(value, array[index])) { - return true; + if (!Object.keys) { + Object.keys = function (o) { + var a = [] + for (var i in o) if (o.hasOwnProperty(i)) a.push(i) + return a } } - return false; -} -/** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ -function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; + function checkBufferLength (parser) { + var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10) + var maxActual = 0 + for (var i = 0, l = buffers.length; i < l; i++) { + var len = parser[buffers[i]].length + if (len > maxAllowed) { + // Text/cdata nodes can get big, and since they're buffered, + // we can get here under normal conditions. + // Avoid issues by emitting the text node now, + // so at least it won't get any bigger. + switch (buffers[i]) { + case 'textNode': + closeText(parser) + break - while (++index < length) { - array[offset + index] = values[index]; - } - return array; -} + case 'cdata': + emitNode(parser, 'oncdata', parser.cdata) + parser.cdata = '' + break -/** - * 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); + case 'script': + emitNode(parser, 'onscript', parser.script) + parser.script = '' + break - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; + default: + error(parser, 'Max buffer length exceeded: ' + buffers[i]) + } + } + maxActual = Math.max(maxActual, len) } + // schedule the next check for the earliest possible buffer overrun. + var m = sax.MAX_BUFFER_LENGTH - maxActual + parser.bufferCheckPosition = m + parser.position } - return -1; -} -/** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseIndexOf(array, value, fromIndex) { - if (value !== value) { - return baseFindIndex(array, baseIsNaN, fromIndex); + function clearBuffers (parser) { + for (var i = 0, l = buffers.length; i < l; i++) { + parser[buffers[i]] = '' + } } - var index = fromIndex - 1, - length = array.length; - while (++index < length) { - if (array[index] === value) { - return index; + function flushBuffers (parser) { + closeText(parser) + if (parser.cdata !== '') { + emitNode(parser, 'oncdata', parser.cdata) + parser.cdata = '' + } + if (parser.script !== '') { + emitNode(parser, 'onscript', parser.script) + parser.script = '' } } - return -1; -} - -/** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ -function baseIsNaN(value) { - return value !== value; -} - -/** - * 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); -} - -/** - * 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]; -} -/** - * Checks if `value` is a host object in IE < 9. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a host object, else `false`. - */ -function isHostObject(value) { - // Many host objects are `Object` objects that can coerce to strings - // despite having improperly defined `toString` methods. - var result = false; - if (value != null && typeof value.toString != 'function') { - try { - result = !!(value + ''); - } catch (e) {} + SAXParser.prototype = { + end: function () { end(this) }, + write: write, + resume: function () { this.error = null; return this }, + close: function () { return this.write(null) }, + flush: function () { flushBuffers(this) } } - return result; -} -/** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ -function setToArray(set) { - var index = -1, - result = Array(set.size); + var Stream + try { + Stream = (__nccwpck_require__(12781).Stream) + } catch (ex) { + Stream = function () {} + } + if (!Stream) Stream = function () {} - set.forEach(function(value) { - result[++index] = value; - }); - return result; -} + var streamWraps = sax.EVENTS.filter(function (ev) { + return ev !== 'error' && ev !== 'end' + }) -/** Used for built-in method references. */ -var arrayProto = Array.prototype, - funcProto = Function.prototype, - objectProto = Object.prototype; + function createStream (strict, opt) { + return new SAXStream(strict, opt) + } -/** Used to detect overreaching core-js shims. */ -var coreJsData = root['__core-js_shared__']; + function SAXStream (strict, opt) { + if (!(this instanceof SAXStream)) { + return new SAXStream(strict, opt) + } -/** 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) : ''; -}()); + Stream.apply(this) -/** Used to resolve the decompiled source of functions. */ -var funcToString = funcProto.toString; + this._parser = new SAXParser(strict, opt) + this.writable = true + this.readable = true -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; + var me = this -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; + this._parser.onend = function () { + me.emit('end') + } -/** Used to detect if a method is native. */ -var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' -); + this._parser.onerror = function (er) { + me.emit('error', er) -/** Built-in value references. */ -var Symbol = root.Symbol, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - splice = arrayProto.splice, - spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; + // if didn't throw, then means error was handled. + // go ahead and clear error, so we can write again. + me._parser.error = null + } -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max; + this._decoder = null -/* Built-in method references that are verified to be native. */ -var Map = getNative(root, 'Map'), - Set = getNative(root, 'Set'), - nativeCreate = getNative(Object, 'create'); - -/** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function Hash(entries) { - var index = -1, - length = entries ? entries.length : 0; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); + streamWraps.forEach(function (ev) { + Object.defineProperty(me, 'on' + ev, { + get: function () { + return me._parser['on' + ev] + }, + set: function (h) { + if (!h) { + me.removeAllListeners(ev) + me._parser['on' + ev] = h + return h + } + me.on(ev, h) + }, + enumerable: true, + configurable: false + }) + }) } -} -/** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ -function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; -} + SAXStream.prototype = Object.create(Stream.prototype, { + constructor: { + value: SAXStream + } + }) -/** - * 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) { - return this.has(key) && delete this.__data__[key]; -} + SAXStream.prototype.write = function (data) { + if (typeof Buffer === 'function' && + typeof Buffer.isBuffer === 'function' && + Buffer.isBuffer(data)) { + if (!this._decoder) { + var SD = (__nccwpck_require__(71576).StringDecoder) + this._decoder = new SD('utf8') + } + data = this._decoder.write(data) + } -/** - * 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; + this._parser.write(data.toString()) + this.emit('data', data) + return true } - return hasOwnProperty.call(data, key) ? data[key] : undefined; -} - -/** - * 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); -} - -/** - * 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__; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; - return this; -} - -// Add methods to `Hash`. -Hash.prototype.clear = hashClear; -Hash.prototype['delete'] = hashDelete; -Hash.prototype.get = hashGet; -Hash.prototype.has = hashHas; -Hash.prototype.set = hashSet; - -/** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function ListCache(entries) { - var index = -1, - length = entries ? entries.length : 0; - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); + SAXStream.prototype.end = function (chunk) { + if (chunk && chunk.length) { + this.write(chunk) + } + this._parser.end() + return true } -} - -/** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ -function listCacheClear() { - this.__data__ = []; -} -/** - * 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); + SAXStream.prototype.on = function (ev, handler) { + var me = this + if (!me._parser['on' + ev] && streamWraps.indexOf(ev) !== -1) { + me._parser['on' + ev] = function () { + var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments) + args.splice(0, 0, ev) + me.emit.apply(me, args) + } + } - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); + return Stream.prototype.on.call(me, ev, handler) } - return true; -} -/** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); + // this really needs to be replaced with character classes. + // XML allows all manner of ridiculous numbers and digits. + var CDATA = '[CDATA[' + var DOCTYPE = 'DOCTYPE' + var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace' + var XMLNS_NAMESPACE = 'http://www.w3.org/2000/xmlns/' + var rootNS = { xml: XML_NAMESPACE, xmlns: XMLNS_NAMESPACE } - return index < 0 ? undefined : data[index][1]; -} + // http://www.w3.org/TR/REC-xml/#NT-NameStartChar + // This implementation works on strings, a single character at a time + // as such, it cannot ever support astral-plane characters (10000-EFFFF) + // without a significant breaking change to either this parser, or the + // JavaScript language. Implementation of an emoji-capable xml parser + // is left as an exercise for the reader. + var nameStart = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/ -/** - * 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; -} + var nameBody = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/ -/** - * 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); + var entityStart = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/ + var entityBody = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/ - if (index < 0) { - data.push([key, value]); - } else { - data[index][1] = value; + function isWhitespace (c) { + return c === ' ' || c === '\n' || c === '\r' || c === '\t' } - return this; -} - -// Add methods to `ListCache`. -ListCache.prototype.clear = listCacheClear; -ListCache.prototype['delete'] = listCacheDelete; -ListCache.prototype.get = listCacheGet; -ListCache.prototype.has = listCacheHas; -ListCache.prototype.set = listCacheSet; - -/** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function MapCache(entries) { - var index = -1, - length = entries ? entries.length : 0; - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); + function isQuote (c) { + return c === '"' || c === '\'' } -} - -/** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ -function mapCacheClear() { - this.__data__ = { - 'hash': new Hash, - 'map': new (Map || ListCache), - 'string': new Hash - }; -} - -/** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function mapCacheDelete(key) { - return getMapData(this, key)['delete'](key); -} - -/** - * 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); -} - -/** - * 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); -} - -/** - * 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) { - getMapData(this, key).set(key, value); - 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; - -/** - * - * 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 ? values.length : 0; - - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); + function isAttribEnd (c) { + return c === '>' || isWhitespace(c) } -} - -/** - * 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; -} - -/** - * 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); -} - -// Add methods to `SetCache`. -SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; -SetCache.prototype.has = setCacheHas; -/** - * 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; - } + function isMatch (regex, c) { + return regex.test(c) } - return -1; -} -/** - * 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; + function notMatch (regex, c) { + return !isMatch(regex, c) + } - predicate || (predicate = isFlattenable); - result || (result = []); + var S = 0 + sax.STATE = { + BEGIN: S++, // leading byte order mark or whitespace + BEGIN_WHITESPACE: S++, // leading whitespace + TEXT: S++, // general stuff + TEXT_ENTITY: S++, // & and such. + OPEN_WAKA: S++, // < + SGML_DECL: S++, // + SCRIPT: S++, //