diff --git a/dist/index.js b/dist/index.js index ab81d4d..a6d7635 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,1263 +1,1539 @@ /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ -/***/ 3140: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.create = void 0; -const artifact_client_1 = __nccwpck_require__(5327); -/** - * Constructs an ArtifactClient - */ -function create() { - return artifact_client_1.DefaultArtifactClient.create(); -} -exports.create = create; -//# sourceMappingURL=artifact-client.js.map - -/***/ }), - -/***/ 5327: +/***/ 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; - 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]; })); -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 __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 })); -exports.DefaultArtifactClient = void 0; -const core = __importStar(__nccwpck_require__(7334)); -const upload_specification_1 = __nccwpck_require__(8359); -const upload_http_client_1 = __nccwpck_require__(9482); -const utils_1 = __nccwpck_require__(1337); -const path_and_artifact_name_validation_1 = __nccwpck_require__(1611); -const download_http_client_1 = __nccwpck_require__(2342); -const download_specification_1 = __nccwpck_require__(1087); -const config_variables_1 = __nccwpck_require__(7289); -const path_1 = __nccwpck_require__(1017); -class DefaultArtifactClient { +const client_1 = __nccwpck_require__(46190); +__exportStar(__nccwpck_require__(1647), exports); +__exportStar(__nccwpck_require__(38182), exports); +__exportStar(__nccwpck_require__(46190), exports); +const client = new client_1.DefaultArtifactClient(); +exports["default"] = client; +//# sourceMappingURL=artifact.js.map + +/***/ }), + +/***/ 54622: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +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*/ } + ]); + } /** - * Constructs a DefaultArtifactClient + * Creates a new `Timestamp` for the current time. */ - static create() { - return new DefaultArtifactClient(); + 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; } /** - * Uploads an artifact + * Converts a `Timestamp` to a JavaScript Date. */ - uploadArtifact(name, files, rootDirectory, options) { - return __awaiter(this, void 0, void 0, function* () { - core.info(`Starting artifact upload -For more detailed logs during the artifact upload process, enable step-debugging: https://docs.github.com/actions/monitoring-and-troubleshooting-workflows/enabling-debug-logging#enabling-step-debug-logging`); - path_and_artifact_name_validation_1.checkArtifactName(name); - // Get specification for the files being uploaded - const uploadSpecification = upload_specification_1.getUploadSpecification(name, rootDirectory, files); - const uploadResponse = { - artifactName: name, - artifactItems: [], - size: 0, - failedItems: [] - }; - const uploadHttpClient = new upload_http_client_1.UploadHttpClient(); - if (uploadSpecification.length === 0) { - core.warning(`No files found that can be uploaded`); - } - else { - // Create an entry for the artifact in the file container - const response = yield uploadHttpClient.createArtifactInFileContainer(name, options); - if (!response.fileContainerResourceUrl) { - core.debug(response.toString()); - throw new Error('No URL provided by the Artifact Service to upload an artifact to'); - } - core.debug(`Upload Resource URL: ${response.fileContainerResourceUrl}`); - core.info(`Container for artifact "${name}" successfully created. Starting upload of file(s)`); - // Upload each of the files that were found concurrently - const uploadResult = yield uploadHttpClient.uploadArtifactToFileContainer(response.fileContainerResourceUrl, uploadSpecification, options); - // Update the size of the artifact to indicate we are done uploading - // The uncompressed size is used for display when downloading a zip of the artifact from the UI - core.info(`File upload process has finished. Finalizing the artifact upload`); - yield uploadHttpClient.patchArtifactSize(uploadResult.totalSize, name); - if (uploadResult.failedItems.length > 0) { - core.info(`Upload finished. There were ${uploadResult.failedItems.length} items that failed to upload`); - } - else { - core.info(`Artifact has been finalized. All files have been successfully uploaded!`); - } - core.info(` -The raw size of all the files that were specified for upload is ${uploadResult.totalSize} bytes -The size of all the files that were uploaded is ${uploadResult.uploadSize} bytes. This takes into account any gzip compression used to reduce the upload size, time and storage - -Note: The size of downloaded zips can differ significantly from the reported size. For more information see: https://github.com/actions/upload-artifact#zipped-artifact-downloads \r\n`); - uploadResponse.artifactItems = uploadSpecification.map(item => item.absoluteFilePath); - uploadResponse.size = uploadResult.uploadSize; - uploadResponse.failedItems = uploadResult.failedItems; - } - return uploadResponse; - }); + toDate(message) { + return new Date(runtime_6.PbLong.from(message.seconds).toNumber() * 1000 + Math.ceil(message.nanos / 1000000)); } - downloadArtifact(name, path, options) { - return __awaiter(this, void 0, void 0, function* () { - const downloadHttpClient = new download_http_client_1.DownloadHttpClient(); - const artifacts = yield downloadHttpClient.listArtifacts(); - if (artifacts.count === 0) { - throw new Error(`Unable to find any artifacts for the associated workflow`); - } - const artifactToDownload = artifacts.value.find(artifact => { - return artifact.name === name; - }); - if (!artifactToDownload) { - throw new Error(`Unable to find an artifact with the name: ${name}`); - } - const items = yield downloadHttpClient.getContainerItems(artifactToDownload.name, artifactToDownload.fileContainerResourceUrl); - if (!path) { - path = config_variables_1.getWorkSpaceDirectory(); - } - path = path_1.normalize(path); - path = path_1.resolve(path); - // During upload, empty directories are rejected by the remote server so there should be no artifacts that consist of only empty directories - const downloadSpecification = download_specification_1.getDownloadSpecification(name, items.value, path, (options === null || options === void 0 ? void 0 : options.createArtifactFolder) || false); - if (downloadSpecification.filesToDownload.length === 0) { - core.info(`No downloadable files were found for the artifact: ${artifactToDownload.name}`); - } - else { - // Create all necessary directories recursively before starting any download - yield utils_1.createDirectoriesForArtifact(downloadSpecification.directoryStructure); - core.info('Directory structure has been setup for the artifact'); - yield utils_1.createEmptyFilesForArtifact(downloadSpecification.emptyFilesToCreate); - yield downloadHttpClient.downloadSingleArtifact(downloadSpecification.filesToDownload); - } - return { - artifactName: name, - downloadPath: downloadSpecification.rootDownloadLocation - }; - }); + /** + * 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; } - downloadAllArtifacts(path) { - return __awaiter(this, void 0, void 0, function* () { - const downloadHttpClient = new download_http_client_1.DownloadHttpClient(); - const response = []; - const artifacts = yield downloadHttpClient.listArtifacts(); - if (artifacts.count === 0) { - core.info('Unable to find any artifacts for the associated workflow'); - return response; - } - if (!path) { - path = config_variables_1.getWorkSpaceDirectory(); - } - path = path_1.normalize(path); - path = path_1.resolve(path); - let downloadedArtifacts = 0; - while (downloadedArtifacts < artifacts.count) { - const currentArtifactToDownload = artifacts.value[downloadedArtifacts]; - downloadedArtifacts += 1; - core.info(`starting download of artifact ${currentArtifactToDownload.name} : ${downloadedArtifacts}/${artifacts.count}`); - // Get container entries for the specific artifact - const items = yield downloadHttpClient.getContainerItems(currentArtifactToDownload.name, currentArtifactToDownload.fileContainerResourceUrl); - const downloadSpecification = download_specification_1.getDownloadSpecification(currentArtifactToDownload.name, items.value, path, true); - if (downloadSpecification.filesToDownload.length === 0) { - core.info(`No downloadable files were found for any artifact ${currentArtifactToDownload.name}`); - } - else { - yield utils_1.createDirectoriesForArtifact(downloadSpecification.directoryStructure); - yield utils_1.createEmptyFilesForArtifact(downloadSpecification.emptyFilesToCreate); - yield downloadHttpClient.downloadSingleArtifact(downloadSpecification.filesToDownload); - } - response.push({ - artifactName: currentArtifactToDownload.name, - downloadPath: downloadSpecification.rootDownloadLocation - }); + /** + * 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; + } + 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 response; - }); + } + 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; } } -exports.DefaultArtifactClient = DefaultArtifactClient; -//# sourceMappingURL=artifact-client.js.map +/** + * @generated MessageType for protobuf message google.protobuf.Timestamp + */ +exports.Timestamp = new Timestamp$Type(); +//# sourceMappingURL=timestamp.js.map /***/ }), -/***/ 7289: -/***/ ((__unused_webpack_module, exports) => { +/***/ 8626: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getRetentionDays = exports.getWorkSpaceDirectory = exports.getWorkFlowRunId = exports.getRuntimeUrl = exports.getRuntimeToken = exports.getDownloadFileConcurrency = exports.getInitialRetryIntervalInMilliseconds = exports.getRetryMultiplier = exports.getRetryLimit = exports.getUploadChunkSize = exports.getUploadFileConcurrency = void 0; -// The number of concurrent uploads that happens at the same time -function getUploadFileConcurrency() { - return 2; -} -exports.getUploadFileConcurrency = getUploadFileConcurrency; -// When uploading large files that can't be uploaded with a single http call, this controls -// the chunk size that is used during upload -function getUploadChunkSize() { - return 8 * 1024 * 1024; // 8 MB Chunks -} -exports.getUploadChunkSize = getUploadChunkSize; -// The maximum number of retries that can be attempted before an upload or download fails -function getRetryLimit() { - return 5; -} -exports.getRetryLimit = getRetryLimit; -// With exponential backoff, the larger the retry count, the larger the wait time before another attempt -// The retry multiplier controls by how much the backOff time increases depending on the number of retries -function getRetryMultiplier() { - return 1.5; -} -exports.getRetryMultiplier = getRetryMultiplier; -// The initial wait time if an upload or download fails and a retry is being attempted for the first time -function getInitialRetryIntervalInMilliseconds() { - return 3000; -} -exports.getInitialRetryIntervalInMilliseconds = getInitialRetryIntervalInMilliseconds; -// The number of concurrent downloads that happens at the same time -function getDownloadFileConcurrency() { - return 2; -} -exports.getDownloadFileConcurrency = getDownloadFileConcurrency; -function getRuntimeToken() { - const token = process.env['ACTIONS_RUNTIME_TOKEN']; - if (!token) { - throw new Error('Unable to get ACTIONS_RUNTIME_TOKEN env variable'); +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*/ } + ]); } - return token; -} -exports.getRuntimeToken = getRuntimeToken; -function getRuntimeUrl() { - const runtimeUrl = process.env['ACTIONS_RUNTIME_URL']; - if (!runtimeUrl) { - throw new Error('Unable to get ACTIONS_RUNTIME_URL env variable'); + /** + * Encode `DoubleValue` to JSON number. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.scalar(2, message.value, "value", false, true); } - return runtimeUrl; -} -exports.getRuntimeUrl = getRuntimeUrl; -function getWorkFlowRunId() { - const workFlowRunId = process.env['GITHUB_RUN_ID']; - if (!workFlowRunId) { - throw new Error('Unable to get GITHUB_RUN_ID env variable'); + /** + * 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 workFlowRunId; -} -exports.getWorkFlowRunId = getWorkFlowRunId; -function getWorkSpaceDirectory() { - const workspaceDirectory = process.env['GITHUB_WORKSPACE']; - if (!workspaceDirectory) { - throw new Error('Unable to get GITHUB_WORKSPACE env variable'); + 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); + } + } + 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; } - return workspaceDirectory; -} -exports.getWorkSpaceDirectory = getWorkSpaceDirectory; -function getRetentionDays() { - return process.env['GITHUB_RETENTION_DAYS']; } -exports.getRetentionDays = getRetentionDays; -//# sourceMappingURL=config-variables.js.map - -/***/ }), - -/***/ 8541: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - /** - * CRC64: cyclic redundancy check, 64-bits - * - * In order to validate that artifacts are not being corrupted over the wire, this redundancy check allows us to - * validate that there was no corruption during transmission. The implementation here is based on Go's hash/crc64 pkg, - * but without the slicing-by-8 optimization: https://cs.opensource.google/go/go/+/master:src/hash/crc64/crc64.go - * - * This implementation uses a pregenerated table based on 0x9A6C9329AC4BC9B5 as the polynomial, the same polynomial that - * is used for Azure Storage: https://github.com/Azure/azure-storage-net/blob/cbe605f9faa01bfc3003d75fc5a16b2eaccfe102/Lib/Common/Core/Util/Crc64.cs#L27 + * @generated MessageType for protobuf message google.protobuf.DoubleValue */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -// when transpile target is >= ES2020 (after dropping node 12) these can be changed to bigint literals - ts(2737) -const PREGEN_POLY_TABLE = [ - BigInt('0x0000000000000000'), - BigInt('0x7F6EF0C830358979'), - BigInt('0xFEDDE190606B12F2'), - BigInt('0x81B31158505E9B8B'), - BigInt('0xC962E5739841B68F'), - BigInt('0xB60C15BBA8743FF6'), - BigInt('0x37BF04E3F82AA47D'), - BigInt('0x48D1F42BC81F2D04'), - BigInt('0xA61CECB46814FE75'), - BigInt('0xD9721C7C5821770C'), - BigInt('0x58C10D24087FEC87'), - BigInt('0x27AFFDEC384A65FE'), - BigInt('0x6F7E09C7F05548FA'), - BigInt('0x1010F90FC060C183'), - BigInt('0x91A3E857903E5A08'), - BigInt('0xEECD189FA00BD371'), - BigInt('0x78E0FF3B88BE6F81'), - BigInt('0x078E0FF3B88BE6F8'), - BigInt('0x863D1EABE8D57D73'), - BigInt('0xF953EE63D8E0F40A'), - BigInt('0xB1821A4810FFD90E'), - BigInt('0xCEECEA8020CA5077'), - BigInt('0x4F5FFBD87094CBFC'), - BigInt('0x30310B1040A14285'), - BigInt('0xDEFC138FE0AA91F4'), - BigInt('0xA192E347D09F188D'), - BigInt('0x2021F21F80C18306'), - BigInt('0x5F4F02D7B0F40A7F'), - BigInt('0x179EF6FC78EB277B'), - BigInt('0x68F0063448DEAE02'), - BigInt('0xE943176C18803589'), - BigInt('0x962DE7A428B5BCF0'), - BigInt('0xF1C1FE77117CDF02'), - BigInt('0x8EAF0EBF2149567B'), - BigInt('0x0F1C1FE77117CDF0'), - BigInt('0x7072EF2F41224489'), - BigInt('0x38A31B04893D698D'), - BigInt('0x47CDEBCCB908E0F4'), - BigInt('0xC67EFA94E9567B7F'), - BigInt('0xB9100A5CD963F206'), - BigInt('0x57DD12C379682177'), - BigInt('0x28B3E20B495DA80E'), - BigInt('0xA900F35319033385'), - BigInt('0xD66E039B2936BAFC'), - BigInt('0x9EBFF7B0E12997F8'), - BigInt('0xE1D10778D11C1E81'), - BigInt('0x606216208142850A'), - BigInt('0x1F0CE6E8B1770C73'), - BigInt('0x8921014C99C2B083'), - BigInt('0xF64FF184A9F739FA'), - BigInt('0x77FCE0DCF9A9A271'), - BigInt('0x08921014C99C2B08'), - BigInt('0x4043E43F0183060C'), - BigInt('0x3F2D14F731B68F75'), - BigInt('0xBE9E05AF61E814FE'), - BigInt('0xC1F0F56751DD9D87'), - BigInt('0x2F3DEDF8F1D64EF6'), - BigInt('0x50531D30C1E3C78F'), - BigInt('0xD1E00C6891BD5C04'), - BigInt('0xAE8EFCA0A188D57D'), - BigInt('0xE65F088B6997F879'), - BigInt('0x9931F84359A27100'), - BigInt('0x1882E91B09FCEA8B'), - BigInt('0x67EC19D339C963F2'), - BigInt('0xD75ADABD7A6E2D6F'), - BigInt('0xA8342A754A5BA416'), - BigInt('0x29873B2D1A053F9D'), - BigInt('0x56E9CBE52A30B6E4'), - BigInt('0x1E383FCEE22F9BE0'), - BigInt('0x6156CF06D21A1299'), - BigInt('0xE0E5DE5E82448912'), - BigInt('0x9F8B2E96B271006B'), - BigInt('0x71463609127AD31A'), - BigInt('0x0E28C6C1224F5A63'), - BigInt('0x8F9BD7997211C1E8'), - BigInt('0xF0F5275142244891'), - BigInt('0xB824D37A8A3B6595'), - BigInt('0xC74A23B2BA0EECEC'), - BigInt('0x46F932EAEA507767'), - BigInt('0x3997C222DA65FE1E'), - BigInt('0xAFBA2586F2D042EE'), - BigInt('0xD0D4D54EC2E5CB97'), - BigInt('0x5167C41692BB501C'), - BigInt('0x2E0934DEA28ED965'), - BigInt('0x66D8C0F56A91F461'), - BigInt('0x19B6303D5AA47D18'), - BigInt('0x980521650AFAE693'), - BigInt('0xE76BD1AD3ACF6FEA'), - BigInt('0x09A6C9329AC4BC9B'), - BigInt('0x76C839FAAAF135E2'), - BigInt('0xF77B28A2FAAFAE69'), - BigInt('0x8815D86ACA9A2710'), - BigInt('0xC0C42C4102850A14'), - BigInt('0xBFAADC8932B0836D'), - BigInt('0x3E19CDD162EE18E6'), - BigInt('0x41773D1952DB919F'), - BigInt('0x269B24CA6B12F26D'), - BigInt('0x59F5D4025B277B14'), - BigInt('0xD846C55A0B79E09F'), - BigInt('0xA72835923B4C69E6'), - BigInt('0xEFF9C1B9F35344E2'), - BigInt('0x90973171C366CD9B'), - BigInt('0x1124202993385610'), - BigInt('0x6E4AD0E1A30DDF69'), - BigInt('0x8087C87E03060C18'), - BigInt('0xFFE938B633338561'), - BigInt('0x7E5A29EE636D1EEA'), - BigInt('0x0134D92653589793'), - BigInt('0x49E52D0D9B47BA97'), - BigInt('0x368BDDC5AB7233EE'), - BigInt('0xB738CC9DFB2CA865'), - BigInt('0xC8563C55CB19211C'), - BigInt('0x5E7BDBF1E3AC9DEC'), - BigInt('0x21152B39D3991495'), - BigInt('0xA0A63A6183C78F1E'), - BigInt('0xDFC8CAA9B3F20667'), - BigInt('0x97193E827BED2B63'), - BigInt('0xE877CE4A4BD8A21A'), - BigInt('0x69C4DF121B863991'), - BigInt('0x16AA2FDA2BB3B0E8'), - BigInt('0xF86737458BB86399'), - BigInt('0x8709C78DBB8DEAE0'), - BigInt('0x06BAD6D5EBD3716B'), - BigInt('0x79D4261DDBE6F812'), - BigInt('0x3105D23613F9D516'), - BigInt('0x4E6B22FE23CC5C6F'), - BigInt('0xCFD833A67392C7E4'), - BigInt('0xB0B6C36E43A74E9D'), - BigInt('0x9A6C9329AC4BC9B5'), - BigInt('0xE50263E19C7E40CC'), - BigInt('0x64B172B9CC20DB47'), - BigInt('0x1BDF8271FC15523E'), - BigInt('0x530E765A340A7F3A'), - BigInt('0x2C608692043FF643'), - BigInt('0xADD397CA54616DC8'), - BigInt('0xD2BD67026454E4B1'), - BigInt('0x3C707F9DC45F37C0'), - BigInt('0x431E8F55F46ABEB9'), - BigInt('0xC2AD9E0DA4342532'), - BigInt('0xBDC36EC59401AC4B'), - BigInt('0xF5129AEE5C1E814F'), - BigInt('0x8A7C6A266C2B0836'), - BigInt('0x0BCF7B7E3C7593BD'), - BigInt('0x74A18BB60C401AC4'), - BigInt('0xE28C6C1224F5A634'), - BigInt('0x9DE29CDA14C02F4D'), - BigInt('0x1C518D82449EB4C6'), - BigInt('0x633F7D4A74AB3DBF'), - BigInt('0x2BEE8961BCB410BB'), - BigInt('0x548079A98C8199C2'), - BigInt('0xD53368F1DCDF0249'), - BigInt('0xAA5D9839ECEA8B30'), - BigInt('0x449080A64CE15841'), - BigInt('0x3BFE706E7CD4D138'), - BigInt('0xBA4D61362C8A4AB3'), - BigInt('0xC52391FE1CBFC3CA'), - BigInt('0x8DF265D5D4A0EECE'), - BigInt('0xF29C951DE49567B7'), - BigInt('0x732F8445B4CBFC3C'), - BigInt('0x0C41748D84FE7545'), - BigInt('0x6BAD6D5EBD3716B7'), - BigInt('0x14C39D968D029FCE'), - BigInt('0x95708CCEDD5C0445'), - BigInt('0xEA1E7C06ED698D3C'), - BigInt('0xA2CF882D2576A038'), - BigInt('0xDDA178E515432941'), - BigInt('0x5C1269BD451DB2CA'), - BigInt('0x237C997575283BB3'), - BigInt('0xCDB181EAD523E8C2'), - BigInt('0xB2DF7122E51661BB'), - BigInt('0x336C607AB548FA30'), - BigInt('0x4C0290B2857D7349'), - BigInt('0x04D364994D625E4D'), - BigInt('0x7BBD94517D57D734'), - BigInt('0xFA0E85092D094CBF'), - BigInt('0x856075C11D3CC5C6'), - BigInt('0x134D926535897936'), - BigInt('0x6C2362AD05BCF04F'), - BigInt('0xED9073F555E26BC4'), - BigInt('0x92FE833D65D7E2BD'), - BigInt('0xDA2F7716ADC8CFB9'), - BigInt('0xA54187DE9DFD46C0'), - BigInt('0x24F29686CDA3DD4B'), - BigInt('0x5B9C664EFD965432'), - BigInt('0xB5517ED15D9D8743'), - BigInt('0xCA3F8E196DA80E3A'), - BigInt('0x4B8C9F413DF695B1'), - BigInt('0x34E26F890DC31CC8'), - BigInt('0x7C339BA2C5DC31CC'), - BigInt('0x035D6B6AF5E9B8B5'), - BigInt('0x82EE7A32A5B7233E'), - BigInt('0xFD808AFA9582AA47'), - BigInt('0x4D364994D625E4DA'), - BigInt('0x3258B95CE6106DA3'), - BigInt('0xB3EBA804B64EF628'), - BigInt('0xCC8558CC867B7F51'), - BigInt('0x8454ACE74E645255'), - BigInt('0xFB3A5C2F7E51DB2C'), - BigInt('0x7A894D772E0F40A7'), - BigInt('0x05E7BDBF1E3AC9DE'), - BigInt('0xEB2AA520BE311AAF'), - BigInt('0x944455E88E0493D6'), - BigInt('0x15F744B0DE5A085D'), - BigInt('0x6A99B478EE6F8124'), - BigInt('0x224840532670AC20'), - BigInt('0x5D26B09B16452559'), - BigInt('0xDC95A1C3461BBED2'), - BigInt('0xA3FB510B762E37AB'), - BigInt('0x35D6B6AF5E9B8B5B'), - BigInt('0x4AB846676EAE0222'), - BigInt('0xCB0B573F3EF099A9'), - BigInt('0xB465A7F70EC510D0'), - BigInt('0xFCB453DCC6DA3DD4'), - BigInt('0x83DAA314F6EFB4AD'), - BigInt('0x0269B24CA6B12F26'), - BigInt('0x7D0742849684A65F'), - BigInt('0x93CA5A1B368F752E'), - BigInt('0xECA4AAD306BAFC57'), - BigInt('0x6D17BB8B56E467DC'), - BigInt('0x12794B4366D1EEA5'), - BigInt('0x5AA8BF68AECEC3A1'), - BigInt('0x25C64FA09EFB4AD8'), - BigInt('0xA4755EF8CEA5D153'), - BigInt('0xDB1BAE30FE90582A'), - BigInt('0xBCF7B7E3C7593BD8'), - BigInt('0xC399472BF76CB2A1'), - BigInt('0x422A5673A732292A'), - BigInt('0x3D44A6BB9707A053'), - BigInt('0x759552905F188D57'), - BigInt('0x0AFBA2586F2D042E'), - BigInt('0x8B48B3003F739FA5'), - BigInt('0xF42643C80F4616DC'), - BigInt('0x1AEB5B57AF4DC5AD'), - BigInt('0x6585AB9F9F784CD4'), - BigInt('0xE436BAC7CF26D75F'), - BigInt('0x9B584A0FFF135E26'), - BigInt('0xD389BE24370C7322'), - BigInt('0xACE74EEC0739FA5B'), - BigInt('0x2D545FB4576761D0'), - BigInt('0x523AAF7C6752E8A9'), - BigInt('0xC41748D84FE75459'), - BigInt('0xBB79B8107FD2DD20'), - BigInt('0x3ACAA9482F8C46AB'), - BigInt('0x45A459801FB9CFD2'), - BigInt('0x0D75ADABD7A6E2D6'), - BigInt('0x721B5D63E7936BAF'), - BigInt('0xF3A84C3BB7CDF024'), - BigInt('0x8CC6BCF387F8795D'), - BigInt('0x620BA46C27F3AA2C'), - BigInt('0x1D6554A417C62355'), - BigInt('0x9CD645FC4798B8DE'), - BigInt('0xE3B8B53477AD31A7'), - BigInt('0xAB69411FBFB21CA3'), - BigInt('0xD407B1D78F8795DA'), - BigInt('0x55B4A08FDFD90E51'), - BigInt('0x2ADA5047EFEC8728') -]; -class CRC64 { +exports.DoubleValue = new DoubleValue$Type(); +// @generated message type with reflection information, may provide speed optimized methods +class FloatValue$Type extends runtime_7.MessageType { constructor() { - this._crc = BigInt(0); - } - update(data) { - const buffer = typeof data === 'string' ? Buffer.from(data) : data; - let crc = CRC64.flip64Bits(this._crc); - for (const dataByte of buffer) { - const crcByte = Number(crc & BigInt(0xff)); - crc = PREGEN_POLY_TABLE[crcByte ^ dataByte] ^ (crc >> BigInt(8)); - } - this._crc = CRC64.flip64Bits(crc); - } - digest(encoding) { - switch (encoding) { - case 'hex': - return this._crc.toString(16).toUpperCase(); - case 'base64': - return this.toBuffer().toString('base64'); - default: - return this.toBuffer(); - } + 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; } - toBuffer() { - return Buffer.from([0, 8, 16, 24, 32, 40, 48, 56].map(s => Number((this._crc >> BigInt(s)) & BigInt(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; + } + 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); + } + } + return message; } - static flip64Bits(n) { - return (BigInt(1) << BigInt(64)) - BigInt(1) - n; + 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; } } -exports["default"] = CRC64; -//# sourceMappingURL=crc64.js.map - -/***/ }), - -/***/ 2342: -/***/ (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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DownloadHttpClient = void 0; -const fs = __importStar(__nccwpck_require__(7147)); -const core = __importStar(__nccwpck_require__(7334)); -const zlib = __importStar(__nccwpck_require__(9796)); -const utils_1 = __nccwpck_require__(1337); -const url_1 = __nccwpck_require__(7310); -const status_reporter_1 = __nccwpck_require__(3705); -const perf_hooks_1 = __nccwpck_require__(4074); -const http_manager_1 = __nccwpck_require__(7623); -const config_variables_1 = __nccwpck_require__(7289); -const requestUtils_1 = __nccwpck_require__(1784); -class DownloadHttpClient { +/** + * @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() { - this.downloadHttpManager = new http_manager_1.HttpManager(config_variables_1.getDownloadFileConcurrency(), '@actions/artifact-download'); - // downloads are usually significantly faster than uploads so display status information every second - this.statusReporter = new status_reporter_1.StatusReporter(1000); + super("google.protobuf.Int64Value", [ + { no: 1, name: "value", kind: "scalar", T: 3 /*ScalarType.INT64*/ } + ]); } /** - * Gets a list of all artifacts that are in a specific container + * Encode `Int64Value` to JSON string. */ - listArtifacts() { - return __awaiter(this, void 0, void 0, function* () { - const artifactUrl = utils_1.getArtifactUrl(); - // use the first client from the httpManager, `keep-alive` is not used so the connection will close immediately - const client = this.downloadHttpManager.getClient(0); - const headers = utils_1.getDownloadHeaders('application/json'); - const response = yield requestUtils_1.retryHttpClientRequest('List Artifacts', () => __awaiter(this, void 0, void 0, function* () { return client.get(artifactUrl, headers); })); - const body = yield response.readBody(); - return JSON.parse(body); - }); + internalJsonWrite(message, options) { + return this.refJsonWriter.scalar(runtime_1.ScalarType.INT64, message.value, "value", false, true); } /** - * Fetches a set of container items that describe the contents of an artifact - * @param artifactName the name of the artifact - * @param containerUrl the artifact container URL for the run + * Decode `Int64Value` from JSON string. */ - getContainerItems(artifactName, containerUrl) { - return __awaiter(this, void 0, void 0, function* () { - // the itemPath search parameter controls which containers will be returned - const resourceUrl = new url_1.URL(containerUrl); - resourceUrl.searchParams.append('itemPath', artifactName); - // use the first client from the httpManager, `keep-alive` is not used so the connection will close immediately - const client = this.downloadHttpManager.getClient(0); - const headers = utils_1.getDownloadHeaders('application/json'); - const response = yield requestUtils_1.retryHttpClientRequest('Get Container Items', () => __awaiter(this, void 0, void 0, function* () { return client.get(resourceUrl.toString(), headers); })); - const body = yield response.readBody(); - return JSON.parse(body); - }); + 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*/ } + ]); } /** - * Concurrently downloads all the files that are part of an artifact - * @param downloadItems information about what items to download and where to save them + * Encode `UInt64Value` to JSON string. */ - downloadSingleArtifact(downloadItems) { - return __awaiter(this, void 0, void 0, function* () { - const DOWNLOAD_CONCURRENCY = config_variables_1.getDownloadFileConcurrency(); - // limit the number of files downloaded at a single time - core.debug(`Download file concurrency is set to ${DOWNLOAD_CONCURRENCY}`); - const parallelDownloads = [...new Array(DOWNLOAD_CONCURRENCY).keys()]; - let currentFile = 0; - let downloadedFiles = 0; - core.info(`Total number of files that will be downloaded: ${downloadItems.length}`); - this.statusReporter.setTotalNumberOfFilesToProcess(downloadItems.length); - this.statusReporter.start(); - yield Promise.all(parallelDownloads.map((index) => __awaiter(this, void 0, void 0, function* () { - while (currentFile < downloadItems.length) { - const currentFileToDownload = downloadItems[currentFile]; - currentFile += 1; - const startTime = perf_hooks_1.performance.now(); - yield this.downloadIndividualFile(index, currentFileToDownload.sourceLocation, currentFileToDownload.targetPath); - if (core.isDebug()) { - core.debug(`File: ${++downloadedFiles}/${downloadItems.length}. ${currentFileToDownload.targetPath} took ${(perf_hooks_1.performance.now() - startTime).toFixed(3)} milliseconds to finish downloading`); - } - this.statusReporter.incrementProcessedCount(); - } - }))) - .catch(error => { - throw new Error(`Unable to download the artifact: ${error}`); - }) - .finally(() => { - this.statusReporter.stop(); - // safety dispose all connections - this.downloadHttpManager.disposeAndReplaceAllClients(); - }); - }); + internalJsonWrite(message, options) { + return this.refJsonWriter.scalar(runtime_1.ScalarType.UINT64, message.value, "value", false, true); } /** - * Downloads an individual file - * @param httpClientIndex the index of the http client that is used to make all of the calls - * @param artifactLocation origin location where a file will be downloaded from - * @param downloadPath destination location for the file being downloaded + * Decode `UInt64Value` from JSON string. */ - downloadIndividualFile(httpClientIndex, artifactLocation, downloadPath) { - return __awaiter(this, void 0, void 0, function* () { - let retryCount = 0; - const retryLimit = config_variables_1.getRetryLimit(); - let destinationStream = fs.createWriteStream(downloadPath); - const headers = utils_1.getDownloadHeaders('application/json', true, true); - // a single GET request is used to download a file - const makeDownloadRequest = () => __awaiter(this, void 0, void 0, function* () { - const client = this.downloadHttpManager.getClient(httpClientIndex); - return yield client.get(artifactLocation, headers); - }); - // check the response headers to determine if the file was compressed using gzip - const isGzip = (incomingHeaders) => { - return ('content-encoding' in incomingHeaders && - incomingHeaders['content-encoding'] === 'gzip'); - }; - // Increments the current retry count and then checks if the retry limit has been reached - // If there have been too many retries, fail so the download stops. If there is a retryAfterValue value provided, - // it will be used - const backOff = (retryAfterValue) => __awaiter(this, void 0, void 0, function* () { - retryCount++; - if (retryCount > retryLimit) { - return Promise.reject(new Error(`Retry limit has been reached. Unable to download ${artifactLocation}`)); - } - else { - this.downloadHttpManager.disposeAndReplaceClient(httpClientIndex); - if (retryAfterValue) { - // Back off by waiting the specified time denoted by the retry-after header - core.info(`Backoff due to too many requests, retry #${retryCount}. Waiting for ${retryAfterValue} milliseconds before continuing the download`); - yield utils_1.sleep(retryAfterValue); - } - else { - // Back off using an exponential value that depends on the retry count - const backoffTime = utils_1.getExponentialRetryTimeInMilliseconds(retryCount); - core.info(`Exponential backoff for retry #${retryCount}. Waiting for ${backoffTime} milliseconds before continuing the download`); - yield utils_1.sleep(backoffTime); - } - core.info(`Finished backoff for retry #${retryCount}, continuing with download`); - } - }); - const isAllBytesReceived = (expected, received) => { - // be lenient, if any input is missing, assume success, i.e. not truncated - if (!expected || - !received || - process.env['ACTIONS_ARTIFACT_SKIP_DOWNLOAD_VALIDATION']) { - core.info('Skipping download validation.'); - return true; - } - return parseInt(expected) === received; - }; - const resetDestinationStream = (fileDownloadPath) => __awaiter(this, void 0, void 0, function* () { - destinationStream.close(); - yield utils_1.rmFile(fileDownloadPath); - destinationStream = fs.createWriteStream(fileDownloadPath); - }); - // keep trying to download a file until a retry limit has been reached - while (retryCount <= retryLimit) { - let response; - try { - response = yield makeDownloadRequest(); - } - catch (error) { - // if an error is caught, it is usually indicative of a timeout so retry the download - core.info('An error occurred while attempting to download a file'); - // eslint-disable-next-line no-console - console.log(error); - // increment the retryCount and use exponential backoff to wait before making the next request - yield backOff(); - continue; - } - let forceRetry = false; - if (utils_1.isSuccessStatusCode(response.message.statusCode)) { - // The body contains the contents of the file however calling response.readBody() causes all the content to be converted to a string - // which can cause some gzip encoded data to be lost - // Instead of using response.readBody(), response.message is a readableStream that can be directly used to get the raw body contents - try { - const isGzipped = isGzip(response.message.headers); - yield this.pipeResponseToFile(response, destinationStream, isGzipped); - if (isGzipped || - isAllBytesReceived(response.message.headers['content-length'], yield utils_1.getFileSize(downloadPath))) { - return; - } - else { - forceRetry = true; - } - } - catch (error) { - // retry on error, most likely streams were corrupted - forceRetry = true; - } - } - if (forceRetry || utils_1.isRetryableStatusCode(response.message.statusCode)) { - core.info(`A ${response.message.statusCode} response code has been received while attempting to download an artifact`); - resetDestinationStream(downloadPath); - // if a throttled status code is received, try to get the retryAfter header value, else differ to standard exponential backoff - utils_1.isThrottledStatusCode(response.message.statusCode) - ? yield backOff(utils_1.tryGetRetryAfterValueTimeInMilliseconds(response.message.headers)) - : yield backOff(); - } - else { - // Some unexpected response code, fail immediately and stop the download - utils_1.displayHttpDiagnostics(response); - return Promise.reject(new Error(`Unexpected http ${response.message.statusCode} during download for ${artifactLocation}`)); - } + 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; + } +} +/** + * @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*/ } + ]); } /** - * Pipes the response from downloading an individual file to the appropriate destination stream while decoding gzip content if necessary - * @param response the http response received when downloading a file - * @param destinationStream the stream where the file should be written to - * @param isGzip a boolean denoting if the content is compressed using gzip and if we need to decode it + * Encode `Int32Value` to JSON string. */ - pipeResponseToFile(response, destinationStream, isGzip) { - return __awaiter(this, void 0, void 0, function* () { - yield new Promise((resolve, reject) => { - if (isGzip) { - const gunzip = zlib.createGunzip(); - response.message - .on('error', error => { - core.error(`An error occurred while attempting to read the response stream`); - gunzip.close(); - destinationStream.close(); - reject(error); - }) - .pipe(gunzip) - .on('error', error => { - core.error(`An error occurred while attempting to decompress the response stream`); - destinationStream.close(); - reject(error); - }) - .pipe(destinationStream) - .on('close', () => { - resolve(); - }) - .on('error', error => { - core.error(`An error occurred while writing a downloaded file to ${destinationStream.path}`); - reject(error); - }); - } - else { - response.message - .on('error', error => { - core.error(`An error occurred while attempting to read the response stream`); - destinationStream.close(); - reject(error); - }) - .pipe(destinationStream) - .on('close', () => { - resolve(); - }) - .on('error', error => { - core.error(`An error occurred while writing a downloaded file to ${destinationStream.path}`); - reject(error); - }); - } - }); - return; - }); + internalJsonWrite(message, options) { + return this.refJsonWriter.scalar(5, message.value, "value", false, true); } -} -exports.DownloadHttpClient = DownloadHttpClient; -//# sourceMappingURL=download-http-client.js.map - -/***/ }), - -/***/ 1087: -/***/ (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.getDownloadSpecification = void 0; -const path = __importStar(__nccwpck_require__(1017)); -/** - * Creates a specification for a set of files that will be downloaded - * @param artifactName the name of the artifact - * @param artifactEntries a set of container entries that describe that files that make up an artifact - * @param downloadPath the path where the artifact will be downloaded to - * @param includeRootDirectory specifies if there should be an extra directory (denoted by the artifact name) where the artifact files should be downloaded to - */ -function getDownloadSpecification(artifactName, artifactEntries, downloadPath, includeRootDirectory) { - // use a set for the directory paths so that there are no duplicates - const directories = new Set(); - const specifications = { - rootDownloadLocation: includeRootDirectory - ? path.join(downloadPath, artifactName) - : downloadPath, - directoryStructure: [], - emptyFilesToCreate: [], - filesToDownload: [] - }; - for (const entry of artifactEntries) { - // Ignore artifacts in the container that don't begin with the same name - if (entry.path.startsWith(`${artifactName}/`) || - entry.path.startsWith(`${artifactName}\\`)) { - // normalize all separators to the local OS - const normalizedPathEntry = path.normalize(entry.path); - // entry.path always starts with the artifact name, if includeRootDirectory is false, remove the name from the beginning of the path - const filePath = path.join(downloadPath, includeRootDirectory - ? normalizedPathEntry - : normalizedPathEntry.replace(artifactName, '')); - // Case insensitive folder structure maintained in the backend, not every folder is created so the 'folder' - // itemType cannot be relied upon. The file must be used to determine the directory structure - if (entry.itemType === 'file') { - // Get the directories that we need to create from the filePath for each individual file - directories.add(path.dirname(filePath)); - if (entry.fileLength === 0) { - // An empty file was uploaded, create the empty files locally so that no extra http calls are made - specifications.emptyFilesToCreate.push(filePath); - } - else { - specifications.filesToDownload.push({ - sourceLocation: entry.contentLocation, - targetPath: filePath - }); - } + /** + * 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; } - specifications.directoryStructure = Array.from(directories); - return specifications; } -exports.getDownloadSpecification = getDownloadSpecification; -//# sourceMappingURL=download-specification.js.map - -/***/ }), - -/***/ 7623: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.HttpManager = void 0; -const utils_1 = __nccwpck_require__(1337); /** - * Used for managing http clients during either upload or download + * @generated MessageType for protobuf message google.protobuf.Int32Value */ -class HttpManager { - constructor(clientCount, userAgent) { - if (clientCount < 1) { - throw new Error('There must be at least one client'); - } - this.userAgent = userAgent; - this.clients = new Array(clientCount).fill(utils_1.createHttpClient(userAgent)); +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*/ } + ]); } - getClient(index) { - return this.clients[index]; + /** + * Encode `UInt32Value` to JSON string. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.scalar(13, message.value, "value", false, true); } - // client disposal is necessary if a keep-alive connection is used to properly close the connection - // for more information see: https://github.com/actions/http-client/blob/04e5ad73cd3fd1f5610a32116b0759eddf6570d2/index.ts#L292 - disposeAndReplaceClient(index) { - this.clients[index].dispose(); - this.clients[index] = utils_1.createHttpClient(this.userAgent); + /** + * 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; } - disposeAndReplaceAllClients() { - for (const [index] of this.clients.entries()) { - this.disposeAndReplaceClient(index); + 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); + } } + 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; } } -exports.HttpManager = HttpManager; -//# sourceMappingURL=http-manager.js.map - -/***/ }), - -/***/ 1611: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.checkArtifactFilePath = exports.checkArtifactName = void 0; -const core_1 = __nccwpck_require__(7334); /** - * 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 + * @generated MessageType for protobuf message google.protobuf.UInt32Value */ -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 /'] -]); +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); + } + } + 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; + } +} /** - * Scans the name of the artifact to make sure there are no illegal characters + * @generated MessageType for protobuf message google.protobuf.BoolValue */ -function checkArtifactName(name) { - if (!name) { - throw new Error(`Artifact name: ${name}, is incorrectly provided`); +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*/ } + ]); } - for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactNameCharacters) { - if (name.includes(invalidCharacterKey)) { - throw new Error(`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.`); + /** + * 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; } - core_1.info(`Artifact name is valid!`); } -exports.checkArtifactName = checkArtifactName; /** - * Scans the name of the filePath used to make sure there are no illegal characters + * @generated MessageType for protobuf message google.protobuf.StringValue */ -function checkArtifactFilePath(path) { - if (!path) { - throw new Error(`Artifact path: ${path}, is incorrectly provided`); +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*/ } + ]); } - for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactFilePathCharacters) { - if (path.includes(invalidCharacterKey)) { - throw new Error(`Artifact path 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. - `); + /** + * 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; } } -exports.checkArtifactFilePath = checkArtifactFilePath; -//# sourceMappingURL=path-and-artifact-name-validation.js.map +/** + * @generated MessageType for protobuf message google.protobuf.BytesValue + */ +exports.BytesValue = new BytesValue$Type(); +//# sourceMappingURL=wrappers.js.map /***/ }), -/***/ 1784: +/***/ 49960: /***/ (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]; } }); + 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.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 __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 })); -exports.retryHttpClientRequest = exports.retry = void 0; -const utils_1 = __nccwpck_require__(1337); -const core = __importStar(__nccwpck_require__(7334)); -const config_variables_1 = __nccwpck_require__(7289); -function retry(name, operation, customErrorMessages, maxAttempts) { - return __awaiter(this, void 0, void 0, function* () { - let response = undefined; - let statusCode = undefined; - let isRetryable = false; - let errorMessage = ''; - let customErrorInformation = undefined; - let attempt = 1; - while (attempt <= maxAttempts) { - try { - response = yield operation(); - statusCode = response.message.statusCode; - if (utils_1.isSuccessStatusCode(statusCode)) { - return response; - } - // Extra error information that we want to display if a particular response code is hit - if (statusCode) { - customErrorInformation = customErrorMessages.get(statusCode); - } - isRetryable = utils_1.isRetryableStatusCode(statusCode); - errorMessage = `Artifact service responded with ${statusCode}`; - } - catch (error) { - isRetryable = true; - errorMessage = error.message; - } - if (!isRetryable) { - core.info(`${name} - Error is not retryable`); - if (response) { - utils_1.displayHttpDiagnostics(response); - } - break; - } - core.info(`${name} - Attempt ${attempt} of ${maxAttempts} failed with error: ${errorMessage}`); - yield utils_1.sleep(utils_1.getExponentialRetryTimeInMilliseconds(attempt)); - attempt++; - } - if (response) { - utils_1.displayHttpDiagnostics(response); - } - if (customErrorInformation) { - throw Error(`${name} failed: ${customErrorInformation}`); - } - throw Error(`${name} failed: ${errorMessage}`); - }); -} -exports.retry = retry; -function retryHttpClientRequest(name, method, customErrorMessages = new Map(), maxAttempts = config_variables_1.getRetryLimit()) { - return __awaiter(this, void 0, void 0, function* () { - return yield retry(name, method, customErrorMessages, maxAttempts); - }); -} -exports.retryHttpClientRequest = retryHttpClientRequest; -//# sourceMappingURL=requestUtils.js.map +__exportStar(__nccwpck_require__(54622), exports); +__exportStar(__nccwpck_require__(8626), exports); +__exportStar(__nccwpck_require__(58178), exports); +__exportStar(__nccwpck_require__(63077), exports); +//# sourceMappingURL=index.js.map /***/ }), -/***/ 3705: +/***/ 58178: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.StatusReporter = void 0; -const core_1 = __nccwpck_require__(7334); +exports.ArtifactService = exports.DeleteArtifactResponse = exports.DeleteArtifactRequest = 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*/ } + ]); + } + 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); + } + } + 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; + } +} /** - * Status Reporter that displays information about the progress/status of an artifact that is being uploaded or downloaded - * - * Variable display time that can be adjusted using the displayFrequencyInMilliseconds variable - * The total status of the upload/download gets displayed according to this value - * If there is a large file that is being uploaded, extra information about the individual status can also be displayed using the updateLargeFileStatus function + * @generated MessageType for protobuf message github.actions.results.api.v1.CreateArtifactRequest */ -class StatusReporter { - constructor(displayFrequencyInMilliseconds) { - this.totalNumberOfFilesToProcess = 0; - this.processedCount = 0; - this.largeFiles = new Map(); - this.totalFileStatus = undefined; - this.displayFrequencyInMilliseconds = displayFrequencyInMilliseconds; - } - setTotalNumberOfFilesToProcess(fileTotal) { - this.totalNumberOfFilesToProcess = fileTotal; - this.processedCount = 0; - } - start() { - // displays information about the total upload/download status - this.totalFileStatus = setInterval(() => { - // display 1 decimal place without any rounding - const percentage = this.formatPercentage(this.processedCount, this.totalNumberOfFilesToProcess); - core_1.info(`Total file count: ${this.totalNumberOfFilesToProcess} ---- Processed file #${this.processedCount} (${percentage.slice(0, percentage.indexOf('.') + 2)}%)`); - }, this.displayFrequencyInMilliseconds); - } - // if there is a large file that is being uploaded in chunks, this is used to display extra information about the status of the upload - updateLargeFileStatus(fileName, chunkStartIndex, chunkEndIndex, totalUploadFileSize) { - // display 1 decimal place without any rounding - const percentage = this.formatPercentage(chunkEndIndex, totalUploadFileSize); - core_1.info(`Uploaded ${fileName} (${percentage.slice(0, percentage.indexOf('.') + 2)}%) bytes ${chunkStartIndex}:${chunkEndIndex}`); - } - stop() { - if (this.totalFileStatus) { - clearInterval(this.totalFileStatus); +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); + } } + return message; } - incrementProcessedCount() { - this.processedCount++; - } - formatPercentage(numerator, denominator) { - // toFixed() rounds, so use extra precision to display accurate information even though 4 decimal places are not displayed - return ((numerator / denominator) * 100).toFixed(4).toString(); + 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; } } -exports.StatusReporter = StatusReporter; -//# sourceMappingURL=status-reporter.js.map - -/***/ }), - -/***/ 9110: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - +/** + * @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); + } + } + 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; + } +} +/** + * @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*/ } + ]); + } + 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); + } + } + return message; + } + 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; + } +} +/** + * @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 } + ]); + } + 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; + } + 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; + } +} +/** + * @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; + } + 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; + } +} +/** + * @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; + } + 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; + } +} +/** + * @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; + } + 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; + } +} +/** + * @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*/ } + ]); + } + 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; + } + 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; + } + 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 message type with reflection information, may provide speed optimized methods +class DeleteArtifactRequest$Type extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.DeleteArtifactRequest", [ + { 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; + } + 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; + } +} +/** + * @generated MessageType for protobuf message github.actions.results.api.v1.DeleteArtifactRequest + */ +exports.DeleteArtifactRequest = new DeleteArtifactRequest$Type(); +// @generated message type with reflection information, may provide speed optimized methods +class DeleteArtifactResponse$Type extends runtime_5.MessageType { + constructor() { + super("github.actions.results.api.v1.DeleteArtifactResponse", [ + { no: 1, name: "ok", kind: "scalar", T: 8 /*ScalarType.BOOL*/ }, + { no: 2, name: "artifact_id", kind: "scalar", T: 3 /*ScalarType.INT64*/ } + ]); + } + 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); + } + } + return message; + } + 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; + } +} +/** + * @generated MessageType for protobuf message github.actions.results.api.v1.DeleteArtifactResponse + */ +exports.DeleteArtifactResponse = new DeleteArtifactResponse$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 }, + { name: "DeleteArtifact", options: {}, I: exports.DeleteArtifactRequest, O: exports.DeleteArtifactResponse } +]); +//# sourceMappingURL=artifact.js.map + +/***/ }), + +/***/ 63077: +/***/ (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) { @@ -1267,125 +1543,512 @@ 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); } -}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createGZipFileInBuffer = exports.createGZipFileOnDisk = void 0; -const fs = __importStar(__nccwpck_require__(7147)); -const zlib = __importStar(__nccwpck_require__(9796)); -const util_1 = __nccwpck_require__(3837); -const stat = util_1.promisify(fs.stat); -/** - * GZipping certain files that are already compressed will likely not yield further size reductions. Creating large temporary gzip - * files then will just waste a lot of time before ultimately being discarded (especially for very large files). - * If any of these types of files are encountered then on-disk gzip creation will be skipped and the original file will be uploaded as-is - */ -const gzipExemptFileExtensions = [ - '.gzip', - '.zip', - '.tar.lz', - '.tar.gz', - '.tar.bz2', - '.7z' +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); + this.DeleteArtifact.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, + })); + } + DeleteArtifact(request) { + const data = artifact_1.DeleteArtifactRequest.toJson(request, { + useProtoFieldName: true, + emitDefaultValues: false, + }); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "DeleteArtifact", "application/json", data); + return promise.then((data) => artifact_1.DeleteArtifactResponse.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); + this.DeleteArtifact.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)); + } + DeleteArtifact(request) { + const data = artifact_1.DeleteArtifactRequest.toBinary(request); + const promise = this.rpc.request("github.actions.results.api.v1.ArtifactService", "DeleteArtifact", "application/protobuf", data); + return promise.then((data) => artifact_1.DeleteArtifactResponse.fromBinary(data)); + } +} +exports.ArtifactServiceClientProtobuf = ArtifactServiceClientProtobuf; +var ArtifactServiceMethod; +(function (ArtifactServiceMethod) { + ArtifactServiceMethod["CreateArtifact"] = "CreateArtifact"; + ArtifactServiceMethod["FinalizeArtifact"] = "FinalizeArtifact"; + ArtifactServiceMethod["ListArtifacts"] = "ListArtifacts"; + ArtifactServiceMethod["GetSignedArtifactURL"] = "GetSignedArtifactURL"; + ArtifactServiceMethod["DeleteArtifact"] = "DeleteArtifact"; +})(ArtifactServiceMethod || (exports.ArtifactServiceMethod = ArtifactServiceMethod = {})); +exports.ArtifactServiceMethodList = [ + ArtifactServiceMethod.CreateArtifact, + ArtifactServiceMethod.FinalizeArtifact, + ArtifactServiceMethod.ListArtifacts, + ArtifactServiceMethod.GetSignedArtifactURL, + ArtifactServiceMethod.DeleteArtifact, ]; -/** - * Creates a Gzip compressed file of an original file at the provided temporary filepath location - * @param {string} originalFilePath filepath of whatever will be compressed. The original file will be unmodified - * @param {string} tempFilePath the location of where the Gzip file will be created - * @returns the size of gzip file that gets created - */ -function createGZipFileOnDisk(originalFilePath, tempFilePath) { +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); + }); + case "DeleteArtifact": + return (ctx, service, data, interceptors) => __awaiter(this, void 0, void 0, function* () { + ctx = Object.assign(Object.assign({}, ctx), { methodName: "DeleteArtifact" }); + yield events.onMatch(ctx); + return handleArtifactServiceDeleteArtifactRequest(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); + } +} +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); + } +} +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); + } +} +function handleArtifactServiceDeleteArtifactRequest(ctx, service, data, interceptors) { + switch (ctx.contentType) { + case twirp_ts_1.TwirpContentType.JSON: + return handleArtifactServiceDeleteArtifactJSON(ctx, service, data, interceptors); + case twirp_ts_1.TwirpContentType.Protobuf: + return handleArtifactServiceDeleteArtifactProtobuf(ctx, service, data, interceptors); + default: + const msg = "unexpected Content-Type"; + throw new twirp_ts_1.TwirpError(twirp_ts_1.TwirpErrorCode.BadRoute, msg); + } +} +function handleArtifactServiceCreateArtifactJSON(ctx, service, data, interceptors) { return __awaiter(this, void 0, void 0, function* () { - for (const gzipExemptExtension of gzipExemptFileExtensions) { - if (originalFilePath.endsWith(gzipExemptExtension)) { - // return a really large number so that the original file gets uploaded - return Number.MAX_SAFE_INTEGER; + 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); } } - return new Promise((resolve, reject) => { - const inputStream = fs.createReadStream(originalFilePath); - const gzip = zlib.createGzip(); - const outputStream = fs.createWriteStream(tempFilePath); - inputStream.pipe(gzip).pipe(outputStream); - outputStream.on('finish', () => __awaiter(this, void 0, void 0, function* () { - // wait for stream to finish before calculating the size which is needed as part of the Content-Length header when starting an upload - const size = (yield stat(tempFilePath)).size; - resolve(size); - })); - outputStream.on('error', error => { - // eslint-disable-next-line no-console - console.log(error); - reject; + 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, + })); }); } -exports.createGZipFileOnDisk = createGZipFileOnDisk; -/** - * Creates a GZip file in memory using a buffer. Should be used for smaller files to reduce disk I/O - * @param originalFilePath the path to the original file that is being GZipped - * @returns a buffer with the GZip file - */ -function createGZipFileInBuffer(originalFilePath) { +function handleArtifactServiceFinalizeArtifactJSON(ctx, service, data, interceptors) { return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { - var e_1, _a; - const inputStream = fs.createReadStream(originalFilePath); - const gzip = zlib.createGzip(); - inputStream.pipe(gzip); - // read stream into buffer, using experimental async iterators see https://github.com/nodejs/readable-stream/issues/403#issuecomment-479069043 - const chunks = []; - try { - for (var gzip_1 = __asyncValues(gzip), gzip_1_1; gzip_1_1 = yield gzip_1.next(), !gzip_1_1.done;) { - const chunk = gzip_1_1.value; - chunks.push(chunk); - } + 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); } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (gzip_1_1 && !gzip_1_1.done && (_a = gzip_1.return)) yield _a.call(gzip_1); - } - finally { if (e_1) throw e_1.error; } + } + 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 handleArtifactServiceDeleteArtifactJSON(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.DeleteArtifactRequest.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); } - resolve(Buffer.concat(chunks)); + } + if (interceptors && interceptors.length > 0) { + const interceptor = (0, twirp_ts_1.chainInterceptors)(...interceptors); + response = yield interceptor(ctx, request, (ctx, inputReq) => { + return service.DeleteArtifact(ctx, inputReq); + }); + } + else { + response = yield service.DeleteArtifact(ctx, request); + } + return JSON.stringify(artifact_1.DeleteArtifactResponse.toJson(response, { + useProtoFieldName: true, + emitDefaultValues: false, })); }); } -exports.createGZipFileInBuffer = createGZipFileInBuffer; -//# sourceMappingURL=upload-gzip.js.map +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); + }); + } + else { + response = yield service.GetSignedArtifactURL(ctx, request); + } + return Buffer.from(artifact_1.GetSignedArtifactURLResponse.toBinary(response)); + }); +} +function handleArtifactServiceDeleteArtifactProtobuf(ctx, service, data, interceptors) { + return __awaiter(this, void 0, void 0, function* () { + let request; + let response; + try { + request = artifact_1.DeleteArtifactRequest.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.DeleteArtifact(ctx, inputReq); + }); + } + else { + response = yield service.DeleteArtifact(ctx, request); + } + return Buffer.from(artifact_1.DeleteArtifactResponse.toBinary(response)); + }); +} +//# sourceMappingURL=artifact.twirp.js.map /***/ }), -/***/ 9482: +/***/ 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; - 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) { @@ -1395,397 +2058,245 @@ 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.UploadHttpClient = void 0; -const fs = __importStar(__nccwpck_require__(7147)); -const core = __importStar(__nccwpck_require__(7334)); -const tmp = __importStar(__nccwpck_require__(4988)); -const stream = __importStar(__nccwpck_require__(2781)); -const utils_1 = __nccwpck_require__(1337); -const config_variables_1 = __nccwpck_require__(7289); -const util_1 = __nccwpck_require__(3837); -const url_1 = __nccwpck_require__(7310); -const perf_hooks_1 = __nccwpck_require__(4074); -const status_reporter_1 = __nccwpck_require__(3705); -const http_client_1 = __nccwpck_require__(7820); -const http_manager_1 = __nccwpck_require__(7623); -const upload_gzip_1 = __nccwpck_require__(9110); -const requestUtils_1 = __nccwpck_require__(1784); -const stat = util_1.promisify(fs.stat); -class UploadHttpClient { - constructor() { - this.uploadHttpManager = new http_manager_1.HttpManager(config_variables_1.getUploadFileConcurrency(), '@actions/artifact-upload'); - this.statusReporter = new status_reporter_1.StatusReporter(10000); - } - /** - * Creates a file container for the new artifact in the remote blob storage/file service - * @param {string} artifactName Name of the artifact being created - * @returns The response from the Artifact Service if the file container was successfully created - */ - createArtifactInFileContainer(artifactName, options) { +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 delete_artifact_1 = __nccwpck_require__(70071); +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* () { - const parameters = { - Type: 'actions_storage', - Name: artifactName - }; - // calculate retention period - if (options && options.retentionDays) { - const maxRetentionStr = config_variables_1.getRetentionDays(); - parameters.RetentionDays = utils_1.getProperRetention(options.retentionDays, maxRetentionStr); - } - const data = JSON.stringify(parameters, null, 2); - const artifactUrl = utils_1.getArtifactUrl(); - // use the first client from the httpManager, `keep-alive` is not used so the connection will close immediately - const client = this.uploadHttpManager.getClient(0); - const headers = utils_1.getUploadHeaders('application/json', false); - // Extra information to display when a particular HTTP code is returned - // If a 403 is returned when trying to create a file container, the customer has exceeded - // their storage quota so no new artifact containers can be created - const customErrorMessages = new Map([ - [ - http_client_1.HttpCodes.Forbidden, - 'Artifact storage quota has been hit. Unable to upload any new artifacts' - ], - [ - http_client_1.HttpCodes.BadRequest, - `The artifact name ${artifactName} is not valid. Request URL ${artifactUrl}` - ] - ]); - const response = yield requestUtils_1.retryHttpClientRequest('Create Artifact Container', () => __awaiter(this, void 0, void 0, function* () { return client.post(artifactUrl, data, headers); }), customErrorMessages); - const body = yield response.readBody(); - return JSON.parse(body); + 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; + } }); } - /** - * Concurrently upload all of the files in chunks - * @param {string} uploadUrl Base Url for the artifact that was created - * @param {SearchResult[]} filesToUpload A list of information about the files being uploaded - * @returns The size of all the files uploaded in bytes - */ - uploadArtifactToFileContainer(uploadUrl, filesToUpload, options) { + downloadArtifact(artifactId, options) { return __awaiter(this, void 0, void 0, function* () { - const FILE_CONCURRENCY = config_variables_1.getUploadFileConcurrency(); - const MAX_CHUNK_SIZE = config_variables_1.getUploadChunkSize(); - core.debug(`File Concurrency: ${FILE_CONCURRENCY}, and Chunk Size: ${MAX_CHUNK_SIZE}`); - const parameters = []; - // by default, file uploads will continue if there is an error unless specified differently in the options - let continueOnError = true; - if (options) { - if (options.continueOnError === false) { - continueOnError = false; - } - } - // prepare the necessary parameters to upload all the files - for (const file of filesToUpload) { - const resourceUrl = new url_1.URL(uploadUrl); - resourceUrl.searchParams.append('itemPath', file.uploadFilePath); - parameters.push({ - file: file.absoluteFilePath, - resourceUrl: resourceUrl.toString(), - maxChunkSize: MAX_CHUNK_SIZE, - continueOnError - }); - } - const parallelUploads = [...new Array(FILE_CONCURRENCY).keys()]; - const failedItemsToReport = []; - let currentFile = 0; - let completedFiles = 0; - let uploadFileSize = 0; - let totalFileSize = 0; - let abortPendingFileUploads = false; - this.statusReporter.setTotalNumberOfFilesToProcess(filesToUpload.length); - this.statusReporter.start(); - // only allow a certain amount of files to be uploaded at once, this is done to reduce potential errors - yield Promise.all(parallelUploads.map((index) => __awaiter(this, void 0, void 0, function* () { - while (currentFile < filesToUpload.length) { - const currentFileParameters = parameters[currentFile]; - currentFile += 1; - if (abortPendingFileUploads) { - failedItemsToReport.push(currentFileParameters.file); - continue; - } - const startTime = perf_hooks_1.performance.now(); - const uploadFileResult = yield this.uploadFileAsync(index, currentFileParameters); - if (core.isDebug()) { - core.debug(`File: ${++completedFiles}/${filesToUpload.length}. ${currentFileParameters.file} took ${(perf_hooks_1.performance.now() - startTime).toFixed(3)} milliseconds to finish upload`); - } - uploadFileSize += uploadFileResult.successfulUploadSize; - totalFileSize += uploadFileResult.totalSize; - if (uploadFileResult.isSuccess === false) { - failedItemsToReport.push(currentFileParameters.file); - if (!continueOnError) { - // fail fast - core.error(`aborting artifact upload`); - abortPendingFileUploads = true; - } - } - this.statusReporter.incrementProcessedCount(); + try { + if ((0, config_1.isGhes)()) { + throw new errors_1.GHESNotSupportedError(); } - }))); - this.statusReporter.stop(); - // done uploading, safety dispose all connections - this.uploadHttpManager.disposeAndReplaceAllClients(); - core.info(`Total size of all the files uploaded is ${uploadFileSize} bytes`); - return { - uploadSize: uploadFileSize, - totalSize: totalFileSize, - failedItems: failedItemsToReport - }; + 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; + } }); } - /** - * Asynchronously uploads a file. The file is compressed and uploaded using GZip if it is determined to save space. - * If the upload file is bigger than the max chunk size it will be uploaded via multiple calls - * @param {number} httpClientIndex The index of the httpClient that is being used to make all of the calls - * @param {UploadFileParameters} parameters Information about the file that needs to be uploaded - * @returns The size of the file that was uploaded in bytes along with any failed uploads - */ - uploadFileAsync(httpClientIndex, parameters) { + listArtifacts(options) { return __awaiter(this, void 0, void 0, function* () { - const fileStat = yield stat(parameters.file); - const totalFileSize = fileStat.size; - const isFIFO = fileStat.isFIFO(); - let offset = 0; - let isUploadSuccessful = true; - let failedChunkSizes = 0; - let uploadFileSize = 0; - let isGzip = true; - // the file that is being uploaded is less than 64k in size to increase throughput and to minimize disk I/O - // for creating a new GZip file, an in-memory buffer is used for compression - // with named pipes the file size is reported as zero in that case don't read the file in memory - if (!isFIFO && totalFileSize < 65536) { - core.debug(`${parameters.file} is less than 64k in size. Creating a gzip file in-memory to potentially reduce the upload size`); - const buffer = yield upload_gzip_1.createGZipFileInBuffer(parameters.file); - // An open stream is needed in the event of a failure and we need to retry. If a NodeJS.ReadableStream is directly passed in, - // it will not properly get reset to the start of the stream if a chunk upload needs to be retried - let openUploadStream; - if (totalFileSize < buffer.byteLength) { - // compression did not help with reducing the size, use a readable stream from the original file for upload - core.debug(`The gzip file created for ${parameters.file} did not help with reducing the size of the file. The original file will be uploaded as-is`); - openUploadStream = () => fs.createReadStream(parameters.file); - isGzip = false; - uploadFileSize = totalFileSize; - } - else { - // create a readable stream using a PassThrough stream that is both readable and writable - core.debug(`A gzip file created for ${parameters.file} helped with reducing the size of the original file. The file will be uploaded using gzip.`); - openUploadStream = () => { - const passThrough = new stream.PassThrough(); - passThrough.end(buffer); - return passThrough; - }; - uploadFileSize = buffer.byteLength; + try { + if ((0, config_1.isGhes)()) { + throw new errors_1.GHESNotSupportedError(); } - const result = yield this.uploadChunk(httpClientIndex, parameters.resourceUrl, openUploadStream, 0, uploadFileSize - 1, uploadFileSize, isGzip, totalFileSize); - if (!result) { - // chunk failed to upload - isUploadSuccessful = false; - failedChunkSizes += uploadFileSize; - core.warning(`Aborting upload for ${parameters.file} due to failure`); + 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 { - isSuccess: isUploadSuccessful, - successfulUploadSize: uploadFileSize - failedChunkSizes, - totalSize: totalFileSize - }; + return (0, list_artifacts_1.listArtifactsInternal)(options === null || options === void 0 ? void 0 : options.latest); } - else { - // the file that is being uploaded is greater than 64k in size, a temporary file gets created on disk using the - // npm tmp-promise package and this file gets used to create a GZipped file - const tempFile = yield tmp.file(); - core.debug(`${parameters.file} is greater than 64k in size. Creating a gzip file on-disk ${tempFile.path} to potentially reduce the upload size`); - // create a GZip file of the original file being uploaded, the original file should not be modified in any way - uploadFileSize = yield upload_gzip_1.createGZipFileOnDisk(parameters.file, tempFile.path); - let uploadFilePath = tempFile.path; - // compression did not help with size reduction, use the original file for upload and delete the temp GZip file - // for named pipes totalFileSize is zero, this assumes compression did help - if (!isFIFO && totalFileSize < uploadFileSize) { - core.debug(`The gzip file created for ${parameters.file} did not help with reducing the size of the file. The original file will be uploaded as-is`); - uploadFileSize = totalFileSize; - uploadFilePath = parameters.file; - isGzip = false; - } - else { - core.debug(`The gzip file created for ${parameters.file} is smaller than the original file. The file will be uploaded using gzip.`); - } - let abortFileUpload = false; - // upload only a single chunk at a time - while (offset < uploadFileSize) { - const chunkSize = Math.min(uploadFileSize - offset, parameters.maxChunkSize); - const startChunkIndex = offset; - const endChunkIndex = offset + chunkSize - 1; - offset += parameters.maxChunkSize; - if (abortFileUpload) { - // if we don't want to continue in the event of an error, any pending upload chunks will be marked as failed - failedChunkSizes += chunkSize; - continue; - } - const result = yield this.uploadChunk(httpClientIndex, parameters.resourceUrl, () => fs.createReadStream(uploadFilePath, { - start: startChunkIndex, - end: endChunkIndex, - autoClose: false - }), startChunkIndex, endChunkIndex, uploadFileSize, isGzip, totalFileSize); - if (!result) { - // Chunk failed to upload, report as failed and do not continue uploading any more chunks for the file. It is possible that part of a chunk was - // successfully uploaded so the server may report a different size for what was uploaded - isUploadSuccessful = false; - failedChunkSizes += chunkSize; - core.warning(`Aborting upload for ${parameters.file} due to failure`); - abortFileUpload = true; - } - else { - // if an individual file is greater than 8MB (1024*1024*8) in size, display extra information about the upload status - if (uploadFileSize > 8388608) { - this.statusReporter.updateLargeFileStatus(parameters.file, startChunkIndex, endChunkIndex, uploadFileSize); - } - } - } - // Delete the temporary file that was created as part of the upload. If the temp file does not get manually deleted by - // calling cleanup, it gets removed when the node process exits. For more info see: https://www.npmjs.com/package/tmp-promise#about - core.debug(`deleting temporary gzip file ${tempFile.path}`); - yield tempFile.cleanup(); - return { - isSuccess: isUploadSuccessful, - successfulUploadSize: uploadFileSize - failedChunkSizes, - totalSize: totalFileSize - }; + 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; } }); } - /** - * Uploads a chunk of an individual file to the specified resourceUrl. If the upload fails and the status code - * indicates a retryable status, we try to upload the chunk as well - * @param {number} httpClientIndex The index of the httpClient being used to make all the necessary calls - * @param {string} resourceUrl Url of the resource that the chunk will be uploaded to - * @param {NodeJS.ReadableStream} openStream Stream of the file that will be uploaded - * @param {number} start Starting byte index of file that the chunk belongs to - * @param {number} end Ending byte index of file that the chunk belongs to - * @param {number} uploadFileSize Total size of the file in bytes that is being uploaded - * @param {boolean} isGzip Denotes if we are uploading a Gzip compressed stream - * @param {number} totalFileSize Original total size of the file that is being uploaded - * @returns if the chunk was successfully uploaded - */ - uploadChunk(httpClientIndex, resourceUrl, openStream, start, end, uploadFileSize, isGzip, totalFileSize) { + getArtifact(artifactName, options) { return __awaiter(this, void 0, void 0, function* () { - // open a new stream and read it to compute the digest - const digest = yield utils_1.digestForStream(openStream()); - // prepare all the necessary headers before making any http call - const headers = utils_1.getUploadHeaders('application/octet-stream', true, isGzip, totalFileSize, end - start + 1, utils_1.getContentRange(start, end, uploadFileSize), digest); - const uploadChunkRequest = () => __awaiter(this, void 0, void 0, function* () { - const client = this.uploadHttpManager.getClient(httpClientIndex); - return yield client.sendStream('PUT', resourceUrl, openStream(), headers); - }); - let retryCount = 0; - const retryLimit = config_variables_1.getRetryLimit(); - // Increments the current retry count and then checks if the retry limit has been reached - // If there have been too many retries, fail so the download stops - const incrementAndCheckRetryLimit = (response) => { - retryCount++; - if (retryCount > retryLimit) { - if (response) { - utils_1.displayHttpDiagnostics(response); - } - core.info(`Retry limit has been reached for chunk at offset ${start} to ${resourceUrl}`); - return true; - } - return false; - }; - const backOff = (retryAfterValue) => __awaiter(this, void 0, void 0, function* () { - this.uploadHttpManager.disposeAndReplaceClient(httpClientIndex); - if (retryAfterValue) { - core.info(`Backoff due to too many requests, retry #${retryCount}. Waiting for ${retryAfterValue} milliseconds before continuing the upload`); - yield utils_1.sleep(retryAfterValue); - } - else { - const backoffTime = utils_1.getExponentialRetryTimeInMilliseconds(retryCount); - core.info(`Exponential backoff for retry #${retryCount}. Waiting for ${backoffTime} milliseconds before continuing the upload at offset ${start}`); - yield utils_1.sleep(backoffTime); - } - core.info(`Finished backoff for retry #${retryCount}, continuing with upload`); - return; - }); - // allow for failed chunks to be retried multiple times - while (retryCount <= retryLimit) { - let response; - try { - response = yield uploadChunkRequest(); - } - catch (error) { - // if an error is caught, it is usually indicative of a timeout so retry the upload - core.info(`An error has been caught http-client index ${httpClientIndex}, retrying the upload`); - // eslint-disable-next-line no-console - console.log(error); - if (incrementAndCheckRetryLimit()) { - return false; - } - yield backOff(); - continue; - } - // Always read the body of the response. There is potential for a resource leak if the body is not read which will - // result in the connection remaining open along with unintended consequences when trying to dispose of the client - yield response.readBody(); - if (utils_1.isSuccessStatusCode(response.message.statusCode)) { - return true; - } - else if (utils_1.isRetryableStatusCode(response.message.statusCode)) { - core.info(`A ${response.message.statusCode} status code has been received, will attempt to retry the upload`); - if (incrementAndCheckRetryLimit(response)) { - return false; - } - utils_1.isThrottledStatusCode(response.message.statusCode) - ? yield backOff(utils_1.tryGetRetryAfterValueTimeInMilliseconds(response.message.headers)) - : yield backOff(); + try { + if ((0, config_1.isGhes)()) { + throw new errors_1.GHESNotSupportedError(); } - else { - core.error(`Unexpected response. Unable to upload chunk to ${resourceUrl}`); - utils_1.displayHttpDiagnostics(response); - return false; + 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; } - return false; }); } - /** - * Updates the size of the artifact from -1 which was initially set when the container was first created for the artifact. - * Updating the size indicates that we are done uploading all the contents of the artifact - */ - patchArtifactSize(size, artifactName) { + deleteArtifact(artifactName, options) { return __awaiter(this, void 0, void 0, function* () { - const resourceUrl = new url_1.URL(utils_1.getArtifactUrl()); - resourceUrl.searchParams.append('artifactName', artifactName); - const parameters = { Size: size }; - const data = JSON.stringify(parameters, null, 2); - core.debug(`URL is ${resourceUrl.toString()}`); - // use the first client from the httpManager, `keep-alive` is not used so the connection will close immediately - const client = this.uploadHttpManager.getClient(0); - const headers = utils_1.getUploadHeaders('application/json', false); - // Extra information to display when a particular HTTP code is returned - const customErrorMessages = new Map([ - [ - http_client_1.HttpCodes.NotFound, - `An Artifact with the name ${artifactName} was not found` - ] - ]); - // TODO retry for all possible response codes, the artifact upload is pretty much complete so it at all costs we should try to finish this - const response = yield requestUtils_1.retryHttpClientRequest('Finalize artifact upload', () => __awaiter(this, void 0, void 0, function* () { return client.patch(resourceUrl.toString(), data, headers); }), customErrorMessages); - yield response.readBody(); - core.debug(`Artifact ${artifactName} has been successfully uploaded, total size in bytes: ${size}`); + 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, workflowRunId, token } } = options; + return (0, delete_artifact_1.deleteArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token); + } + return (0, delete_artifact_1.deleteArtifactInternal)(artifactName); + } + catch (error) { + (0, core_1.warning)(`Delete 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; + } }); } } -exports.UploadHttpClient = UploadHttpClient; -//# sourceMappingURL=upload-http-client.js.map +exports.DefaultArtifactClient = DefaultArtifactClient; +//# sourceMappingURL=client.js.map + +/***/ }), + +/***/ 70071: +/***/ (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.deleteArtifactInternal = exports.deleteArtifactPublic = 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); +const get_artifact_1 = __nccwpck_require__(29491); +const errors_1 = __nccwpck_require__(38182); +function deleteArtifactPublic(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 (0, get_artifact_1.getArtifactPublic)(artifactName, workflowRunId, repositoryOwner, repositoryName, token); + const deleteArtifactResp = yield github.rest.actions.deleteArtifact({ + owner: repositoryOwner, + repo: repositoryName, + artifact_id: getArtifactResp.artifact.id + }); + if (deleteArtifactResp.status !== 204) { + throw new errors_1.InvalidResponseError(`Invalid response from GitHub API: ${deleteArtifactResp.status} (${(_a = deleteArtifactResp === null || deleteArtifactResp === void 0 ? void 0 : deleteArtifactResp.headers) === null || _a === void 0 ? void 0 : _a['x-github-request-id']})`); + } + return { + id: getArtifactResp.artifact.id + }; + }); +} +exports.deleteArtifactPublic = deleteArtifactPublic; +function deleteArtifactInternal(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 listReq = { + workflowRunBackendId, + workflowJobRunBackendId, + nameFilter: generated_1.StringValue.create({ value: artifactName }) + }; + const listRes = yield artifactClient.ListArtifacts(listReq); + if (listRes.artifacts.length === 0) { + throw new errors_1.ArtifactNotFoundError(`Artifact not found for name: ${artifactName}`); + } + let artifact = listRes.artifacts[0]; + if (listRes.artifacts.length > 1) { + artifact = listRes.artifacts.sort((a, b) => Number(b.databaseId) - Number(a.databaseId))[0]; + (0, core_1.debug)(`More than one artifact found for a single name, returning newest (id: ${artifact.databaseId})`); + } + const req = { + workflowRunBackendId: artifact.workflowRunBackendId, + workflowJobRunBackendId: artifact.workflowJobRunBackendId, + name: artifact.name + }; + const res = yield artifactClient.DeleteArtifact(req); + (0, core_1.info)(`Artifact '${artifactName}' (ID: ${res.artifactId}) deleted`); + return { + id: Number(res.artifactId) + }; + }); +} +exports.deleteArtifactInternal = deleteArtifactInternal; +//# sourceMappingURL=delete-artifact.js.map /***/ }), -/***/ 8359: +/***/ 73555: /***/ (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]; } }); + 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]; @@ -1798,99 +2309,222 @@ 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; }; +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.getUploadSpecification = void 0; -const fs = __importStar(__nccwpck_require__(7147)); -const core_1 = __nccwpck_require__(7334); -const path_1 = __nccwpck_require__(1017); -const path_and_artifact_name_validation_1 = __nccwpck_require__(1611); -/** - * Creates a specification that describes how each file that is part of the artifact will be uploaded - * @param artifactName the name of the artifact being uploaded. Used during upload to denote where the artifact is stored on the server - * @param rootDirectory an absolute file path that denotes the path that should be removed from the beginning of each artifact file - * @param artifactFiles a list of absolute file paths that denote what should be uploaded as part of the artifact - */ -function getUploadSpecification(artifactName, rootDirectory, artifactFiles) { - // artifact name was checked earlier on, no need to check again - const specifications = []; - if (!fs.existsSync(rootDirectory)) { - throw new Error(`Provided rootDirectory ${rootDirectory} does not exist`); - } - if (!fs.lstatSync(rootDirectory).isDirectory()) { - throw new Error(`Provided rootDirectory ${rootDirectory} is not a valid directory`); - } - // Normalize and resolve, this allows for either absolute or relative paths to be used - rootDirectory = path_1.normalize(rootDirectory); - rootDirectory = path_1.resolve(rootDirectory); - /* - Example to demonstrate behavior - - Input: - artifactName: my-artifact - 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', 'my-artifact/file1.txt'], - ['/home/user/files/plz-upload/file1.txt', 'my-artifact/file2.txt'], - ['/home/user/files/plz-upload/file1.txt', 'my-artifact/dir/file3.txt'] - ] - */ - for (let file of artifactFiles) { - if (!fs.existsSync(file)) { - throw new Error(`File ${file} does not exist`); +exports.downloadArtifactInternal = exports.downloadArtifactPublic = exports.streamExtractExternal = 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; } - if (!fs.lstatSync(file).isDirectory()) { - // Normalize and resolve, this allows for either absolute or relative paths to be used - file = path_1.normalize(file); - file = path_1.resolve(file); - if (!file.startsWith(rootDirectory)) { - throw new Error(`The rootDirectory: ${rootDirectory} is not a parent directory of the file: ${file}`); + catch (error) { + if (error.code === 'ENOENT') { + return false; } - // Check for forbidden characters in file paths that will be rejected during upload - const uploadPath = file.replace(rootDirectory, ''); - path_and_artifact_name_validation_1.checkArtifactFilePath(uploadPath); - /* - uploadFilePath denotes where the file will be uploaded in the file container on the server. During a run, if multiple artifacts are uploaded, they will all - be saved in the same container. The artifact name is used as the root directory in the container to separate and distinguish uploaded artifacts - - path.join handles all the following cases and would return 'artifact-name/file-to-upload.txt - join('artifact-name/', 'file-to-upload.txt') - join('artifact-name/', '/file-to-upload.txt') - join('artifact-name', 'file-to-upload.txt') - join('artifact-name', '/file-to-upload.txt') - */ - specifications.push({ - absoluteFilePath: file, - uploadFilePath: path_1.join(artifactName, uploadPath) + else { + throw error; + } + } + }); +} +function streamExtract(url, directory) { + return __awaiter(this, void 0, void 0, function* () { + let retryCount = 0; + while (retryCount < 5) { + try { + yield streamExtractExternal(url, directory); + return; + } + catch (error) { + retryCount++; + core.debug(`Failed to download artifact after ${retryCount} retries due to ${error.message}. Retrying in 5 seconds...`); + // wait 5 seconds before retrying + yield new Promise(resolve => setTimeout(resolve, 5000)); + } + } + throw new Error(`Artifact download failed after ${retryCount} retries.`); + }); +} +function streamExtractExternal(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}`); + } + const timeout = 30 * 1000; // 30 seconds + return new Promise((resolve, reject) => { + const timerFn = () => { + response.message.destroy(new Error(`Blob storage chunk did not respond in ${timeout}ms`)); + }; + const timer = setTimeout(timerFn, timeout); + response.message + .on('data', () => { + timer.refresh(); + }) + .on('error', (error) => { + core.debug(`response.message: Artifact download failed: ${error.message}`); + clearTimeout(timer); + reject(error); + }) + .pipe(unzip_stream_1.default.Extract({ path: directory })) + .on('close', () => { + clearTimeout(timer); + resolve(); + }) + .on('error', (error) => { + reject(error); }); + }); + }); +} +exports.streamExtractExternal = streamExtractExternal; +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}`); + } + 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 }; + }); +} +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.`); + } + if (artifacts.length > 1) { + core.warning('Multiple artifacts found, defaulting to first.'); + } + 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.`); + } + catch (error) { + throw new Error(`Unable to download and extract artifact: ${error.message}`); + } + return { downloadPath }; + }); +} +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 }); } else { - // Directories are rejected by the server during upload - core_1.debug(`Removing ${file} from rawSearchResults because it is a directory`); + core.debug(`Artifact destination folder already exists: ${downloadPath}`); } - } - return specifications; + return downloadPath; + }); } -exports.getUploadSpecification = getUploadSpecification; -//# sourceMappingURL=upload-specification.js.map +//# sourceMappingURL=download-artifact.js.map /***/ }), -/***/ 1337: +/***/ 29491: /***/ (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) { @@ -1900,292 +2534,99 @@ 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.digestForStream = exports.sleep = exports.getProperRetention = exports.rmFile = exports.getFileSize = exports.createEmptyFilesForArtifact = exports.createDirectoriesForArtifact = exports.displayHttpDiagnostics = exports.getArtifactUrl = exports.createHttpClient = exports.getUploadHeaders = exports.getDownloadHeaders = exports.getContentRange = exports.tryGetRetryAfterValueTimeInMilliseconds = exports.isThrottledStatusCode = exports.isRetryableStatusCode = exports.isForbiddenStatusCode = exports.isSuccessStatusCode = exports.getApiVersion = exports.parseEnvNumber = exports.getExponentialRetryTimeInMilliseconds = void 0; -const crypto_1 = __importDefault(__nccwpck_require__(6113)); -const fs_1 = __nccwpck_require__(7147); -const core_1 = __nccwpck_require__(7334); -const http_client_1 = __nccwpck_require__(7820); -const auth_1 = __nccwpck_require__(2245); -const config_variables_1 = __nccwpck_require__(7289); -const crc64_1 = __importDefault(__nccwpck_require__(8541)); -/** - * Returns a retry time in milliseconds that exponentially gets larger - * depending on the amount of retries that have been attempted - */ -function getExponentialRetryTimeInMilliseconds(retryCount) { - if (retryCount < 0) { - throw new Error('RetryCount should not be negative'); - } - else if (retryCount === 0) { - return config_variables_1.getInitialRetryIntervalInMilliseconds(); - } - const minTime = config_variables_1.getInitialRetryIntervalInMilliseconds() * config_variables_1.getRetryMultiplier() * retryCount; - const maxTime = minTime * config_variables_1.getRetryMultiplier(); - // returns a random number between the minTime (inclusive) and the maxTime (exclusive) - return Math.trunc(Math.random() * (maxTime - minTime) + minTime); -} -exports.getExponentialRetryTimeInMilliseconds = getExponentialRetryTimeInMilliseconds; -/** - * Parses a env variable that is a number - */ -function parseEnvNumber(key) { - const value = Number(process.env[key]); - if (Number.isNaN(value) || value < 0) { - return undefined; - } - return value; -} -exports.parseEnvNumber = parseEnvNumber; -/** - * Various utility functions to help with the necessary API calls - */ -function getApiVersion() { - return '6.0-preview'; -} -exports.getApiVersion = getApiVersion; -function isSuccessStatusCode(statusCode) { - if (!statusCode) { - return false; - } - return statusCode >= 200 && statusCode < 300; -} -exports.isSuccessStatusCode = isSuccessStatusCode; -function isForbiddenStatusCode(statusCode) { - if (!statusCode) { - return false; - } - return statusCode === http_client_1.HttpCodes.Forbidden; -} -exports.isForbiddenStatusCode = isForbiddenStatusCode; -function isRetryableStatusCode(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, - 413 // Payload Too Large - ]; - return retryableStatusCodes.includes(statusCode); -} -exports.isRetryableStatusCode = isRetryableStatusCode; -function isThrottledStatusCode(statusCode) { - if (!statusCode) { - return false; - } - return statusCode === http_client_1.HttpCodes.TooManyRequests; -} -exports.isThrottledStatusCode = isThrottledStatusCode; -/** - * Attempts to get the retry-after value from a set of http headers. The retry time - * is originally denoted in seconds, so if present, it is converted to milliseconds - * @param headers all the headers received when making an http call - */ -function tryGetRetryAfterValueTimeInMilliseconds(headers) { - if (headers['retry-after']) { - const retryTime = Number(headers['retry-after']); - if (!isNaN(retryTime)) { - core_1.info(`Retry-After header is present with a value of ${retryTime}`); - return retryTime * 1000; - } - core_1.info(`Returned retry-after header value: ${retryTime} is non-numeric and cannot be used`); - return undefined; - } - core_1.info(`No retry-after header was found. Dumping all headers for diagnostic purposes`); - // eslint-disable-next-line no-console - console.log(headers); - return undefined; -} -exports.tryGetRetryAfterValueTimeInMilliseconds = tryGetRetryAfterValueTimeInMilliseconds; -function getContentRange(start, end, total) { - // Format: `bytes start-end/fileSize - // start and end are inclusive - // For a 200 byte chunk starting at byte 0: - // Content-Range: bytes 0-199/200 - return `bytes ${start}-${end}/${total}`; -} -exports.getContentRange = getContentRange; -/** - * Sets all the necessary headers when downloading an artifact - * @param {string} contentType the type of content being uploaded - * @param {boolean} isKeepAlive is the same connection being used to make multiple calls - * @param {boolean} acceptGzip can we accept a gzip encoded response - * @param {string} acceptType the type of content that we can accept - * @returns appropriate headers to make a specific http call during artifact download - */ -function getDownloadHeaders(contentType, isKeepAlive, acceptGzip) { - const requestOptions = {}; - if (contentType) { - requestOptions['Content-Type'] = contentType; - } - if (isKeepAlive) { - requestOptions['Connection'] = 'Keep-Alive'; - // keep alive for at least 10 seconds before closing the connection - requestOptions['Keep-Alive'] = '10'; - } - if (acceptGzip) { - // if we are expecting a response with gzip encoding, it should be using an octet-stream in the accept header - requestOptions['Accept-Encoding'] = 'gzip'; - requestOptions['Accept'] = `application/octet-stream;api-version=${getApiVersion()}`; - } - else { - // default to application/json if we are not working with gzip content - requestOptions['Accept'] = `application/json;api-version=${getApiVersion()}`; - } - return requestOptions; -} -exports.getDownloadHeaders = getDownloadHeaders; -/** - * Sets all the necessary headers when uploading an artifact - * @param {string} contentType the type of content being uploaded - * @param {boolean} isKeepAlive is the same connection being used to make multiple calls - * @param {boolean} isGzip is the connection being used to upload GZip compressed content - * @param {number} uncompressedLength the original size of the content if something is being uploaded that has been compressed - * @param {number} contentLength the length of the content that is being uploaded - * @param {string} contentRange the range of the content that is being uploaded - * @returns appropriate headers to make a specific http call during artifact upload - */ -function getUploadHeaders(contentType, isKeepAlive, isGzip, uncompressedLength, contentLength, contentRange, digest) { - const requestOptions = {}; - requestOptions['Accept'] = `application/json;api-version=${getApiVersion()}`; - if (contentType) { - requestOptions['Content-Type'] = contentType; - } - if (isKeepAlive) { - requestOptions['Connection'] = 'Keep-Alive'; - // keep alive for at least 10 seconds before closing the connection - requestOptions['Keep-Alive'] = '10'; - } - if (isGzip) { - requestOptions['Content-Encoding'] = 'gzip'; - requestOptions['x-tfs-filelength'] = uncompressedLength; - } - if (contentLength) { - requestOptions['Content-Length'] = contentLength; - } - if (contentRange) { - requestOptions['Content-Range'] = contentRange; - } - if (digest) { - requestOptions['x-actions-results-crc64'] = digest.crc64; - requestOptions['x-actions-results-md5'] = digest.md5; - } - return requestOptions; -} -exports.getUploadHeaders = getUploadHeaders; -function createHttpClient(userAgent) { - return new http_client_1.HttpClient(userAgent, [ - new auth_1.BearerCredentialHandler(config_variables_1.getRuntimeToken()) - ]); -} -exports.createHttpClient = createHttpClient; -function getArtifactUrl() { - const artifactUrl = `${config_variables_1.getRuntimeUrl()}_apis/pipelines/workflows/${config_variables_1.getWorkFlowRunId()}/artifacts?api-version=${getApiVersion()}`; - core_1.debug(`Artifact Url: ${artifactUrl}`); - return artifactUrl; -} -exports.getArtifactUrl = getArtifactUrl; -/** - * Uh oh! Something might have gone wrong during either upload or download. The IHtttpClientResponse object contains information - * about the http call that was made by the actions http client. This information might be useful to display for diagnostic purposes, but - * this entire object is really big and most of the information is not really useful. This function takes the response object and displays only - * the information that we want. - * - * Certain information such as the TLSSocket and the Readable state are not really useful for diagnostic purposes so they can be avoided. - * Other information such as the headers, the response code and message might be useful, so this is displayed. - */ -function displayHttpDiagnostics(response) { - core_1.info(`##### Begin Diagnostic HTTP information ##### -Status Code: ${response.message.statusCode} -Status Message: ${response.message.statusMessage} -Header Information: ${JSON.stringify(response.message.headers, undefined, 2)} -###### End Diagnostic HTTP information ######`); -} -exports.displayHttpDiagnostics = displayHttpDiagnostics; -function createDirectoriesForArtifact(directories) { +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* () { - for (const directory of directories) { - yield fs_1.promises.mkdir(directory, { - recursive: true - }); + 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']})`); } - }); -} -exports.createDirectoriesForArtifact = createDirectoriesForArtifact; -function createEmptyFilesForArtifact(emptyFilesToCreate) { - return __awaiter(this, void 0, void 0, function* () { - for (const filePath of emptyFilesToCreate) { - yield (yield fs_1.promises.open(filePath, 'w')).close(); + if (getArtifactResp.data.artifacts.length === 0) { + throw new errors_1.ArtifactNotFoundError(`Artifact not found for name: ${artifactName} + Please ensure that your artifact is not expired and the artifact was uploaded using a compatible version of toolkit/upload-artifact. + For more information, visit the GitHub Artifacts FAQ: https://github.com/actions/toolkit/blob/main/packages/artifact/docs/faq.md`); } - }); -} -exports.createEmptyFilesForArtifact = createEmptyFilesForArtifact; -function getFileSize(filePath) { - return __awaiter(this, void 0, void 0, function* () { - const stats = yield fs_1.promises.stat(filePath); - core_1.debug(`${filePath} size:(${stats.size}) blksize:(${stats.blksize}) blocks:(${stats.blocks})`); - return stats.size; - }); -} -exports.getFileSize = getFileSize; -function rmFile(filePath) { - return __awaiter(this, void 0, void 0, function* () { - yield fs_1.promises.unlink(filePath); - }); -} -exports.rmFile = rmFile; -function getProperRetention(retentionInput, retentionSetting) { - if (retentionInput < 0) { - throw new Error('Invalid retention, minimum value is 1.'); - } - let retention = retentionInput; - if (retentionSetting) { - const maxRetention = parseInt(retentionSetting); - if (!isNaN(maxRetention) && maxRetention < retention) { - core_1.warning(`Retention days is greater than the max value allowed by the repository setting, reduce retention to ${maxRetention} days`); - retention = maxRetention; + 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 retention; -} -exports.getProperRetention = getProperRetention; -function sleep(milliseconds) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise(resolve => setTimeout(resolve, milliseconds)); + return { + artifact: { + name: artifact.name, + id: artifact.id, + size: artifact.size_in_bytes, + createdAt: artifact.created_at ? new Date(artifact.created_at) : undefined + } + }; }); } -exports.sleep = sleep; -function digestForStream(stream) { +exports.getArtifactPublic = getArtifactPublic; +function getArtifactInternal(artifactName) { return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => { - const crc64 = new crc64_1.default(); - const md5 = crypto_1.default.createHash('md5'); - stream - .on('data', data => { - crc64.update(data); - md5.update(data); - }) - .on('end', () => resolve({ - crc64: crc64.digest('base64'), - md5: md5.digest('base64') - })) - .on('error', reject); - }); + 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} + Please ensure that your artifact is not expired and the artifact was uploaded using a compatible version of toolkit/upload-artifact. + For more information, visit the GitHub Artifacts FAQ: https://github.com/actions/toolkit/blob/main/packages/artifact/docs/faq.md`); + } + 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 + } + }; }); } -exports.digestForStream = digestForStream; -//# sourceMappingURL=utils.js.map +exports.getArtifactInternal = getArtifactInternal; +//# sourceMappingURL=get-artifact.js.map /***/ }), -/***/ 80: +/***/ 44141: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -2199,186 +2640,196 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __importStar(__nccwpck_require__(7334)); -const path = __importStar(__nccwpck_require__(1017)); -const utils = __importStar(__nccwpck_require__(5406)); -const cacheHttpClient = __importStar(__nccwpck_require__(8494)); -const tar_1 = __nccwpck_require__(9403); -class ValidationError extends Error { - constructor(message) { - super(message); - this.name = 'ValidationError'; - Object.setPrototypeOf(this, ValidationError.prototype); - } -} -exports.ValidationError = ValidationError; -class ReserveCacheError extends Error { - constructor(message) { - super(message); - this.name = 'ReserveCacheError'; - Object.setPrototypeOf(this, ReserveCacheError.prototype); - } -} -exports.ReserveCacheError = ReserveCacheError; -function checkPaths(paths) { - if (!paths || paths.length === 0) { - throw new ValidationError(`Path Validation Error: At least one directory or file path is required`); - } -} -function checkKey(key) { - if (key.length > 512) { - throw new ValidationError(`Key Validation Error: ${key} cannot be larger than 512 characters.`); - } - const regex = /^[^,]*$/; - if (!regex.test(key)) { - throw new ValidationError(`Key Validation Error: ${key} cannot contain commas.`); - } -} -/** - * isFeatureAvailable to check the presence of Actions cache service - * - * @returns boolean return true if Actions cache service feature is available, otherwise false - */ -function isFeatureAvailable() { - return !!process.env['ACTIONS_CACHE_URL']; -} -exports.isFeatureAvailable = isFeatureAvailable; -/** - * Restores cache from keys - * - * @param paths a list of file paths to restore from the cache - * @param primaryKey an explicit key for restoring the cache - * @param restoreKeys an optional ordered list of keys to use for restoring the cache if no cache hit occurred for key - * @param downloadOptions cache download options - * @returns string returns the key for the cache hit, otherwise returns undefined - */ -function restoreCache(paths, primaryKey, restoreKeys, options) { +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* () { - checkPaths(paths); - restoreKeys = restoreKeys || []; - const keys = [primaryKey, ...restoreKeys]; - core.debug('Resolved Keys:'); - core.debug(JSON.stringify(keys)); - if (keys.length > 10) { - throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); - } - for (const key of keys) { - checkKey(key); - } - const compressionMethod = yield utils.getCompressionMethod(); - // path are needed to compute version - const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, { - compressionMethod + (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 }); - if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) { - // Cache not found - return undefined; + 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 + }); } - const archivePath = path.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); - core.debug(`Archive Path: ${archivePath}`); - try { - // Download the cache from the cache entry - yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options); - if (core.isDebug()) { - yield tar_1.listTar(archivePath, compressionMethod); + // 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 + }); } - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); - yield tar_1.extractTar(archivePath, compressionMethod); - core.info('Cache restored successfully'); } - finally { - // Try to delete the archive to save space - try { - yield utils.unlinkFile(archivePath); - } - catch (error) { - core.debug(`Failed to delete archive: ${error}`); - } + if (latest) { + artifacts = filterLatest(artifacts); } - return cacheEntry.cacheKey; + (0, core_1.info)(`Found ${artifacts.length} artifact(s)`); + return { + artifacts + }; }); } -exports.restoreCache = restoreCache; -/** - * Saves a list of files with the specified key - * - * @param paths a list of file paths to be cached - * @param key an explicit key for restoring the cache - * @param options cache upload options - * @returns number returns cacheId if the cache was saved successfully and throws an error if save fails - */ -function saveCache(paths, key, options) { - var _a, _b, _c, _d, _e; +exports.listArtifactsPublic = listArtifactsPublic; +function listArtifactsInternal(latest = false) { return __awaiter(this, void 0, void 0, function* () { - checkPaths(paths); - checkKey(key); - const compressionMethod = yield utils.getCompressionMethod(); - let cacheId = null; - const cachePaths = yield utils.resolvePaths(paths); - core.debug('Cache Paths:'); - core.debug(`${JSON.stringify(cachePaths)}`); - if (cachePaths.length === 0) { - throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); - } - const archiveFolder = yield utils.createTempDirectory(); - const archivePath = path.join(archiveFolder, utils.getCacheFileName(compressionMethod)); - core.debug(`Archive Path: ${archivePath}`); - try { - yield tar_1.createTar(archiveFolder, cachePaths, compressionMethod); - if (core.isDebug()) { - yield tar_1.listTar(archivePath, compressionMethod); - } - const fileSizeLimit = 10 * 1024 * 1024 * 1024; // 10GB per repo limit - const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); - core.debug(`File Size: ${archiveFileSize}`); - // For GHES, this check will take place in ReserveCache API with enterprise file size limit - if (archiveFileSize > fileSizeLimit && !utils.isGhes()) { - throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`); - } - core.debug('Reserving Cache'); - const reserveCacheResponse = yield cacheHttpClient.reserveCache(key, paths, { - compressionMethod, - cacheSize: archiveFileSize - }); - if ((_a = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _a === void 0 ? void 0 : _a.cacheId) { - cacheId = (_b = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _b === void 0 ? void 0 : _b.cacheId; - } - else if ((reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.statusCode) === 400) { - throw new Error((_d = (_c = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : `Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the data cap limit, not saving cache.`); - } - else { - throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache. More details: ${(_e = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _e === void 0 ? void 0 : _e.message}`); - } - core.debug(`Saving Cache (ID: ${cacheId})`); - yield cacheHttpClient.saveCache(cacheId, archivePath, options); - } - finally { - // Try to delete the archive to save space - try { - yield utils.unlinkFile(archivePath); - } - catch (error) { - core.debug(`Failed to delete archive: ${error}`); - } + 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 cacheId; + (0, core_1.info)(`Found ${artifacts.length} artifact(s)`); + return { + artifacts + }; }); } -exports.saveCache = saveCache; -//# sourceMappingURL=cache.js.map +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); + } + } + return latestArtifacts; +} +//# sourceMappingURL=list-artifacts.js.map /***/ }), -/***/ 8494: +/***/ 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]; } }; + } + 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]; + } + 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]; +} +exports.getRetryOptions = getRetryOptions; +//# sourceMappingURL=retry-options.js.map + +/***/ }), + +/***/ 12312: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -2392,217 +2843,439 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; +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) + ]); + } + // 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}`); + } + }); + } + 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}`); + } + 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++; + } + throw new Error(`Request failed`); + }); + } + isSuccessStatusCode(statusCode) { + if (!statusCode) + return false; + return statusCode >= 200 && statusCode < 300; + } + 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)); + }); + } + 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); + } +} +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 })); -const core = __importStar(__nccwpck_require__(7334)); -const http_client_1 = __nccwpck_require__(7820); -const auth_1 = __nccwpck_require__(2245); -const crypto = __importStar(__nccwpck_require__(6113)); -const fs = __importStar(__nccwpck_require__(7147)); -const url_1 = __nccwpck_require__(7310); -const utils = __importStar(__nccwpck_require__(5406)); -const constants_1 = __nccwpck_require__(5538); -const downloadUtils_1 = __nccwpck_require__(1196); -const options_1 = __nccwpck_require__(1141); -const requestUtils_1 = __nccwpck_require__(8868); -const versionSalt = '1.0'; -function getCacheApiUrl(resource) { - const baseUrl = process.env['ACTIONS_CACHE_URL'] || ''; - if (!baseUrl) { - throw new Error('Cache Service Url not found, unable to restore cache.'); +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'); } - const url = `${baseUrl}_apis/artifactcache/${resource}`; - core.debug(`Resource Url: ${url}`); - return url; + return token; } -function createAcceptHeader(type, apiVersion) { - return `${type};api-version=${apiVersion}`; +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; } -function getRequestOptions() { - const requestOptions = { - headers: { - Accept: createAcceptHeader('application/json', '6.0-preview.1') - } - }; - return requestOptions; +exports.getResultsServiceUrl = getResultsServiceUrl; +function isGhes() { + const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com'); + const hostname = ghUrl.hostname.trimEnd().toUpperCase(); + const isGitHubHost = hostname === 'GITHUB.COM'; + const isGheHost = hostname.endsWith('.GHE.COM') || hostname.endsWith('.GHE.LOCALHOST'); + return !isGitHubHost && !isGheHost; } -function createHttpClient() { - const token = process.env['ACTIONS_RUNTIME_TOKEN'] || ''; - const bearerCredentialHandler = new auth_1.BearerCredentialHandler(token); - return new http_client_1.HttpClient('actions/cache', [bearerCredentialHandler], getRequestOptions()); +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; } -function getCacheVersion(paths, compressionMethod) { - const components = paths.concat(!compressionMethod || compressionMethod === constants_1.CompressionMethod.Gzip - ? [] - : [compressionMethod]); - // Add salt to cache version to support breaking changes in cache entry - components.push(versionSalt); - return crypto - .createHash('sha256') - .update(components.join('|')) - .digest('hex'); +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.getCacheVersion = getCacheVersion; -function getCacheEntry(keys, paths, options) { - return __awaiter(this, void 0, void 0, function* () { - const httpClient = createHttpClient(); - const version = getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod); - const resource = `cache?keys=${encodeURIComponent(keys.join(','))}&version=${version}`; - const response = yield requestUtils_1.retryTypedResponse('getCacheEntry', () => __awaiter(this, void 0, void 0, function* () { return httpClient.getJson(getCacheApiUrl(resource)); })); - if (response.statusCode === 204) { - return null; +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(', ')}`; } - if (!requestUtils_1.isSuccessStatusCode(response.statusCode)) { - throw new Error(`Cache service responded with ${response.statusCode}`); - } - const cacheResult = response.result; - const cacheDownloadUrl = cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.archiveLocation; - if (!cacheDownloadUrl) { - throw new Error('Cache not found.'); - } - core.setSecret(cacheDownloadUrl); - core.debug(`Cache Result:`); - core.debug(JSON.stringify(cacheResult)); - return cacheResult; - }); + super(message); + this.files = files; + this.name = 'FilesNotFoundError'; + } } -exports.getCacheEntry = getCacheEntry; -function downloadCache(archiveLocation, archivePath, options) { - return __awaiter(this, void 0, void 0, function* () { - const archiveUrl = new url_1.URL(archiveLocation); - const downloadOptions = options_1.getDownloadOptions(options); - if (downloadOptions.useAzureSdk && - archiveUrl.hostname.endsWith('.blob.core.windows.net')) { - // Use Azure storage SDK to download caches hosted on Azure to improve speed and reliability. - yield downloadUtils_1.downloadCacheStorageSDK(archiveLocation, archivePath, downloadOptions); - } - else { - // Otherwise, download using the Actions http-client. - yield downloadUtils_1.downloadCacheHttpClient(archiveLocation, archivePath); - } - }); +exports.FilesNotFoundError = FilesNotFoundError; +class InvalidResponseError extends Error { + constructor(message) { + super(message); + this.name = 'InvalidResponseError'; + } } -exports.downloadCache = downloadCache; -// Reserve Cache -function reserveCache(key, paths, options) { - return __awaiter(this, void 0, void 0, function* () { - const httpClient = createHttpClient(); - const version = getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod); - const reserveCacheRequest = { - key, - version, - cacheSize: options === null || options === void 0 ? void 0 : options.cacheSize - }; - const response = yield requestUtils_1.retryTypedResponse('reserveCache', () => __awaiter(this, void 0, void 0, function* () { - return httpClient.postJson(getCacheApiUrl('caches'), reserveCacheRequest); - })); - return response; - }); +exports.InvalidResponseError = InvalidResponseError; +class ArtifactNotFoundError extends Error { + constructor(message = 'Artifact not found') { + super(message); + this.name = 'ArtifactNotFoundError'; + } } -exports.reserveCache = reserveCache; -function getContentRange(start, end) { - // Format: `bytes start-end/filesize - // start and end are inclusive - // filesize can be * - // For a 200 byte chunk starting at byte 0: - // Content-Range: bytes 0-199/* - return `bytes ${start}-${end}/*`; +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'; + } } -function uploadChunk(httpClient, resourceUrl, openStream, start, end) { - return __awaiter(this, void 0, void 0, function* () { - core.debug(`Uploading chunk of size ${end - - start + - 1} bytes at offset ${start} with content range: ${getContentRange(start, end)}`); - const additionalHeaders = { - 'Content-Type': 'application/octet-stream', - 'Content-Range': getContentRange(start, end) - }; - const uploadChunkResponse = yield requestUtils_1.retryHttpClientResponse(`uploadChunk (start: ${start}, end: ${end})`, () => __awaiter(this, void 0, void 0, function* () { - return httpClient.sendStream('PATCH', resourceUrl, openStream(), additionalHeaders); - })); - if (!requestUtils_1.isSuccessStatusCode(uploadChunkResponse.message.statusCode)) { - throw new Error(`Cache service responded with ${uploadChunkResponse.message.statusCode} during upload chunk.`); - } - }); +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'; + } } -function uploadFile(httpClient, cacheId, archivePath, options) { - return __awaiter(this, void 0, void 0, function* () { - // Upload Chunks - const fileSize = utils.getArchiveFileSizeInBytes(archivePath); - const resourceUrl = getCacheApiUrl(`caches/${cacheId.toString()}`); - const fd = fs.openSync(archivePath, 'r'); - const uploadOptions = options_1.getUploadOptions(options); - const concurrency = utils.assertDefined('uploadConcurrency', uploadOptions.uploadConcurrency); - const maxChunkSize = utils.assertDefined('uploadChunkSize', uploadOptions.uploadChunkSize); - const parallelUploads = [...new Array(concurrency).keys()]; - core.debug('Awaiting all uploads'); - let offset = 0; - try { - yield Promise.all(parallelUploads.map(() => __awaiter(this, void 0, void 0, function* () { - while (offset < fileSize) { - const chunkSize = Math.min(fileSize - offset, maxChunkSize); - const start = offset; - const end = offset + chunkSize - 1; - offset += maxChunkSize; - yield uploadChunk(httpClient, resourceUrl, () => fs - .createReadStream(archivePath, { - fd, - start, - end, - autoClose: false - }) - .on('error', error => { - throw new Error(`Cache upload failed because file read failed with ${error.message}`); - }), start, end); - } - }))); - } - finally { - fs.closeSync(fd); - } - return; - }); +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'; + } } -function commitCache(httpClient, cacheId, filesize) { - return __awaiter(this, void 0, void 0, function* () { - const commitCacheRequest = { size: filesize }; - return yield requestUtils_1.retryTypedResponse('commitCache', () => __awaiter(this, void 0, void 0, function* () { - return httpClient.postJson(getCacheApiUrl(`caches/${cacheId.toString()}`), commitCacheRequest); - })); - }); +exports.UsageError = UsageError; +UsageError.isUsageErrorMessage = (msg) => { + if (!msg) + return false; + return msg.includes('insufficient usage'); +}; +//# sourceMappingURL=errors.js.map + +/***/ }), + +/***/ 1647: +/***/ ((__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); +/** + * Ensure that this User Agent String is used in all HTTP calls so that we can monitor telemetry between different versions of this package + */ +function getUserAgentString() { + return `@actions/artifact-${packageJson.version}`; } -function saveCache(cacheId, archivePath, options) { - return __awaiter(this, void 0, void 0, function* () { - const httpClient = createHttpClient(); - core.debug('Upload cache'); - yield uploadFile(httpClient, cacheId, archivePath, options); - // Commit Cache - core.debug('Commiting cache'); - const cacheSize = utils.getArchiveFileSizeInBytes(archivePath); - core.info(`Cache Size: ~${Math.round(cacheSize / (1024 * 1024))} MB (${cacheSize} B)`); - const commitCacheResponse = yield commitCache(httpClient, cacheId, cacheSize); - if (!requestUtils_1.isSuccessStatusCode(commitCacheResponse.statusCode)) { - throw new Error(`Cache service responded with ${commitCacheResponse.statusCode} during commit cache.`); +exports.getUserAgentString = getUserAgentString; +//# sourceMappingURL=user-agent.js.map + +/***/ }), + +/***/ 63062: +/***/ (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 __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; + } + /* + * 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; + } + /* + * 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; } - core.info('Cache saved successfully'); - }); + /* + * 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; + } + throw InvalidJwtError; } -exports.saveCache = saveCache; -//# sourceMappingURL=cacheHttpClient.js.map +exports.getBackendIdsFromToken = getBackendIdsFromToken; +//# sourceMappingURL=util.js.map /***/ }), -/***/ 5406: +/***/ 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) { @@ -2612,210 +3285,254 @@ 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 __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __importStar(__nccwpck_require__(7334)); -const exec = __importStar(__nccwpck_require__(6703)); -const glob = __importStar(__nccwpck_require__(27)); -const io = __importStar(__nccwpck_require__(1608)); -const fs = __importStar(__nccwpck_require__(7147)); -const path = __importStar(__nccwpck_require__(1017)); -const semver = __importStar(__nccwpck_require__(7203)); -const util = __importStar(__nccwpck_require__(3837)); -const uuid_1 = __nccwpck_require__(7282); -const constants_1 = __nccwpck_require__(5538); -// From https://github.com/actions/toolkit/blob/main/packages/tool-cache/src/tool-cache.ts#L23 -function createTempDirectory() { - return __awaiter(this, void 0, void 0, function* () { - const IS_WINDOWS = process.platform === 'win32'; - let tempDirectory = process.env['RUNNER_TEMP'] || ''; - if (!tempDirectory) { - let baseLocation; - if (IS_WINDOWS) { - // On Windows use the USERPROFILE env variable - baseLocation = process.env['USERPROFILE'] || 'C:\\'; - } - else { - if (process.platform === 'darwin') { - baseLocation = '/Users'; - } - else { - baseLocation = '/home'; - } - } - tempDirectory = path.join(baseLocation, 'actions', 'temp'); - } - const dest = path.join(tempDirectory, uuid_1.v4()); - yield io.mkdirP(dest); - return dest; - }); -} -exports.createTempDirectory = createTempDirectory; -function getArchiveFileSizeInBytes(filePath) { - return fs.statSync(filePath).size; -} -exports.getArchiveFileSizeInBytes = getArchiveFileSizeInBytes; -function resolvePaths(patterns) { - var e_1, _a; - var _b; +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* () { - const paths = []; - const workspace = (_b = process.env['GITHUB_WORKSPACE']) !== null && _b !== void 0 ? _b : process.cwd(); - const globber = yield glob.create(patterns.join('\n'), { - implicitDescendants: false - }); + let uploadByteCount = 0; + let lastProgressTime = Date.now(); + let timeoutId; + const chunkTimer = (timeout) => { + // clear the previous timeout + if (timeoutId) { + clearTimeout(timeoutId); + } + timeoutId = setTimeout(() => { + const now = Date.now(); + // if there's been more than 30 seconds since the + // last progress event, then we'll consider the upload stalled + if (now - lastProgressTime > timeout) { + throw new Error('Upload progress stalled.'); + } + }, timeout); + return timeoutId; + }; + const maxConcurrency = (0, config_1.getConcurrency)(); + const bufferSize = (0, config_1.getUploadChunkSize)(); + const blobClient = new storage_blob_1.BlobClient(authenticatedUploadURL); + const blockBlobClient = blobClient.getBlockBlobClient(); + const timeoutDuration = 300000; // 30 seconds + 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; + chunkTimer(timeoutDuration); + lastProgressTime = Date.now(); + }; + 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 { - for (var _c = __asyncValues(globber.globGenerator()), _d; _d = yield _c.next(), !_d.done;) { - const file = _d.value; - const relativeFile = path - .relative(workspace, file) - .replace(new RegExp(`\\${path.sep}`, 'g'), '/'); - core.debug(`Matched: ${relativeFile}`); - // Paths are made relative so the tar entries are all relative to the root of the workspace. - paths.push(`${relativeFile}`); + // Start the chunk timer + timeoutId = chunkTimer(timeoutDuration); + 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); } + throw error; } - catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { - try { - if (_d && !_d.done && (_a = _c.return)) yield _a.call(_c); + // clear the timeout whether or not the upload completes + if (timeoutId) { + clearTimeout(timeoutId); } - finally { if (e_1) throw e_1.error; } - } - return paths; - }); -} -exports.resolvePaths = resolvePaths; -function unlinkFile(filePath) { - return __awaiter(this, void 0, void 0, function* () { - return util.promisify(fs.unlink)(filePath); - }); -} -exports.unlinkFile = unlinkFile; -function getVersion(app) { - return __awaiter(this, void 0, void 0, function* () { - core.debug(`Checking ${app} --version`); - let versionOutput = ''; - try { - yield exec.exec(`${app} --version`, [], { - ignoreReturnCode: true, - silent: true, - listeners: { - stdout: (data) => (versionOutput += data.toString()), - stderr: (data) => (versionOutput += data.toString()) - } - }); } - catch (err) { - core.debug(err.message); + 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.`); } - versionOutput = versionOutput.trim(); - core.debug(versionOutput); - return versionOutput; + return { + uploadSize: uploadByteCount, + sha256Hash + }; }); } -// Use zstandard if possible to maximize cache performance -function getCompressionMethod() { - return __awaiter(this, void 0, void 0, function* () { - if (process.platform === 'win32' && !(yield isGnuTarInstalled())) { - // Disable zstd due to bug https://github.com/actions/cache/issues/301 - return constants_1.CompressionMethod.Gzip; - } - const versionOutput = yield getVersion('zstd'); - const version = semver.clean(versionOutput); - if (!versionOutput.toLowerCase().includes('zstd command line interface')) { - // zstd is not installed - return constants_1.CompressionMethod.Gzip; - } - else if (!version || semver.lt(version, 'v1.3.2')) { - // zstd is installed but using a version earlier than v1.3.2 - // v1.3.2 is required to use the `--long` options in zstd - return constants_1.CompressionMethod.ZstdWithoutLong; - } - else { - return constants_1.CompressionMethod.Zstd; +exports.uploadZipToBlobStorage = uploadZipToBlobStorage; +//# sourceMappingURL=blob-upload.js.map + +/***/ }), + +/***/ 63219: +/***/ ((__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__(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`); + } + 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.`); } - }); -} -exports.getCompressionMethod = getCompressionMethod; -function getCacheFileName(compressionMethod) { - return compressionMethod === constants_1.CompressionMethod.Gzip - ? constants_1.CacheFilename.Gzip - : constants_1.CacheFilename.Zstd; -} -exports.getCacheFileName = getCacheFileName; -function isGnuTarInstalled() { - return __awaiter(this, void 0, void 0, function* () { - const versionOutput = yield getVersion('tar'); - return versionOutput.toLowerCase().includes('gnu tar'); - }); -} -exports.isGnuTarInstalled = isGnuTarInstalled; -function assertDefined(name, value) { - if (value === undefined) { - throw Error(`Expected ${name} but value was undefiend`); } - return value; + (0, core_1.info)(`Artifact name is valid!`); } -exports.assertDefined = assertDefined; -function isGhes() { - const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com'); - return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'; +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.isGhes = isGhes; -//# sourceMappingURL=cacheUtils.js.map +exports.validateFilePath = validateFilePath; +//# sourceMappingURL=path-and-artifact-name-validation.js.map /***/ }), -/***/ 5538: -/***/ ((__unused_webpack_module, exports) => { +/***/ 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 })); -var CacheFilename; -(function (CacheFilename) { - CacheFilename["Gzip"] = "cache.tgz"; - CacheFilename["Zstd"] = "cache.tzst"; -})(CacheFilename = exports.CacheFilename || (exports.CacheFilename = {})); -var CompressionMethod; -(function (CompressionMethod) { - CompressionMethod["Gzip"] = "gzip"; - // Long range mode was added to zstd in v1.3.2. - // This enum is for earlier version of zstd that does not have --long support - CompressionMethod["ZstdWithoutLong"] = "zstd-without-long"; - CompressionMethod["Zstd"] = "zstd"; -})(CompressionMethod = exports.CompressionMethod || (exports.CompressionMethod = {})); -// The default number of retry attempts. -exports.DefaultRetryAttempts = 2; -// The default delay in milliseconds between retry attempts. -exports.DefaultRetryDelay = 5000; -// Socket timeout in milliseconds during download. If no traffic is received -// over the socket during this period, the socket is destroyed and the download -// is aborted. -exports.SocketTimeout = 5000; -//# sourceMappingURL=constants.js.map +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.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 /***/ }), -/***/ 1196: +/***/ 42578: /***/ (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) { @@ -2825,231 +3542,320 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __importStar(__nccwpck_require__(7334)); -const http_client_1 = __nccwpck_require__(7820); -const storage_blob_1 = __nccwpck_require__(9900); -const buffer = __importStar(__nccwpck_require__(4300)); -const fs = __importStar(__nccwpck_require__(7147)); -const stream = __importStar(__nccwpck_require__(2781)); -const util = __importStar(__nccwpck_require__(3837)); -const utils = __importStar(__nccwpck_require__(5406)); -const constants_1 = __nccwpck_require__(5538); -const requestUtils_1 = __nccwpck_require__(8868); -/** - * Pipes the body of a HTTP response to a stream - * - * @param response the HTTP response - * @param output the writable stream - */ -function pipeResponseToStream(response, output) { +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 pipeline = util.promisify(stream.pipeline); - yield pipeline(response.message, output); - }); -} -/** - * Class for tracking the download state and displaying stats. - */ -class DownloadProgress { - constructor(contentLength) { - this.contentLength = contentLength; - this.segmentIndex = 0; - this.segmentSize = 0; - this.segmentOffset = 0; - this.receivedBytes = 0; - this.displayedComplete = false; - this.startTime = Date.now(); - } - /** - * Progress to the next segment. Only call this method when the previous segment - * is complete. - * - * @param segmentSize the length of the next segment - */ - nextSegment(segmentSize) { - this.segmentOffset = this.segmentOffset + this.segmentSize; - this.segmentIndex = this.segmentIndex + 1; - this.segmentSize = segmentSize; - this.receivedBytes = 0; - core.debug(`Downloading segment at offset ${this.segmentOffset} with length ${this.segmentSize}...`); - } - /** - * Sets the number of bytes received for the current segment. - * - * @param receivedBytes the number of bytes received - */ - setReceivedBytes(receivedBytes) { - this.receivedBytes = receivedBytes; - } - /** - * Returns the total number of bytes transferred. - */ - getTransferredBytes() { - return this.segmentOffset + this.receivedBytes; - } - /** - * Returns true if the download is complete. - */ - isDone() { - return this.getTransferredBytes() === this.contentLength; - } - /** - * Prints the current download stats. Once the download completes, this will print one - * last line and then stop. - */ - display() { - if (this.displayedComplete) { - return; + (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}` + }); } - const transferredBytes = this.segmentOffset + this.receivedBytes; - const percentage = (100 * (transferredBytes / this.contentLength)).toFixed(1); - const elapsedTime = Date.now() - this.startTime; - const downloadSpeed = (transferredBytes / - (1024 * 1024) / - (elapsedTime / 1000)).toFixed(1); - core.info(`Received ${transferredBytes} of ${this.contentLength} (${percentage}%), ${downloadSpeed} MBs/sec`); - if (this.isDone()) { - this.displayedComplete = true; + 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'); } - } - /** - * Returns a function used to handle TransferProgressEvents. - */ - onProgress() { - return (progress) => { - this.setReceivedBytes(progress.loadedBytes); + const artifactId = BigInt(finalizeArtifactResp.artifactId); + core.info(`Artifact ${name}.zip successfully finalized. Artifact ID ${artifactId}`); + return { + size: uploadResult.uploadSize, + id: Number(artifactId) }; + }); +} +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]; } }; } - /** - * Starts the timer that displays the stats. - * - * @param delayInMs the delay between each write - */ - startDisplayTimer(delayInMs = 1000) { - const displayCallback = () => { - this.display(); - if (!this.isDone()) { - this.timeoutHandle = setTimeout(displayCallback, delayInMs); - } - }; - this.timeoutHandle = setTimeout(displayCallback, delayInMs); + 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`); } - /** - * Stops the timer that displays the stats. As this typically indicates the download - * is complete, this will display one last line, unless the last line has already - * been written. - */ - stopDisplayTimer() { - if (this.timeoutHandle) { - clearTimeout(this.timeoutHandle); - this.timeoutHandle = undefined; - } - this.display(); + 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.DownloadProgress = DownloadProgress; +exports.validateRootDirectory = validateRootDirectory; /** - * Download the cache using the Actions toolkit http-client - * - * @param archiveLocation the URL for the cache - * @param archivePath the local path where the cache is saved + * 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 downloadCacheHttpClient(archiveLocation, archivePath) { - return __awaiter(this, void 0, void 0, function* () { - const writeStream = fs.createWriteStream(archivePath); - const httpClient = new http_client_1.HttpClient('actions/cache'); - const downloadResponse = yield requestUtils_1.retryHttpClientResponse('downloadCache', () => __awaiter(this, void 0, void 0, function* () { return httpClient.get(archiveLocation); })); - // Abort download if no traffic received over the socket. - downloadResponse.message.socket.setTimeout(constants_1.SocketTimeout, () => { - downloadResponse.message.destroy(); - core.debug(`Aborting download, socket timed out after ${constants_1.SocketTimeout} ms`); - }); - yield pipeResponseToStream(downloadResponse, writeStream); - // Validate download size. - const contentLengthHeader = downloadResponse.message.headers['content-length']; - if (contentLengthHeader) { - const expectedLength = parseInt(contentLengthHeader); - const actualLength = utils.getArchiveFileSizeInBytes(archivePath); - if (actualLength !== expectedLength) { - throw new Error(`Incomplete download. Expected file size: ${expectedLength}, actual file size: ${actualLength}`); +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('Unable to validate download, no Content-Length header'); + // Empty directory + const directoryPath = file.replace(rootDirectory, ''); + (0, path_and_artifact_name_validation_1.validateFilePath)(directoryPath); + specification.push({ + sourcePath: null, + destinationPath: directoryPath + }); } + } + return specification; +} +exports.getUploadZipSpecification = getUploadZipSpecification; +//# sourceMappingURL=upload-zip-specification.js.map + +/***/ }), + +/***/ 69186: +/***/ (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) { + 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.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 + }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + _transform(chunk, enc, cb) { + cb(null, chunk); + } } -exports.downloadCacheHttpClient = downloadCacheHttpClient; -/** - * Download the cache using the Azure Storage SDK. Only call this method if the - * URL points to an Azure Storage endpoint. - * - * @param archiveLocation the URL for the cache - * @param archivePath the local path where the cache is saved - * @param options the download options with the defaults set - */ -function downloadCacheStorageSDK(archiveLocation, archivePath, options) { - var _a; +exports.ZipUploadStream = ZipUploadStream; +function createZipUploadStream(uploadSpecification, compressionLevel = exports.DEFAULT_COMPRESSION_LEVEL) { return __awaiter(this, void 0, void 0, function* () { - const client = new storage_blob_1.BlockBlobClient(archiveLocation, undefined, { - retryOptions: { - // Override the timeout used when downloading each 4 MB chunk - // The default is 2 min / MB, which is way too slow - tryTimeoutInMs: options.timeoutInMs - } + core.debug(`Creating Artifact archive with compressionLevel: ${compressionLevel}`); + const zip = archiver.create('zip', { + highWaterMark: (0, config_1.getUploadChunkSize)(), + zlib: { level: compressionLevel } }); - const properties = yield client.getProperties(); - const contentLength = (_a = properties.contentLength) !== null && _a !== void 0 ? _a : -1; - if (contentLength < 0) { - // We should never hit this condition, but just in case fall back to downloading the - // file as one large stream - core.debug('Unable to determine content length, downloading file with http-client...'); - yield downloadCacheHttpClient(archiveLocation, archivePath); - } - else { - // Use downloadToBuffer for faster downloads, since internally it splits the - // file into 4 MB chunks which can then be parallelized and retried independently - // - // If the file exceeds the buffer maximum length (~1 GB on 32-bit systems and ~2 GB - // on 64-bit systems), split the download into multiple segments - // ~2 GB = 2147483647, beyond this, we start getting out of range error. So, capping it accordingly. - const maxSegmentSize = Math.min(2147483647, buffer.constants.MAX_LENGTH); - const downloadProgress = new DownloadProgress(contentLength); - const fd = fs.openSync(archivePath, 'w'); - try { - downloadProgress.startDisplayTimer(); - while (!downloadProgress.isDone()) { - const segmentStart = downloadProgress.segmentOffset + downloadProgress.segmentSize; - const segmentSize = Math.min(maxSegmentSize, contentLength - segmentStart); - downloadProgress.nextSegment(segmentSize); - const result = yield client.downloadToBuffer(segmentStart, segmentSize, { - concurrency: options.downloadConcurrency, - onProgress: downloadProgress.onProgress() - }); - fs.writeFileSync(fd, result); - } + // 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 + }); } - finally { - downloadProgress.stopDisplayTimer(); - fs.closeSync(fd); + else { + // Add a directory to the zip + zip.append('', { name: file.destinationPath }); } } + 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.downloadCacheStorageSDK = downloadCacheStorageSDK; -//# sourceMappingURL=downloadUtils.js.map +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); + } + 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 /***/ }), -/***/ 8868: +/***/ 27799: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -3071,112 +3877,178 @@ var __importStar = (this && this.__importStar) || function (mod) { return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __importStar(__nccwpck_require__(7334)); -const http_client_1 = __nccwpck_require__(7820); -const constants_1 = __nccwpck_require__(5538); -function isSuccessStatusCode(statusCode) { - if (!statusCode) { - return false; +const core = __importStar(__nccwpck_require__(42186)); +const path = __importStar(__nccwpck_require__(71017)); +const utils = __importStar(__nccwpck_require__(91518)); +const cacheHttpClient = __importStar(__nccwpck_require__(98245)); +const tar_1 = __nccwpck_require__(56490); +class ValidationError extends Error { + constructor(message) { + super(message); + this.name = 'ValidationError'; + Object.setPrototypeOf(this, ValidationError.prototype); } - return statusCode >= 200 && statusCode < 300; } -exports.isSuccessStatusCode = isSuccessStatusCode; -function isServerErrorStatusCode(statusCode) { - if (!statusCode) { - return true; +exports.ValidationError = ValidationError; +class ReserveCacheError extends Error { + constructor(message) { + super(message); + this.name = 'ReserveCacheError'; + Object.setPrototypeOf(this, ReserveCacheError.prototype); } - return statusCode >= 500; } -exports.isServerErrorStatusCode = isServerErrorStatusCode; -function isRetryableStatusCode(statusCode) { - if (!statusCode) { - return false; +exports.ReserveCacheError = ReserveCacheError; +function checkPaths(paths) { + if (!paths || paths.length === 0) { + throw new ValidationError(`Path Validation Error: At least one directory or file path is required`); } - const retryableStatusCodes = [ - http_client_1.HttpCodes.BadGateway, - http_client_1.HttpCodes.ServiceUnavailable, - http_client_1.HttpCodes.GatewayTimeout - ]; - return retryableStatusCodes.includes(statusCode); } -exports.isRetryableStatusCode = isRetryableStatusCode; -function sleep(milliseconds) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise(resolve => setTimeout(resolve, milliseconds)); - }); +function checkKey(key) { + if (key.length > 512) { + throw new ValidationError(`Key Validation Error: ${key} cannot be larger than 512 characters.`); + } + const regex = /^[^,]*$/; + if (!regex.test(key)) { + throw new ValidationError(`Key Validation Error: ${key} cannot contain commas.`); + } } -function retry(name, method, getStatusCode, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay, onError = undefined) { +/** + * isFeatureAvailable to check the presence of Actions cache service + * + * @returns boolean return true if Actions cache service feature is available, otherwise false + */ +function isFeatureAvailable() { + return !!process.env['ACTIONS_CACHE_URL']; +} +exports.isFeatureAvailable = isFeatureAvailable; +/** + * Restores cache from keys + * + * @param paths a list of file paths to restore from the cache + * @param primaryKey an explicit key for restoring the cache + * @param restoreKeys an optional ordered list of keys to use for restoring the cache if no cache hit occurred for key + * @param downloadOptions cache download options + * @returns string returns the key for the cache hit, otherwise returns undefined + */ +function restoreCache(paths, primaryKey, restoreKeys, options) { return __awaiter(this, void 0, void 0, function* () { - let errorMessage = ''; - let attempt = 1; - while (attempt <= maxAttempts) { - let response = undefined; - let statusCode = undefined; - let isRetryable = false; + checkPaths(paths); + restoreKeys = restoreKeys || []; + const keys = [primaryKey, ...restoreKeys]; + core.debug('Resolved Keys:'); + core.debug(JSON.stringify(keys)); + if (keys.length > 10) { + throw new ValidationError(`Key Validation Error: Keys are limited to a maximum of 10.`); + } + for (const key of keys) { + checkKey(key); + } + const compressionMethod = yield utils.getCompressionMethod(); + // path are needed to compute version + const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, { + compressionMethod + }); + if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) { + // Cache not found + return undefined; + } + const archivePath = path.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); + core.debug(`Archive Path: ${archivePath}`); + try { + // Download the cache from the cache entry + yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options); + if (core.isDebug()) { + yield tar_1.listTar(archivePath, compressionMethod); + } + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); + yield tar_1.extractTar(archivePath, compressionMethod); + core.info('Cache restored successfully'); + } + finally { + // Try to delete the archive to save space try { - response = yield method(); + yield utils.unlinkFile(archivePath); } catch (error) { - if (onError) { - response = onError(error); - } - isRetryable = true; - errorMessage = error.message; - } - if (response) { - statusCode = getStatusCode(response); - if (!isServerErrorStatusCode(statusCode)) { - return response; - } - } - if (statusCode) { - isRetryable = isRetryableStatusCode(statusCode); - errorMessage = `Cache service responded with ${statusCode}`; - } - core.debug(`${name} - Attempt ${attempt} of ${maxAttempts} failed with error: ${errorMessage}`); - if (!isRetryable) { - core.debug(`${name} - Error is not retryable`); - break; + core.debug(`Failed to delete archive: ${error}`); } - yield sleep(delay); - attempt++; } - throw Error(`${name} failed: ${errorMessage}`); + return cacheEntry.cacheKey; }); } -exports.retry = retry; -function retryTypedResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay) { +exports.restoreCache = restoreCache; +/** + * Saves a list of files with the specified key + * + * @param paths a list of file paths to be cached + * @param key an explicit key for restoring the cache + * @param options cache upload options + * @returns number returns cacheId if the cache was saved successfully and throws an error if save fails + */ +function saveCache(paths, key, options) { + var _a, _b, _c, _d, _e; return __awaiter(this, void 0, void 0, function* () { - return yield retry(name, method, (response) => response.statusCode, maxAttempts, delay, - // If the error object contains the statusCode property, extract it and return - // an TypedResponse so it can be processed by the retry logic. - (error) => { - if (error instanceof http_client_1.HttpClientError) { - return { - statusCode: error.statusCode, - result: null, - headers: {}, - error - }; + checkPaths(paths); + checkKey(key); + const compressionMethod = yield utils.getCompressionMethod(); + let cacheId = null; + const cachePaths = yield utils.resolvePaths(paths); + core.debug('Cache Paths:'); + core.debug(`${JSON.stringify(cachePaths)}`); + if (cachePaths.length === 0) { + throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); + } + const archiveFolder = yield utils.createTempDirectory(); + const archivePath = path.join(archiveFolder, utils.getCacheFileName(compressionMethod)); + core.debug(`Archive Path: ${archivePath}`); + try { + yield tar_1.createTar(archiveFolder, cachePaths, compressionMethod); + if (core.isDebug()) { + yield tar_1.listTar(archivePath, compressionMethod); + } + const fileSizeLimit = 10 * 1024 * 1024 * 1024; // 10GB per repo limit + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core.debug(`File Size: ${archiveFileSize}`); + // For GHES, this check will take place in ReserveCache API with enterprise file size limit + if (archiveFileSize > fileSizeLimit && !utils.isGhes()) { + throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`); + } + core.debug('Reserving Cache'); + const reserveCacheResponse = yield cacheHttpClient.reserveCache(key, paths, { + compressionMethod, + cacheSize: archiveFileSize + }); + if ((_a = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _a === void 0 ? void 0 : _a.cacheId) { + cacheId = (_b = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _b === void 0 ? void 0 : _b.cacheId; + } + else if ((reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.statusCode) === 400) { + throw new Error((_d = (_c = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : `Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the data cap limit, not saving cache.`); } else { - return undefined; + throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache. More details: ${(_e = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.error) === null || _e === void 0 ? void 0 : _e.message}`); } - }); - }); -} -exports.retryTypedResponse = retryTypedResponse; -function retryHttpClientResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay) { - return __awaiter(this, void 0, void 0, function* () { - return yield retry(name, method, (response) => response.message.statusCode, maxAttempts, delay); + core.debug(`Saving Cache (ID: ${cacheId})`); + yield cacheHttpClient.saveCache(cacheId, archivePath, options); + } + finally { + // Try to delete the archive to save space + try { + yield utils.unlinkFile(archivePath); + } + catch (error) { + core.debug(`Failed to delete archive: ${error}`); + } + } + return cacheId; }); } -exports.retryHttpClientResponse = retryHttpClientResponse; -//# sourceMappingURL=requestUtils.js.map +exports.saveCache = saveCache; +//# sourceMappingURL=cache.js.map /***/ }), -/***/ 9403: +/***/ 98245: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -3198,160 +4070,225 @@ var __importStar = (this && this.__importStar) || function (mod) { return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -const exec_1 = __nccwpck_require__(6703); -const io = __importStar(__nccwpck_require__(1608)); -const fs_1 = __nccwpck_require__(7147); -const path = __importStar(__nccwpck_require__(1017)); -const utils = __importStar(__nccwpck_require__(5406)); -const constants_1 = __nccwpck_require__(5538); -function getTarPath(args, compressionMethod) { - return __awaiter(this, void 0, void 0, function* () { - switch (process.platform) { - case 'win32': { - const systemTar = `${process.env['windir']}\\System32\\tar.exe`; - if (compressionMethod !== constants_1.CompressionMethod.Gzip) { - // We only use zstandard compression on windows when gnu tar is installed due to - // a bug with compressing large files with bsdtar + zstd - args.push('--force-local'); - } - else if (fs_1.existsSync(systemTar)) { - return systemTar; - } - else if (yield utils.isGnuTarInstalled()) { - args.push('--force-local'); - } - break; - } - case 'darwin': { - const gnuTar = yield io.which('gtar', false); - if (gnuTar) { - // fix permission denied errors when extracting BSD tar archive with GNU tar - https://github.com/actions/cache/issues/527 - args.push('--delay-directory-restore'); - return gnuTar; - } - break; - } - default: - break; +const core = __importStar(__nccwpck_require__(42186)); +const http_client_1 = __nccwpck_require__(96255); +const auth_1 = __nccwpck_require__(35526); +const crypto = __importStar(__nccwpck_require__(6113)); +const fs = __importStar(__nccwpck_require__(57147)); +const url_1 = __nccwpck_require__(57310); +const utils = __importStar(__nccwpck_require__(91518)); +const constants_1 = __nccwpck_require__(88840); +const downloadUtils_1 = __nccwpck_require__(55500); +const options_1 = __nccwpck_require__(76215); +const requestUtils_1 = __nccwpck_require__(13981); +const versionSalt = '1.0'; +function getCacheApiUrl(resource) { + const baseUrl = process.env['ACTIONS_CACHE_URL'] || ''; + if (!baseUrl) { + throw new Error('Cache Service Url not found, unable to restore cache.'); + } + const url = `${baseUrl}_apis/artifactcache/${resource}`; + core.debug(`Resource Url: ${url}`); + return url; +} +function createAcceptHeader(type, apiVersion) { + return `${type};api-version=${apiVersion}`; +} +function getRequestOptions() { + const requestOptions = { + headers: { + Accept: createAcceptHeader('application/json', '6.0-preview.1') } - return yield io.which('tar', true); + }; + return requestOptions; +} +function createHttpClient() { + const token = process.env['ACTIONS_RUNTIME_TOKEN'] || ''; + const bearerCredentialHandler = new auth_1.BearerCredentialHandler(token); + return new http_client_1.HttpClient('actions/cache', [bearerCredentialHandler], getRequestOptions()); +} +function getCacheVersion(paths, compressionMethod) { + const components = paths.concat(!compressionMethod || compressionMethod === constants_1.CompressionMethod.Gzip + ? [] + : [compressionMethod]); + // Add salt to cache version to support breaking changes in cache entry + components.push(versionSalt); + return crypto + .createHash('sha256') + .update(components.join('|')) + .digest('hex'); +} +exports.getCacheVersion = getCacheVersion; +function getCacheEntry(keys, paths, options) { + return __awaiter(this, void 0, void 0, function* () { + const httpClient = createHttpClient(); + const version = getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod); + const resource = `cache?keys=${encodeURIComponent(keys.join(','))}&version=${version}`; + const response = yield requestUtils_1.retryTypedResponse('getCacheEntry', () => __awaiter(this, void 0, void 0, function* () { return httpClient.getJson(getCacheApiUrl(resource)); })); + if (response.statusCode === 204) { + return null; + } + if (!requestUtils_1.isSuccessStatusCode(response.statusCode)) { + throw new Error(`Cache service responded with ${response.statusCode}`); + } + const cacheResult = response.result; + const cacheDownloadUrl = cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.archiveLocation; + if (!cacheDownloadUrl) { + throw new Error('Cache not found.'); + } + core.setSecret(cacheDownloadUrl); + core.debug(`Cache Result:`); + core.debug(JSON.stringify(cacheResult)); + return cacheResult; }); } -function execTar(args, compressionMethod, cwd) { +exports.getCacheEntry = getCacheEntry; +function downloadCache(archiveLocation, archivePath, options) { return __awaiter(this, void 0, void 0, function* () { - try { - yield exec_1.exec(`"${yield getTarPath(args, compressionMethod)}"`, args, { cwd }); + const archiveUrl = new url_1.URL(archiveLocation); + const downloadOptions = options_1.getDownloadOptions(options); + if (downloadOptions.useAzureSdk && + archiveUrl.hostname.endsWith('.blob.core.windows.net')) { + // Use Azure storage SDK to download caches hosted on Azure to improve speed and reliability. + yield downloadUtils_1.downloadCacheStorageSDK(archiveLocation, archivePath, downloadOptions); } - catch (error) { - throw new Error(`Tar failed with error: ${error === null || error === void 0 ? void 0 : error.message}`); + else { + // Otherwise, download using the Actions http-client. + yield downloadUtils_1.downloadCacheHttpClient(archiveLocation, archivePath); } }); } -function getWorkingDirectory() { - var _a; - return (_a = process.env['GITHUB_WORKSPACE']) !== null && _a !== void 0 ? _a : process.cwd(); +exports.downloadCache = downloadCache; +// Reserve Cache +function reserveCache(key, paths, options) { + return __awaiter(this, void 0, void 0, function* () { + const httpClient = createHttpClient(); + const version = getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod); + const reserveCacheRequest = { + key, + version, + cacheSize: options === null || options === void 0 ? void 0 : options.cacheSize + }; + const response = yield requestUtils_1.retryTypedResponse('reserveCache', () => __awaiter(this, void 0, void 0, function* () { + return httpClient.postJson(getCacheApiUrl('caches'), reserveCacheRequest); + })); + return response; + }); } -function extractTar(archivePath, compressionMethod) { +exports.reserveCache = reserveCache; +function getContentRange(start, end) { + // Format: `bytes start-end/filesize + // start and end are inclusive + // filesize can be * + // For a 200 byte chunk starting at byte 0: + // Content-Range: bytes 0-199/* + return `bytes ${start}-${end}/*`; +} +function uploadChunk(httpClient, resourceUrl, openStream, start, end) { return __awaiter(this, void 0, void 0, function* () { - // Create directory to extract tar into - const workingDirectory = getWorkingDirectory(); - yield io.mkdirP(workingDirectory); - // --d: Decompress. - // --long=#: Enables long distance matching with # bits. Maximum is 30 (1GB) on 32-bit OS and 31 (2GB) on 64-bit. - // Using 30 here because we also support 32-bit self-hosted runners. - function getCompressionProgram() { - switch (compressionMethod) { - case constants_1.CompressionMethod.Zstd: - return ['--use-compress-program', 'zstd -d --long=30']; - case constants_1.CompressionMethod.ZstdWithoutLong: - return ['--use-compress-program', 'zstd -d']; - default: - return ['-z']; - } + core.debug(`Uploading chunk of size ${end - + start + + 1} bytes at offset ${start} with content range: ${getContentRange(start, end)}`); + const additionalHeaders = { + 'Content-Type': 'application/octet-stream', + 'Content-Range': getContentRange(start, end) + }; + const uploadChunkResponse = yield requestUtils_1.retryHttpClientResponse(`uploadChunk (start: ${start}, end: ${end})`, () => __awaiter(this, void 0, void 0, function* () { + return httpClient.sendStream('PATCH', resourceUrl, openStream(), additionalHeaders); + })); + if (!requestUtils_1.isSuccessStatusCode(uploadChunkResponse.message.statusCode)) { + throw new Error(`Cache service responded with ${uploadChunkResponse.message.statusCode} during upload chunk.`); } - const args = [ - ...getCompressionProgram(), - '-xf', - archivePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), - '-P', - '-C', - workingDirectory.replace(new RegExp(`\\${path.sep}`, 'g'), '/') - ]; - yield execTar(args, compressionMethod); }); } -exports.extractTar = extractTar; -function createTar(archiveFolder, sourceDirectories, compressionMethod) { +function uploadFile(httpClient, cacheId, archivePath, options) { return __awaiter(this, void 0, void 0, function* () { - // Write source directories to manifest.txt to avoid command length limits - const manifestFilename = 'manifest.txt'; - const cacheFileName = utils.getCacheFileName(compressionMethod); - fs_1.writeFileSync(path.join(archiveFolder, manifestFilename), sourceDirectories.join('\n')); - const workingDirectory = getWorkingDirectory(); - // -T#: Compress using # working thread. If # is 0, attempt to detect and use the number of physical CPU cores. - // --long=#: Enables long distance matching with # bits. Maximum is 30 (1GB) on 32-bit OS and 31 (2GB) on 64-bit. - // Using 30 here because we also support 32-bit self-hosted runners. - // Long range mode is added to zstd in v1.3.2 release, so we will not use --long in older version of zstd. - function getCompressionProgram() { - switch (compressionMethod) { - case constants_1.CompressionMethod.Zstd: - return ['--use-compress-program', 'zstd -T0 --long=30']; - case constants_1.CompressionMethod.ZstdWithoutLong: - return ['--use-compress-program', 'zstd -T0']; - default: - return ['-z']; - } + // Upload Chunks + const fileSize = utils.getArchiveFileSizeInBytes(archivePath); + const resourceUrl = getCacheApiUrl(`caches/${cacheId.toString()}`); + const fd = fs.openSync(archivePath, 'r'); + const uploadOptions = options_1.getUploadOptions(options); + const concurrency = utils.assertDefined('uploadConcurrency', uploadOptions.uploadConcurrency); + const maxChunkSize = utils.assertDefined('uploadChunkSize', uploadOptions.uploadChunkSize); + const parallelUploads = [...new Array(concurrency).keys()]; + core.debug('Awaiting all uploads'); + let offset = 0; + try { + yield Promise.all(parallelUploads.map(() => __awaiter(this, void 0, void 0, function* () { + while (offset < fileSize) { + const chunkSize = Math.min(fileSize - offset, maxChunkSize); + const start = offset; + const end = offset + chunkSize - 1; + offset += maxChunkSize; + yield uploadChunk(httpClient, resourceUrl, () => fs + .createReadStream(archivePath, { + fd, + start, + end, + autoClose: false + }) + .on('error', error => { + throw new Error(`Cache upload failed because file read failed with ${error.message}`); + }), start, end); + } + }))); } - const args = [ - '--posix', - ...getCompressionProgram(), - '-cf', - cacheFileName.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), - '-P', - '-C', - workingDirectory.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), - '--files-from', - manifestFilename - ]; - yield execTar(args, compressionMethod, archiveFolder); + finally { + fs.closeSync(fd); + } + return; }); } -exports.createTar = createTar; -function listTar(archivePath, compressionMethod) { +function commitCache(httpClient, cacheId, filesize) { return __awaiter(this, void 0, void 0, function* () { - // --d: Decompress. - // --long=#: Enables long distance matching with # bits. - // Maximum is 30 (1GB) on 32-bit OS and 31 (2GB) on 64-bit. - // Using 30 here because we also support 32-bit self-hosted runners. - function getCompressionProgram() { - switch (compressionMethod) { - case constants_1.CompressionMethod.Zstd: - return ['--use-compress-program', 'zstd -d --long=30']; - case constants_1.CompressionMethod.ZstdWithoutLong: - return ['--use-compress-program', 'zstd -d']; - default: - return ['-z']; - } + const commitCacheRequest = { size: filesize }; + return yield requestUtils_1.retryTypedResponse('commitCache', () => __awaiter(this, void 0, void 0, function* () { + return httpClient.postJson(getCacheApiUrl(`caches/${cacheId.toString()}`), commitCacheRequest); + })); + }); +} +function saveCache(cacheId, archivePath, options) { + return __awaiter(this, void 0, void 0, function* () { + const httpClient = createHttpClient(); + core.debug('Upload cache'); + yield uploadFile(httpClient, cacheId, archivePath, options); + // Commit Cache + core.debug('Commiting cache'); + const cacheSize = utils.getArchiveFileSizeInBytes(archivePath); + core.info(`Cache Size: ~${Math.round(cacheSize / (1024 * 1024))} MB (${cacheSize} B)`); + const commitCacheResponse = yield commitCache(httpClient, cacheId, cacheSize); + if (!requestUtils_1.isSuccessStatusCode(commitCacheResponse.statusCode)) { + throw new Error(`Cache service responded with ${commitCacheResponse.statusCode} during commit cache.`); } - const args = [ - ...getCompressionProgram(), - '-tf', - archivePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), - '-P' - ]; - yield execTar(args, compressionMethod); + core.info('Cache saved successfully'); }); } -exports.listTar = listTar; -//# sourceMappingURL=tar.js.map +exports.saveCache = saveCache; +//# sourceMappingURL=cacheHttpClient.js.map /***/ }), -/***/ 1141: +/***/ 91518: /***/ (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()); + }); +}; +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 __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; @@ -3360,185 +4297,195 @@ var __importStar = (this && this.__importStar) || function (mod) { return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __importStar(__nccwpck_require__(7334)); -/** - * Returns a copy of the upload options with defaults filled in. - * - * @param copy the original upload options - */ -function getUploadOptions(copy) { - const result = { - uploadConcurrency: 4, - uploadChunkSize: 32 * 1024 * 1024 - }; - if (copy) { - if (typeof copy.uploadConcurrency === 'number') { - result.uploadConcurrency = copy.uploadConcurrency; +const core = __importStar(__nccwpck_require__(42186)); +const exec = __importStar(__nccwpck_require__(71514)); +const glob = __importStar(__nccwpck_require__(28090)); +const io = __importStar(__nccwpck_require__(47351)); +const fs = __importStar(__nccwpck_require__(57147)); +const path = __importStar(__nccwpck_require__(71017)); +const semver = __importStar(__nccwpck_require__(85911)); +const util = __importStar(__nccwpck_require__(73837)); +const uuid_1 = __nccwpck_require__(2155); +const constants_1 = __nccwpck_require__(88840); +// From https://github.com/actions/toolkit/blob/main/packages/tool-cache/src/tool-cache.ts#L23 +function createTempDirectory() { + return __awaiter(this, void 0, void 0, function* () { + const IS_WINDOWS = process.platform === 'win32'; + let tempDirectory = process.env['RUNNER_TEMP'] || ''; + if (!tempDirectory) { + let baseLocation; + if (IS_WINDOWS) { + // On Windows use the USERPROFILE env variable + baseLocation = process.env['USERPROFILE'] || 'C:\\'; + } + else { + if (process.platform === 'darwin') { + baseLocation = '/Users'; + } + else { + baseLocation = '/home'; + } + } + tempDirectory = path.join(baseLocation, 'actions', 'temp'); } - if (typeof copy.uploadChunkSize === 'number') { - result.uploadChunkSize = copy.uploadChunkSize; + const dest = path.join(tempDirectory, uuid_1.v4()); + yield io.mkdirP(dest); + return dest; + }); +} +exports.createTempDirectory = createTempDirectory; +function getArchiveFileSizeInBytes(filePath) { + return fs.statSync(filePath).size; +} +exports.getArchiveFileSizeInBytes = getArchiveFileSizeInBytes; +function resolvePaths(patterns) { + var e_1, _a; + var _b; + return __awaiter(this, void 0, void 0, function* () { + const paths = []; + const workspace = (_b = process.env['GITHUB_WORKSPACE']) !== null && _b !== void 0 ? _b : process.cwd(); + const globber = yield glob.create(patterns.join('\n'), { + implicitDescendants: false + }); + try { + for (var _c = __asyncValues(globber.globGenerator()), _d; _d = yield _c.next(), !_d.done;) { + const file = _d.value; + const relativeFile = path + .relative(workspace, file) + .replace(new RegExp(`\\${path.sep}`, 'g'), '/'); + core.debug(`Matched: ${relativeFile}`); + // Paths are made relative so the tar entries are all relative to the root of the workspace. + paths.push(`${relativeFile}`); + } } - } - core.debug(`Upload concurrency: ${result.uploadConcurrency}`); - core.debug(`Upload chunk size: ${result.uploadChunkSize}`); - return result; + 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; } + } + return paths; + }); } -exports.getUploadOptions = getUploadOptions; -/** - * Returns a copy of the download options with defaults filled in. - * - * @param copy the original download options - */ -function getDownloadOptions(copy) { - const result = { - useAzureSdk: true, - downloadConcurrency: 8, - timeoutInMs: 30000 - }; - if (copy) { - if (typeof copy.useAzureSdk === 'boolean') { - result.useAzureSdk = copy.useAzureSdk; +exports.resolvePaths = resolvePaths; +function unlinkFile(filePath) { + return __awaiter(this, void 0, void 0, function* () { + return util.promisify(fs.unlink)(filePath); + }); +} +exports.unlinkFile = unlinkFile; +function getVersion(app) { + return __awaiter(this, void 0, void 0, function* () { + core.debug(`Checking ${app} --version`); + let versionOutput = ''; + try { + yield exec.exec(`${app} --version`, [], { + ignoreReturnCode: true, + silent: true, + listeners: { + stdout: (data) => (versionOutput += data.toString()), + stderr: (data) => (versionOutput += data.toString()) + } + }); } - if (typeof copy.downloadConcurrency === 'number') { - result.downloadConcurrency = copy.downloadConcurrency; + catch (err) { + core.debug(err.message); } - if (typeof copy.timeoutInMs === 'number') { - result.timeoutInMs = copy.timeoutInMs; + versionOutput = versionOutput.trim(); + core.debug(versionOutput); + return versionOutput; + }); +} +// Use zstandard if possible to maximize cache performance +function getCompressionMethod() { + return __awaiter(this, void 0, void 0, function* () { + if (process.platform === 'win32' && !(yield isGnuTarInstalled())) { + // Disable zstd due to bug https://github.com/actions/cache/issues/301 + return constants_1.CompressionMethod.Gzip; + } + const versionOutput = yield getVersion('zstd'); + const version = semver.clean(versionOutput); + if (!versionOutput.toLowerCase().includes('zstd command line interface')) { + // zstd is not installed + return constants_1.CompressionMethod.Gzip; + } + else if (!version || semver.lt(version, 'v1.3.2')) { + // zstd is installed but using a version earlier than v1.3.2 + // v1.3.2 is required to use the `--long` options in zstd + return constants_1.CompressionMethod.ZstdWithoutLong; + } + else { + return constants_1.CompressionMethod.Zstd; } + }); +} +exports.getCompressionMethod = getCompressionMethod; +function getCacheFileName(compressionMethod) { + return compressionMethod === constants_1.CompressionMethod.Gzip + ? constants_1.CacheFilename.Gzip + : constants_1.CacheFilename.Zstd; +} +exports.getCacheFileName = getCacheFileName; +function isGnuTarInstalled() { + return __awaiter(this, void 0, void 0, function* () { + const versionOutput = yield getVersion('tar'); + return versionOutput.toLowerCase().includes('gnu tar'); + }); +} +exports.isGnuTarInstalled = isGnuTarInstalled; +function assertDefined(name, value) { + if (value === undefined) { + throw Error(`Expected ${name} but value was undefiend`); } - core.debug(`Use Azure SDK: ${result.useAzureSdk}`); - core.debug(`Download concurrency: ${result.downloadConcurrency}`); - core.debug(`Request timeout (ms): ${result.timeoutInMs}`); - return result; + return value; } -exports.getDownloadOptions = getDownloadOptions; -//# sourceMappingURL=options.js.map +exports.assertDefined = assertDefined; +function isGhes() { + const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com'); + return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'; +} +exports.isGhes = isGhes; +//# sourceMappingURL=cacheUtils.js.map /***/ }), -/***/ 4897: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 88840: +/***/ ((__unused_webpack_module, exports) => { "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.issue = exports.issueCommand = void 0; -const os = __importStar(__nccwpck_require__(2037)); -const utils_1 = __nccwpck_require__(3704); -/** - * 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; - } - 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; - } -} -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 +var CacheFilename; +(function (CacheFilename) { + CacheFilename["Gzip"] = "cache.tgz"; + CacheFilename["Zstd"] = "cache.tzst"; +})(CacheFilename = exports.CacheFilename || (exports.CacheFilename = {})); +var CompressionMethod; +(function (CompressionMethod) { + CompressionMethod["Gzip"] = "gzip"; + // Long range mode was added to zstd in v1.3.2. + // This enum is for earlier version of zstd that does not have --long support + CompressionMethod["ZstdWithoutLong"] = "zstd-without-long"; + CompressionMethod["Zstd"] = "zstd"; +})(CompressionMethod = exports.CompressionMethod || (exports.CompressionMethod = {})); +// The default number of retry attempts. +exports.DefaultRetryAttempts = 2; +// The default delay in milliseconds between retry attempts. +exports.DefaultRetryDelay = 5000; +// Socket timeout in milliseconds during download. If no traffic is received +// over the socket during this period, the socket is destroyed and the download +// is aborted. +exports.SocketTimeout = 5000; +//# sourceMappingURL=constants.js.map /***/ }), -/***/ 7334: +/***/ 55500: /***/ (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) { @@ -3548,367 +4495,358 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; 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__(4897); -const file_command_1 = __nccwpck_require__(790); -const utils_1 = __nccwpck_require__(3704); -const os = __importStar(__nccwpck_require__(2037)); -const path = __importStar(__nccwpck_require__(1017)); -const uuid_1 = __nccwpck_require__(4216); -const oidc_utils_1 = __nccwpck_require__(3324); +const core = __importStar(__nccwpck_require__(42186)); +const http_client_1 = __nccwpck_require__(96255); +const storage_blob_1 = __nccwpck_require__(84100); +const buffer = __importStar(__nccwpck_require__(14300)); +const fs = __importStar(__nccwpck_require__(57147)); +const stream = __importStar(__nccwpck_require__(12781)); +const util = __importStar(__nccwpck_require__(73837)); +const utils = __importStar(__nccwpck_require__(91518)); +const constants_1 = __nccwpck_require__(88840); +const requestUtils_1 = __nccwpck_require__(13981); /** - * The code to exit an action + * Pipes the body of a HTTP response to a stream + * + * @param response the HTTP response + * @param output the writable stream */ -var ExitCode; -(function (ExitCode) { +function pipeResponseToStream(response, output) { + return __awaiter(this, void 0, void 0, function* () { + const pipeline = util.promisify(stream.pipeline); + yield pipeline(response.message, output); + }); +} +/** + * Class for tracking the download state and displaying stats. + */ +class DownloadProgress { + constructor(contentLength) { + this.contentLength = contentLength; + this.segmentIndex = 0; + this.segmentSize = 0; + this.segmentOffset = 0; + this.receivedBytes = 0; + this.displayedComplete = false; + this.startTime = Date.now(); + } /** - * A code indicating that the action was successful + * Progress to the next segment. Only call this method when the previous segment + * is complete. + * + * @param segmentSize the length of the next segment */ - ExitCode[ExitCode["Success"] = 0] = "Success"; + nextSegment(segmentSize) { + this.segmentOffset = this.segmentOffset + this.segmentSize; + this.segmentIndex = this.segmentIndex + 1; + this.segmentSize = segmentSize; + this.receivedBytes = 0; + core.debug(`Downloading segment at offset ${this.segmentOffset} with length ${this.segmentSize}...`); + } /** - * A code indicating that the action was a failure + * Sets the number of bytes received for the current segment. + * + * @param receivedBytes the number of bytes received */ - 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) { - const delimiter = `ghadelimiter_${uuid_1.v4()}`; - // 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 (name.includes(delimiter)) { - throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); - } - if (convertedVal.includes(delimiter)) { - throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); - } - const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`; - file_command_1.issueCommand('ENV', commandValue); + setReceivedBytes(receivedBytes) { + this.receivedBytes = receivedBytes; } - else { - command_1.issueCommand('set-env', { name }, convertedVal); + /** + * Returns the total number of bytes transferred. + */ + getTransferredBytes() { + return this.segmentOffset + this.receivedBytes; } -} -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.issueCommand('PATH', inputPath); + /** + * Returns true if the download is complete. + */ + isDone() { + return this.getTransferredBytes() === this.contentLength; } - else { - command_1.issueCommand('add-path', {}, inputPath); + /** + * Prints the current download stats. Once the download completes, this will print one + * last line and then stop. + */ + display() { + if (this.displayedComplete) { + return; + } + const transferredBytes = this.segmentOffset + this.receivedBytes; + const percentage = (100 * (transferredBytes / this.contentLength)).toFixed(1); + const elapsedTime = Date.now() - this.startTime; + const downloadSpeed = (transferredBytes / + (1024 * 1024) / + (elapsedTime / 1000)).toFixed(1); + core.info(`Received ${transferredBytes} of ${this.contentLength} (${percentage}%), ${downloadSpeed} MBs/sec`); + if (this.isDone()) { + this.displayedComplete = true; + } } - 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}`); + /** + * Returns a function used to handle TransferProgressEvents. + */ + onProgress() { + return (progress) => { + this.setReceivedBytes(progress.loadedBytes); + }; } - if (options && options.trimWhitespace === false) { - return val; + /** + * Starts the timer that displays the stats. + * + * @param delayInMs the delay between each write + */ + startDisplayTimer(delayInMs = 1000) { + const displayCallback = () => { + this.display(); + if (!this.isDone()) { + this.timeoutHandle = setTimeout(displayCallback, delayInMs); + } + }; + this.timeoutHandle = setTimeout(displayCallback, delayInMs); + } + /** + * Stops the timer that displays the stats. As this typically indicates the download + * is complete, this will display one last line, unless the last line has already + * been written. + */ + stopDisplayTimer() { + if (this.timeoutHandle) { + clearTimeout(this.timeoutHandle); + this.timeoutHandle = undefined; + } + this.display(); } - 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 !== ''); - return inputs; -} -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) { - process.stdout.write(os.EOL); - command_1.issueCommand('set-output', { name }, 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; +exports.DownloadProgress = DownloadProgress; /** - * Wrap an asynchronous function call in a group. - * - * Returns the same type as the function itself. + * Download the cache using the Actions toolkit http-client * - * @param name The name of the group - * @param fn The function to wrap in the group + * @param archiveLocation the URL for the cache + * @param archivePath the local path where the cache is saved */ -function group(name, fn) { +function downloadCacheHttpClient(archiveLocation, archivePath) { return __awaiter(this, void 0, void 0, function* () { - startGroup(name); - let result; - try { - result = yield fn(); + const writeStream = fs.createWriteStream(archivePath); + const httpClient = new http_client_1.HttpClient('actions/cache'); + const downloadResponse = yield requestUtils_1.retryHttpClientResponse('downloadCache', () => __awaiter(this, void 0, void 0, function* () { return httpClient.get(archiveLocation); })); + // Abort download if no traffic received over the socket. + downloadResponse.message.socket.setTimeout(constants_1.SocketTimeout, () => { + downloadResponse.message.destroy(); + core.debug(`Aborting download, socket timed out after ${constants_1.SocketTimeout} ms`); + }); + yield pipeResponseToStream(downloadResponse, writeStream); + // Validate download size. + const contentLengthHeader = downloadResponse.message.headers['content-length']; + if (contentLengthHeader) { + const expectedLength = parseInt(contentLengthHeader); + const actualLength = utils.getArchiveFileSizeInBytes(archivePath); + if (actualLength !== expectedLength) { + throw new Error(`Incomplete download. Expected file size: ${expectedLength}, actual file size: ${actualLength}`); + } } - finally { - endGroup(); + else { + core.debug('Unable to validate download, no Content-Length header'); } - 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) { - command_1.issueCommand('save-state', { name }, value); -} -exports.saveState = saveState; +exports.downloadCacheHttpClient = downloadCacheHttpClient; /** - * Gets the value of an state set by this action's main execution. + * Download the cache using the Azure Storage SDK. Only call this method if the + * URL points to an Azure Storage endpoint. * - * @param name name of the state to get - * @returns string + * @param archiveLocation the URL for the cache + * @param archivePath the local path where the cache is saved + * @param options the download options with the defaults set */ -function getState(name) { - return process.env[`STATE_${name}`] || ''; -} -exports.getState = getState; -function getIDToken(aud) { +function downloadCacheStorageSDK(archiveLocation, archivePath, options) { + var _a; return __awaiter(this, void 0, void 0, function* () { - return yield oidc_utils_1.OidcClient.getIDToken(aud); + const client = new storage_blob_1.BlockBlobClient(archiveLocation, undefined, { + retryOptions: { + // Override the timeout used when downloading each 4 MB chunk + // The default is 2 min / MB, which is way too slow + tryTimeoutInMs: options.timeoutInMs + } + }); + const properties = yield client.getProperties(); + const contentLength = (_a = properties.contentLength) !== null && _a !== void 0 ? _a : -1; + if (contentLength < 0) { + // We should never hit this condition, but just in case fall back to downloading the + // file as one large stream + core.debug('Unable to determine content length, downloading file with http-client...'); + yield downloadCacheHttpClient(archiveLocation, archivePath); + } + else { + // Use downloadToBuffer for faster downloads, since internally it splits the + // file into 4 MB chunks which can then be parallelized and retried independently + // + // If the file exceeds the buffer maximum length (~1 GB on 32-bit systems and ~2 GB + // on 64-bit systems), split the download into multiple segments + // ~2 GB = 2147483647, beyond this, we start getting out of range error. So, capping it accordingly. + const maxSegmentSize = Math.min(2147483647, buffer.constants.MAX_LENGTH); + const downloadProgress = new DownloadProgress(contentLength); + const fd = fs.openSync(archivePath, 'w'); + try { + downloadProgress.startDisplayTimer(); + while (!downloadProgress.isDone()) { + const segmentStart = downloadProgress.segmentOffset + downloadProgress.segmentSize; + const segmentSize = Math.min(maxSegmentSize, contentLength - segmentStart); + downloadProgress.nextSegment(segmentSize); + const result = yield client.downloadToBuffer(segmentStart, segmentSize, { + concurrency: options.downloadConcurrency, + onProgress: downloadProgress.onProgress() + }); + fs.writeFileSync(fd, result); + } + } + finally { + downloadProgress.stopDisplayTimer(); + fs.closeSync(fd); + } + } }); } -exports.getIDToken = getIDToken; -/** - * Summary exports - */ -var summary_1 = __nccwpck_require__(4315); -Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); -/** - * @deprecated use core.summary - */ -var summary_2 = __nccwpck_require__(4315); -Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); -/** - * Path exports - */ -var path_utils_1 = __nccwpck_require__(8921); -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.downloadCacheStorageSDK = downloadCacheStorageSDK; +//# sourceMappingURL=downloadUtils.js.map /***/ }), -/***/ 790: +/***/ 13981: /***/ (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]; } }); -}) : (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 __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 __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); + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.issueCommand = void 0; -// We use any as a valid input type -/* eslint-disable @typescript-eslint/no-explicit-any */ -const fs = __importStar(__nccwpck_require__(7147)); -const os = __importStar(__nccwpck_require__(2037)); -const utils_1 = __nccwpck_require__(3704); -function issueCommand(command, message) { - const filePath = process.env[`GITHUB_${command}`]; - if (!filePath) { - throw new Error(`Unable to find environment variable for file command ${command}`); +const core = __importStar(__nccwpck_require__(42186)); +const http_client_1 = __nccwpck_require__(96255); +const constants_1 = __nccwpck_require__(88840); +function isSuccessStatusCode(statusCode) { + if (!statusCode) { + return false; } - if (!fs.existsSync(filePath)) { - throw new Error(`Missing file at path: ${filePath}`); + return statusCode >= 200 && statusCode < 300; +} +exports.isSuccessStatusCode = isSuccessStatusCode; +function isServerErrorStatusCode(statusCode) { + if (!statusCode) { + return true; } - fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, { - encoding: 'utf8' + return statusCode >= 500; +} +exports.isServerErrorStatusCode = isServerErrorStatusCode; +function isRetryableStatusCode(statusCode) { + if (!statusCode) { + return false; + } + const retryableStatusCodes = [ + http_client_1.HttpCodes.BadGateway, + http_client_1.HttpCodes.ServiceUnavailable, + http_client_1.HttpCodes.GatewayTimeout + ]; + return retryableStatusCodes.includes(statusCode); +} +exports.isRetryableStatusCode = isRetryableStatusCode; +function sleep(milliseconds) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise(resolve => setTimeout(resolve, milliseconds)); }); } -exports.issueCommand = issueCommand; -//# sourceMappingURL=file-command.js.map +function retry(name, method, getStatusCode, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay, onError = undefined) { + return __awaiter(this, void 0, void 0, function* () { + let errorMessage = ''; + let attempt = 1; + while (attempt <= maxAttempts) { + let response = undefined; + let statusCode = undefined; + let isRetryable = false; + try { + response = yield method(); + } + catch (error) { + if (onError) { + response = onError(error); + } + isRetryable = true; + errorMessage = error.message; + } + if (response) { + statusCode = getStatusCode(response); + if (!isServerErrorStatusCode(statusCode)) { + return response; + } + } + if (statusCode) { + isRetryable = isRetryableStatusCode(statusCode); + errorMessage = `Cache service responded with ${statusCode}`; + } + core.debug(`${name} - Attempt ${attempt} of ${maxAttempts} failed with error: ${errorMessage}`); + if (!isRetryable) { + core.debug(`${name} - Error is not retryable`); + break; + } + yield sleep(delay); + attempt++; + } + throw Error(`${name} failed: ${errorMessage}`); + }); +} +exports.retry = retry; +function retryTypedResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay) { + return __awaiter(this, void 0, void 0, function* () { + return yield retry(name, method, (response) => response.statusCode, maxAttempts, delay, + // If the error object contains the statusCode property, extract it and return + // an TypedResponse so it can be processed by the retry logic. + (error) => { + if (error instanceof http_client_1.HttpClientError) { + return { + statusCode: error.statusCode, + result: null, + headers: {}, + error + }; + } + else { + return undefined; + } + }); + }); +} +exports.retryTypedResponse = retryTypedResponse; +function retryHttpClientResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay) { + return __awaiter(this, void 0, void 0, function* () { + return yield retry(name, method, (response) => response.message.statusCode, maxAttempts, delay); + }); +} +exports.retryHttpClientResponse = retryHttpClientResponse; +//# sourceMappingURL=requestUtils.js.map /***/ }), -/***/ 3324: +/***/ 56490: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -3922,77 +4860,233 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.OidcClient = void 0; -const http_client_1 = __nccwpck_require__(7820); -const auth_1 = __nccwpck_require__(2245); -const core_1 = __nccwpck_require__(7334); -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'); +const exec_1 = __nccwpck_require__(71514); +const io = __importStar(__nccwpck_require__(47351)); +const fs_1 = __nccwpck_require__(57147); +const path = __importStar(__nccwpck_require__(71017)); +const utils = __importStar(__nccwpck_require__(91518)); +const constants_1 = __nccwpck_require__(88840); +function getTarPath(args, compressionMethod) { + return __awaiter(this, void 0, void 0, function* () { + switch (process.platform) { + case 'win32': { + const systemTar = `${process.env['windir']}\\System32\\tar.exe`; + if (compressionMethod !== constants_1.CompressionMethod.Gzip) { + // We only use zstandard compression on windows when gnu tar is installed due to + // a bug with compressing large files with bsdtar + zstd + args.push('--force-local'); + } + else if (fs_1.existsSync(systemTar)) { + return systemTar; + } + else if (yield utils.isGnuTarInstalled()) { + args.push('--force-local'); + } + break; + } + case 'darwin': { + const gnuTar = yield io.which('gtar', false); + if (gnuTar) { + // fix permission denied errors when extracting BSD tar archive with GNU tar - https://github.com/actions/cache/issues/527 + args.push('--delay-directory-restore'); + return gnuTar; + } + break; + } + default: + break; } - 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'); + return yield io.which('tar', true); + }); +} +function execTar(args, compressionMethod, cwd) { + return __awaiter(this, void 0, void 0, function* () { + try { + yield exec_1.exec(`"${yield getTarPath(args, compressionMethod)}"`, args, { cwd }); } - 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'); + catch (error) { + throw new Error(`Tar failed with error: ${error === null || error === void 0 ? void 0 : error.message}`); + } + }); +} +function getWorkingDirectory() { + var _a; + return (_a = process.env['GITHUB_WORKSPACE']) !== null && _a !== void 0 ? _a : process.cwd(); +} +function extractTar(archivePath, compressionMethod) { + return __awaiter(this, void 0, void 0, function* () { + // Create directory to extract tar into + const workingDirectory = getWorkingDirectory(); + yield io.mkdirP(workingDirectory); + // --d: Decompress. + // --long=#: Enables long distance matching with # bits. Maximum is 30 (1GB) on 32-bit OS and 31 (2GB) on 64-bit. + // Using 30 here because we also support 32-bit self-hosted runners. + function getCompressionProgram() { + switch (compressionMethod) { + case constants_1.CompressionMethod.Zstd: + return ['--use-compress-program', 'zstd -d --long=30']; + case constants_1.CompressionMethod.ZstdWithoutLong: + return ['--use-compress-program', 'zstd -d']; + default: + return ['-z']; } - 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; + } + const args = [ + ...getCompressionProgram(), + '-xf', + archivePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), + '-P', + '-C', + workingDirectory.replace(new RegExp(`\\${path.sep}`, 'g'), '/') + ]; + yield execTar(args, compressionMethod); + }); +} +exports.extractTar = extractTar; +function createTar(archiveFolder, sourceDirectories, compressionMethod) { + return __awaiter(this, void 0, void 0, function* () { + // Write source directories to manifest.txt to avoid command length limits + const manifestFilename = 'manifest.txt'; + const cacheFileName = utils.getCacheFileName(compressionMethod); + fs_1.writeFileSync(path.join(archiveFolder, manifestFilename), sourceDirectories.join('\n')); + const workingDirectory = getWorkingDirectory(); + // -T#: Compress using # working thread. If # is 0, attempt to detect and use the number of physical CPU cores. + // --long=#: Enables long distance matching with # bits. Maximum is 30 (1GB) on 32-bit OS and 31 (2GB) on 64-bit. + // Using 30 here because we also support 32-bit self-hosted runners. + // Long range mode is added to zstd in v1.3.2 release, so we will not use --long in older version of zstd. + function getCompressionProgram() { + switch (compressionMethod) { + case constants_1.CompressionMethod.Zstd: + return ['--use-compress-program', 'zstd -T0 --long=30']; + case constants_1.CompressionMethod.ZstdWithoutLong: + return ['--use-compress-program', 'zstd -T0']; + default: + return ['-z']; } - catch (error) { - throw new Error(`Error message: ${error.message}`); + } + const args = [ + '--posix', + ...getCompressionProgram(), + '-cf', + cacheFileName.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), + '-P', + '-C', + workingDirectory.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), + '--files-from', + manifestFilename + ]; + yield execTar(args, compressionMethod, archiveFolder); + }); +} +exports.createTar = createTar; +function listTar(archivePath, compressionMethod) { + return __awaiter(this, void 0, void 0, function* () { + // --d: Decompress. + // --long=#: Enables long distance matching with # bits. + // Maximum is 30 (1GB) on 32-bit OS and 31 (2GB) on 64-bit. + // Using 30 here because we also support 32-bit self-hosted runners. + function getCompressionProgram() { + switch (compressionMethod) { + case constants_1.CompressionMethod.Zstd: + return ['--use-compress-program', 'zstd -d --long=30']; + case constants_1.CompressionMethod.ZstdWithoutLong: + return ['--use-compress-program', 'zstd -d']; + default: + return ['-z']; } - }); + } + const args = [ + ...getCompressionProgram(), + '-tf', + archivePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), + '-P' + ]; + yield execTar(args, compressionMethod); + }); +} +exports.listTar = listTar; +//# sourceMappingURL=tar.js.map + +/***/ }), + +/***/ 76215: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const core = __importStar(__nccwpck_require__(42186)); +/** + * Returns a copy of the upload options with defaults filled in. + * + * @param copy the original upload options + */ +function getUploadOptions(copy) { + const result = { + uploadConcurrency: 4, + uploadChunkSize: 32 * 1024 * 1024 + }; + if (copy) { + if (typeof copy.uploadConcurrency === 'number') { + result.uploadConcurrency = copy.uploadConcurrency; + } + if (typeof copy.uploadChunkSize === 'number') { + result.uploadChunkSize = copy.uploadChunkSize; + } } + core.debug(`Upload concurrency: ${result.uploadConcurrency}`); + core.debug(`Upload chunk size: ${result.uploadChunkSize}`); + return result; } -exports.OidcClient = OidcClient; -//# sourceMappingURL=oidc-utils.js.map +exports.getUploadOptions = getUploadOptions; +/** + * Returns a copy of the download options with defaults filled in. + * + * @param copy the original download options + */ +function getDownloadOptions(copy) { + const result = { + useAzureSdk: true, + downloadConcurrency: 8, + timeoutInMs: 30000 + }; + if (copy) { + if (typeof copy.useAzureSdk === 'boolean') { + result.useAzureSdk = copy.useAzureSdk; + } + if (typeof copy.downloadConcurrency === 'number') { + result.downloadConcurrency = copy.downloadConcurrency; + } + if (typeof copy.timeoutInMs === 'number') { + result.timeoutInMs = copy.timeoutInMs; + } + } + core.debug(`Use Azure SDK: ${result.useAzureSdk}`); + core.debug(`Download concurrency: ${result.downloadConcurrency}`); + core.debug(`Request timeout (ms): ${result.timeoutInMs}`); + return result; +} +exports.getDownloadOptions = getDownloadOptions; +//# sourceMappingURL=options.js.map /***/ }), -/***/ 8921: +/***/ 87351: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -4017,803 +5111,1061 @@ var __importStar = (this && this.__importStar) || function (mod) { return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; -const path = __importStar(__nccwpck_require__(1017)); +exports.issue = exports.issueCommand = void 0; +const os = __importStar(__nccwpck_require__(22037)); +const utils_1 = __nccwpck_require__(5278); /** - * toPosixPath converts the given path to the posix form. On Windows, \\ will be - * replaced with /. + * Commands * - * @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 \\. + * Command Format: + * ::name key=value,key=value::message * - * @param pth. Path to transform. - * @return string Win32 path. + * Examples: + * ::warning::This is the message + * ::set-env name=MY_VAR::some value */ -function toWin32Path(pth) { - return pth.replace(/[/]/g, '\\'); +function issueCommand(command, properties, message) { + const cmd = new Command(command, properties, message); + process.stdout.write(cmd.toString() + os.EOL); } -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.issueCommand = issueCommand; +function issue(name, message = '') { + issueCommand(name, {}, message); } -exports.toPlatformPath = toPlatformPath; -//# sourceMappingURL=path-utils.js.map +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; + } + 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; + } +} +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 /***/ }), -/***/ 4315: +/***/ 42186: /***/ (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.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; -const os_1 = __nccwpck_require__(2037); -const fs_1 = __nccwpck_require__(7147); -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 = ''; - } - /** - * 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; - } - 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}>`; - } - 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(); - } +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()); + }); +}; +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__(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) { /** - * 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 + * A code indicating that the action was successful */ - addDetails(label, content) { - const element = this.wrap('details', this.wrap('summary', label) + content); - return this.addRaw(element).addEOL(); - } + ExitCode[ExitCode["Success"] = 0] = "Success"; /** - * 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 + * A code indicating that the action was a failure */ - 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(); + 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)); } - /** - * 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(); + 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); } - /** - * 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(); + else { + command_1.issueCommand('add-path', {}, inputPath); } - /** - * 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(); + 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}`); } - /** - * 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(); + if (options && options.trimWhitespace === false) { + return val; } - /** - * 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(); + 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()); } -const _summary = new Summary(); +exports.getMultilineInput = getMultilineInput; /** - * @deprecated use `core.summary` + * 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 */ -exports.markdownSummary = _summary; -exports.summary = _summary; -//# sourceMappingURL=summary.js.map - -/***/ }), - -/***/ 3704: -/***/ ((__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; +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; /** - * Sanitizes an input into a string so it can be passed into issueCommand safely - * @param input input to sanitize into a string + * 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 */ -function toCommandValue(input) { - if (input === null || input === undefined) { - return ''; - } - else if (typeof input === 'string' || input instanceof String) { - return input; +// 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 JSON.stringify(input); + process.stdout.write(os.EOL); + command_1.issueCommand('set-output', { name }, utils_1.toCommandValue(value)); } -exports.toCommandValue = toCommandValue; +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. * - * @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 - }; +function setCommandEcho(enabled) { + command_1.issue('echo', enabled ? 'on' : 'off'); } -exports.toCommandProperties = toCommandProperties; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 4216: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "v1", ({ - enumerable: true, - get: function () { - return _v.default; - } -})); -Object.defineProperty(exports, "v3", ({ - enumerable: true, - get: function () { - return _v2.default; - } -})); -Object.defineProperty(exports, "v4", ({ - enumerable: true, - get: function () { - return _v3.default; - } -})); -Object.defineProperty(exports, "v5", ({ - enumerable: true, - get: function () { - return _v4.default; - } -})); -Object.defineProperty(exports, "NIL", ({ - enumerable: true, - get: function () { - return _nil.default; - } -})); -Object.defineProperty(exports, "version", ({ - enumerable: true, - get: function () { - return _version.default; - } -})); -Object.defineProperty(exports, "validate", ({ - enumerable: true, - get: function () { - return _validate.default; - } -})); -Object.defineProperty(exports, "stringify", ({ - enumerable: true, - get: function () { - return _stringify.default; - } -})); -Object.defineProperty(exports, "parse", ({ - enumerable: true, - get: function () { - return _parse.default; - } -})); - -var _v = _interopRequireDefault(__nccwpck_require__(3983)); - -var _v2 = _interopRequireDefault(__nccwpck_require__(2537)); - -var _v3 = _interopRequireDefault(__nccwpck_require__(5905)); - -var _v4 = _interopRequireDefault(__nccwpck_require__(7245)); - -var _nil = _interopRequireDefault(__nccwpck_require__(2661)); - -var _version = _interopRequireDefault(__nccwpck_require__(1644)); - -var _validate = _interopRequireDefault(__nccwpck_require__(9404)); - -var _stringify = _interopRequireDefault(__nccwpck_require__(4146)); - -var _parse = _interopRequireDefault(__nccwpck_require__(8386)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/***/ }), - -/***/ 6851: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; - -var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function md5(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); - } - - return _crypto.default.createHash('md5').update(bytes).digest(); +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); } - -var _default = md5; -exports["default"] = _default; - -/***/ }), - -/***/ 2661: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = '00000000-0000-0000-0000-000000000000'; -exports["default"] = _default; - -/***/ }), - -/***/ 8386: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; - -var _validate = _interopRequireDefault(__nccwpck_require__(9404)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function parse(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); - } - - let v; - const arr = new Uint8Array(16); // Parse ########-....-....-....-............ - - arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; - arr[1] = v >>> 16 & 0xff; - arr[2] = v >>> 8 & 0xff; - arr[3] = v & 0xff; // Parse ........-####-....-....-............ - - arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; - arr[5] = v & 0xff; // Parse ........-....-####-....-............ - - arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; - arr[7] = v & 0xff; // Parse ........-....-....-####-............ - - arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; - arr[9] = v & 0xff; // Parse ........-....-....-....-############ - // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) - - arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; - arr[11] = v / 0x100000000 & 0xff; - arr[12] = v >>> 24 & 0xff; - arr[13] = v >>> 16 & 0xff; - arr[14] = v >>> 8 & 0xff; - arr[15] = v & 0xff; - return arr; +exports.setFailed = setFailed; +//----------------------------------------------------------------------- +// Logging Commands +//----------------------------------------------------------------------- +/** + * Gets whether Actions Step Debug is on or not + */ +function isDebug() { + return process.env['RUNNER_DEBUG'] === '1'; } - -var _default = parse; -exports["default"] = _default; - -/***/ }), - -/***/ 2072: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; -exports["default"] = _default; +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. + * + * @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.saveState = saveState; +/** + * Gets the value of an state set by this action's main execution. + * + * @param name name of the state to get + * @returns string + */ +function getState(name) { + return process.env[`STATE_${name}`] || ''; +} +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 /***/ }), -/***/ 9710: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 717: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true +// 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]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; })); -exports["default"] = rng; - -var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate - -let poolPtr = rnds8Pool.length; - -function rng() { - if (poolPtr > rnds8Pool.length - 16) { - _crypto.default.randomFillSync(rnds8Pool); - - poolPtr = 0; - } - - return rnds8Pool.slice(poolPtr, poolPtr += 16); +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.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__(78974); +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}`); + } + 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 /***/ }), -/***/ 4529: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 98041: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; - -var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function sha1(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); - } - - return _crypto.default.createHash('sha1').update(bytes).digest(); +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__(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 + }; + 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'); + } + 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'); + } + 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}`); + } + }); + } } - -var _default = sha1; -exports["default"] = _default; +exports.OidcClient = OidcClient; +//# sourceMappingURL=oidc-utils.js.map /***/ }), -/***/ 4146: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 2981: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -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]; })); -exports["default"] = void 0; - -var _validate = _interopRequireDefault(__nccwpck_require__(9404)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - +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.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; +const path = __importStar(__nccwpck_require__(71017)); /** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + * toPosixPath converts the given path to the posix form. On Windows, \\ will be + * replaced with /. + * + * @param pth. Path to transform. + * @return string Posix path. */ -const byteToHex = []; - -for (let i = 0; i < 256; ++i) { - byteToHex.push((i + 0x100).toString(16).substr(1)); +function toPosixPath(pth) { + return pth.replace(/[\\]/g, '/'); } - -function stringify(arr, offset = 0) { - // Note: Be careful editing this code! It's been tuned for performance - // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 - const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one - // of the following: - // - One or more input array values don't map to a hex octet (leading to - // "undefined" in the uuid) - // - Invalid input values for the RFC `version` or `variant` fields - - if (!(0, _validate.default)(uuid)) { - throw TypeError('Stringified UUID is invalid'); - } - - return uuid; +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, '\\'); } - -var _default = stringify; -exports["default"] = _default; +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 /***/ }), -/***/ 3983: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 81327: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; - -var _rng = _interopRequireDefault(__nccwpck_require__(9710)); - -var _stringify = _interopRequireDefault(__nccwpck_require__(4146)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -// **`v1()` - Generate time-based UUID** -// -// Inspired by https://github.com/LiosK/UUID.js -// and http://docs.python.org/library/uuid.html -let _nodeId; - -let _clockseq; // Previous uuid creation time - - -let _lastMSecs = 0; -let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details - -function v1(options, buf, offset) { - let i = buf && offset || 0; - const b = buf || new Array(16); - options = options || {}; - let node = options.node || _nodeId; - let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not - // specified. We do this lazily to minimize issues related to insufficient - // system entropy. See #189 - - if (node == null || clockseq == null) { - const seedBytes = options.random || (options.rng || _rng.default)(); - - if (node == null) { - // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) - node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; +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.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 = ''; } - - if (clockseq == null) { - // Per 4.2.2, randomize (14 bit) clockseq - clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + /** + * 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; + } + 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; + }); } - } // UUID timestamps are 100 nano-second units since the Gregorian epoch, - // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so - // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' - // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + /** + * 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(); + }); + } + /** + * 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(); + } +} +const _summary = new Summary(); +/** + * @deprecated use `core.summary` + */ +exports.markdownSummary = _summary; +exports.summary = _summary; +//# sourceMappingURL=summary.js.map +/***/ }), - let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock +/***/ 5278: +/***/ ((__unused_webpack_module, exports) => { - let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) +"use strict"; - const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression +// 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 {}; + } + 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 - if (dt < 0 && options.clockseq === undefined) { - clockseq = clockseq + 1 & 0x3fff; - } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new - // time interval +/***/ }), +/***/ 78974: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { - nsecs = 0; - } // Per 4.2.1.2 Throw error if too many uuids are requested +"use strict"; - if (nsecs >= 10000) { - throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "v1", ({ + enumerable: true, + get: function () { + return _v.default; } +})); +Object.defineProperty(exports, "v3", ({ + enumerable: true, + get: function () { + return _v2.default; + } +})); +Object.defineProperty(exports, "v4", ({ + enumerable: true, + get: function () { + return _v3.default; + } +})); +Object.defineProperty(exports, "v5", ({ + enumerable: true, + get: function () { + return _v4.default; + } +})); +Object.defineProperty(exports, "NIL", ({ + enumerable: true, + get: function () { + return _nil.default; + } +})); +Object.defineProperty(exports, "version", ({ + enumerable: true, + get: function () { + return _version.default; + } +})); +Object.defineProperty(exports, "validate", ({ + enumerable: true, + get: function () { + return _validate.default; + } +})); +Object.defineProperty(exports, "stringify", ({ + enumerable: true, + get: function () { + return _stringify.default; + } +})); +Object.defineProperty(exports, "parse", ({ + enumerable: true, + get: function () { + return _parse.default; + } +})); - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - - msecs += 12219292800000; // `time_low` +var _v = _interopRequireDefault(__nccwpck_require__(81595)); - const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; - b[i++] = tl >>> 24 & 0xff; - b[i++] = tl >>> 16 & 0xff; - b[i++] = tl >>> 8 & 0xff; - b[i++] = tl & 0xff; // `time_mid` +var _v2 = _interopRequireDefault(__nccwpck_require__(26993)); - const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; - b[i++] = tmh >>> 8 & 0xff; - b[i++] = tmh & 0xff; // `time_high_and_version` +var _v3 = _interopRequireDefault(__nccwpck_require__(51472)); - b[i++] = tmh >>> 24 & 0xf | 0x10; // include version +var _v4 = _interopRequireDefault(__nccwpck_require__(16217)); - b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) +var _nil = _interopRequireDefault(__nccwpck_require__(32381)); - b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` +var _version = _interopRequireDefault(__nccwpck_require__(40427)); - b[i++] = clockseq & 0xff; // `node` +var _validate = _interopRequireDefault(__nccwpck_require__(92609)); - for (let n = 0; n < 6; ++n) { - b[i + n] = node[n]; - } +var _stringify = _interopRequireDefault(__nccwpck_require__(61458)); - return buf || (0, _stringify.default)(b); -} +var _parse = _interopRequireDefault(__nccwpck_require__(26385)); -var _default = v1; -exports["default"] = _default; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /***/ }), -/***/ 2537: +/***/ 5842: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -4824,20 +6176,27 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _v = _interopRequireDefault(__nccwpck_require__(177)); - -var _md = _interopRequireDefault(__nccwpck_require__(6851)); +var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -const v3 = (0, _v.default)('v3', 0x30, _md.default); -var _default = v3; +function md5(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return _crypto.default.createHash('md5').update(bytes).digest(); +} + +var _default = md5; exports["default"] = _default; /***/ }), -/***/ 177: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 32381: +/***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -4845,47 +6204,373 @@ exports["default"] = _default; Object.defineProperty(exports, "__esModule", ({ value: true })); +exports["default"] = void 0; +var _default = '00000000-0000-0000-0000-000000000000'; exports["default"] = _default; -exports.URL = exports.DNS = void 0; - -var _stringify = _interopRequireDefault(__nccwpck_require__(4146)); -var _parse = _interopRequireDefault(__nccwpck_require__(8386)); +/***/ }), -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/***/ 26385: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function stringToBytes(str) { - str = unescape(encodeURIComponent(str)); // UTF8 escape +"use strict"; - const bytes = []; - for (let i = 0; i < str.length; ++i) { - bytes.push(str.charCodeAt(i)); - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; - return bytes; -} +var _validate = _interopRequireDefault(__nccwpck_require__(92609)); -const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; -exports.DNS = DNS; -const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; -exports.URL = URL; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _default(name, version, hashfunc) { - function generateUUID(value, namespace, buf, offset) { - if (typeof value === 'string') { - value = stringToBytes(value); - } +function parse(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } - if (typeof namespace === 'string') { - namespace = (0, _parse.default)(namespace); - } + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ - if (namespace.length !== 16) { - throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); - } // Compute hash of namespace and value, Per 4.3 - // Future: Use spread syntax when supported on all platforms, e.g. `bytes = - // hashfunc([...namespace, ... value])` + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +var _default = parse; +exports["default"] = _default; + +/***/ }), + +/***/ 86230: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; +exports["default"] = _default; + +/***/ }), + +/***/ 9784: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = rng; + +var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate + +let poolPtr = rnds8Pool.length; + +function rng() { + if (poolPtr > rnds8Pool.length - 16) { + _crypto.default.randomFillSync(rnds8Pool); + + poolPtr = 0; + } + + return rnds8Pool.slice(poolPtr, poolPtr += 16); +} + +/***/ }), + +/***/ 38844: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function sha1(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return _crypto.default.createHash('sha1').update(bytes).digest(); +} + +var _default = sha1; +exports["default"] = _default; + +/***/ }), + +/***/ 61458: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _validate = _interopRequireDefault(__nccwpck_require__(92609)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ +const byteToHex = []; + +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).substr(1)); +} + +function stringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!(0, _validate.default)(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; +} + +var _default = stringify; +exports["default"] = _default; + +/***/ }), + +/***/ 81595: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _rng = _interopRequireDefault(__nccwpck_require__(9784)); + +var _stringify = _interopRequireDefault(__nccwpck_require__(61458)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html +let _nodeId; + +let _clockseq; // Previous uuid creation time + + +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || _rng.default)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || (0, _stringify.default)(b); +} + +var _default = v1; +exports["default"] = _default; + +/***/ }), + +/***/ 26993: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _v = _interopRequireDefault(__nccwpck_require__(65920)); + +var _md = _interopRequireDefault(__nccwpck_require__(5842)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v3 = (0, _v.default)('v3', 0x30, _md.default); +var _default = v3; +exports["default"] = _default; + +/***/ }), + +/***/ 65920: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = _default; +exports.URL = exports.DNS = void 0; + +var _stringify = _interopRequireDefault(__nccwpck_require__(61458)); + +var _parse = _interopRequireDefault(__nccwpck_require__(26385)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + const bytes = []; + + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + + return bytes; +} + +const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +exports.DNS = DNS; +const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +exports.URL = URL; + +function _default(name, version, hashfunc) { + function generateUUID(value, namespace, buf, offset) { + if (typeof value === 'string') { + value = stringToBytes(value); + } + + if (typeof namespace === 'string') { + namespace = (0, _parse.default)(namespace); + } + + if (namespace.length !== 16) { + throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` let bytes = new Uint8Array(16 + value.length); @@ -4921,7 +6606,7 @@ function _default(name, version, hashfunc) { /***/ }), -/***/ 5905: +/***/ 51472: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -4932,9 +6617,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _rng = _interopRequireDefault(__nccwpck_require__(9710)); +var _rng = _interopRequireDefault(__nccwpck_require__(9784)); -var _stringify = _interopRequireDefault(__nccwpck_require__(4146)); +var _stringify = _interopRequireDefault(__nccwpck_require__(61458)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -4965,7 +6650,7 @@ exports["default"] = _default; /***/ }), -/***/ 7245: +/***/ 16217: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -4976,9 +6661,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _v = _interopRequireDefault(__nccwpck_require__(177)); +var _v = _interopRequireDefault(__nccwpck_require__(65920)); -var _sha = _interopRequireDefault(__nccwpck_require__(4529)); +var _sha = _interopRequireDefault(__nccwpck_require__(38844)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -4988,7 +6673,7 @@ exports["default"] = _default; /***/ }), -/***/ 9404: +/***/ 92609: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -4999,7 +6684,7 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _regex = _interopRequireDefault(__nccwpck_require__(2072)); +var _regex = _interopRequireDefault(__nccwpck_require__(86230)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -5012,7 +6697,7 @@ exports["default"] = _default; /***/ }), -/***/ 1644: +/***/ 40427: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -5023,7 +6708,7 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _validate = _interopRequireDefault(__nccwpck_require__(9404)); +var _validate = _interopRequireDefault(__nccwpck_require__(92609)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -5040,7 +6725,7 @@ exports["default"] = _default; /***/ }), -/***/ 6703: +/***/ 71514: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -5075,8 +6760,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getExecOutput = exports.exec = void 0; -const string_decoder_1 = __nccwpck_require__(1576); -const tr = __importStar(__nccwpck_require__(4274)); +const string_decoder_1 = __nccwpck_require__(71576); +const tr = __importStar(__nccwpck_require__(88159)); /** * Exec a command. * Output will be streamed to the live console. @@ -5150,7 +6835,7 @@ exports.getExecOutput = getExecOutput; /***/ }), -/***/ 4274: +/***/ 88159: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -5185,13 +6870,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.argStringToArray = exports.ToolRunner = void 0; -const os = __importStar(__nccwpck_require__(2037)); -const events = __importStar(__nccwpck_require__(2361)); -const child = __importStar(__nccwpck_require__(2081)); -const path = __importStar(__nccwpck_require__(1017)); -const io = __importStar(__nccwpck_require__(1608)); -const ioUtil = __importStar(__nccwpck_require__(3017)); -const timers_1 = __nccwpck_require__(9512); +const os = __importStar(__nccwpck_require__(22037)); +const events = __importStar(__nccwpck_require__(82361)); +const child = __importStar(__nccwpck_require__(32081)); +const path = __importStar(__nccwpck_require__(71017)); +const io = __importStar(__nccwpck_require__(47351)); +const ioUtil = __importStar(__nccwpck_require__(81962)); +const timers_1 = __nccwpck_require__(39512); /* eslint-disable @typescript-eslint/unbound-method */ const IS_WINDOWS = process.platform === 'win32'; /* @@ -5775,7 +7460,223 @@ class ExecState extends events.EventEmitter { /***/ }), -/***/ 27: +/***/ 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://api.github.com/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 + +/***/ }), + +/***/ 95438: +/***/ (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.getOctokit = exports.context = void 0; +const Context = __importStar(__nccwpck_require__(74087)); +const utils_1 = __nccwpck_require__(73030); +exports.context = new Context.Context(); +/** + * Returns a hydrated octokit ready to use for GitHub Actions + * + * @param token the repo PAT or GITHUB_TOKEN + * @param options other options to set + */ +function getOctokit(token, options, ...additionalPlugins) { + const GitHubWithPlugins = utils_1.GitHub.plugin(...additionalPlugins); + return new GitHubWithPlugins(utils_1.getOctokitOptions(token, options)); +} +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'); + } + 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}`; +} +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 + +/***/ }), + +/***/ 73030: +/***/ (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.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"; @@ -5791,7 +7692,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.create = void 0; -const internal_globber_1 = __nccwpck_require__(3936); +const internal_globber_1 = __nccwpck_require__(28298); /** * Constructs a globber * @@ -5808,7 +7709,7 @@ exports.create = create; /***/ }), -/***/ 5237: +/***/ 51026: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -5834,7 +7735,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getOptions = void 0; -const core = __importStar(__nccwpck_require__(7334)); +const core = __importStar(__nccwpck_require__(42186)); /** * Returns a copy with defaults filled in. */ @@ -5865,7 +7766,7 @@ exports.getOptions = getOptions; /***/ }), -/***/ 3936: +/***/ 28298: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -5919,14 +7820,14 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DefaultGlobber = void 0; -const core = __importStar(__nccwpck_require__(7334)); -const fs = __importStar(__nccwpck_require__(7147)); -const globOptionsHelper = __importStar(__nccwpck_require__(5237)); -const path = __importStar(__nccwpck_require__(1017)); -const patternHelper = __importStar(__nccwpck_require__(3987)); -const internal_match_kind_1 = __nccwpck_require__(2097); -const internal_pattern_1 = __nccwpck_require__(7207); -const internal_search_state_1 = __nccwpck_require__(6695); +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) { @@ -6107,7 +8008,7 @@ exports.DefaultGlobber = DefaultGlobber; /***/ }), -/***/ 2097: +/***/ 81063: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -6132,7 +8033,7 @@ var MatchKind; /***/ }), -/***/ 2636: +/***/ 1849: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -6161,8 +8062,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.safeTrimTrailingSeparator = exports.normalizeSeparators = exports.hasRoot = exports.hasAbsoluteRoot = exports.ensureAbsoluteRoot = exports.dirname = void 0; -const path = __importStar(__nccwpck_require__(1017)); -const assert_1 = __importDefault(__nccwpck_require__(9491)); +const path = __importStar(__nccwpck_require__(71017)); +const assert_1 = __importDefault(__nccwpck_require__(39491)); const IS_WINDOWS = process.platform === 'win32'; /** * Similar to path.dirname except normalizes the path separators and slightly better handling for Windows UNC paths. @@ -6337,7 +8238,7 @@ exports.safeTrimTrailingSeparator = safeTrimTrailingSeparator; /***/ }), -/***/ 1373: +/***/ 96836: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -6366,9 +8267,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Path = void 0; -const path = __importStar(__nccwpck_require__(1017)); -const pathHelper = __importStar(__nccwpck_require__(2636)); -const assert_1 = __importDefault(__nccwpck_require__(9491)); +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 @@ -6457,7 +8358,7 @@ exports.Path = Path; /***/ }), -/***/ 3987: +/***/ 29005: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -6483,8 +8384,8 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.partialMatch = exports.match = exports.getSearchPaths = void 0; -const pathHelper = __importStar(__nccwpck_require__(2636)); -const internal_match_kind_1 = __nccwpck_require__(2097); +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. @@ -6558,7 +8459,7 @@ exports.partialMatch = partialMatch; /***/ }), -/***/ 7207: +/***/ 64536: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -6587,13 +8488,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Pattern = void 0; -const os = __importStar(__nccwpck_require__(2037)); -const path = __importStar(__nccwpck_require__(1017)); -const pathHelper = __importStar(__nccwpck_require__(2636)); -const assert_1 = __importDefault(__nccwpck_require__(9491)); -const minimatch_1 = __nccwpck_require__(5806); -const internal_match_kind_1 = __nccwpck_require__(2097); -const internal_path_1 = __nccwpck_require__(1373); +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) { @@ -6820,7 +8721,7 @@ exports.Pattern = Pattern; /***/ }), -/***/ 6695: +/***/ 89117: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -6838,7 +8739,7 @@ exports.SearchState = SearchState; /***/ }), -/***/ 2245: +/***/ 35526: /***/ (function(__unused_webpack_module, exports) { "use strict"; @@ -6926,7 +8827,7 @@ exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHand /***/ }), -/***/ 7820: +/***/ 96255: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -6934,7 +8835,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]; @@ -6947,7 +8852,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; }; @@ -6962,10 +8867,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; 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__(3685)); -const https = __importStar(__nccwpck_require__(5687)); -const pm = __importStar(__nccwpck_require__(5241)); -const tunnel = __importStar(__nccwpck_require__(665)); +const http = __importStar(__nccwpck_require__(13685)); +const https = __importStar(__nccwpck_require__(95687)); +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"; @@ -6995,16 +8901,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 @@ -7055,6 +8961,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) { @@ -7360,6 +9279,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; @@ -7407,7 +9335,7 @@ class HttpClient { if (this._keepAlive && useProxy) { agent = this._proxyAgent; } - if (this._keepAlive && !useProxy) { + if (!useProxy) { agent = this._agent; } // if agent is already assigned use that agent. @@ -7439,16 +9367,12 @@ class HttpClient { agent = tunnelAgent(agentOptions); this._proxyAgent = agent; } - // if reusing agent across request and tunneling agent isn't assigned create a new agent - if (this._keepAlive && !agent) { + // if tunneling agent isn't assigned create a new agent + if (!agent) { const options = { keepAlive: this._keepAlive, maxSockets }; agent = usingSsl ? new https.Agent(options) : new http.Agent(options); this._agent = agent; } - // if not using private agent and tunnel agent isn't setup then use global agent - if (!agent) { - agent = usingSsl ? https.globalAgent : http.globalAgent; - } 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 @@ -7459,6 +9383,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); @@ -7538,7 +9486,7 @@ const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCa /***/ }), -/***/ 5241: +/***/ 19835: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -7559,7 +9507,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; @@ -7570,6 +9524,10 @@ function checkBypass(reqUrl) { if (!reqUrl.hostname) { return false; } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; if (!noProxy) { return false; @@ -7595,18 +9553,29 @@ function checkBypass(reqUrl) { .split(',') .map(x => x.trim().toUpperCase()) .filter(x => x)) { - if (upperReqHosts.some(x => x === upperNoProxyItem)) { + if (upperNoProxyItem === '*' || + upperReqHosts.some(x => x === upperNoProxyItem || + x.endsWith(`.${upperNoProxyItem}`) || + (upperNoProxyItem.startsWith('.') && + x.endsWith(`${upperNoProxyItem}`)))) { return true; } } return false; } exports.checkBypass = checkBypass; +function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return (hostLower === 'localhost' || + hostLower.startsWith('127.') || + hostLower.startsWith('[::1]') || + hostLower.startsWith('[0:0:0:0:0:0:0:1]')); +} //# sourceMappingURL=proxy.js.map /***/ }), -/***/ 3017: +/***/ 81962: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -7642,8 +9611,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge var _a; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getCmdPath = exports.tryGetExecutablePath = exports.isRooted = exports.isDirectory = exports.exists = exports.IS_WINDOWS = exports.unlink = exports.symlink = exports.stat = exports.rmdir = exports.rename = exports.readlink = exports.readdir = exports.mkdir = exports.lstat = exports.copyFile = exports.chmod = void 0; -const fs = __importStar(__nccwpck_require__(7147)); -const path = __importStar(__nccwpck_require__(1017)); +const fs = __importStar(__nccwpck_require__(57147)); +const path = __importStar(__nccwpck_require__(71017)); _a = fs.promises, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; exports.IS_WINDOWS = process.platform === 'win32'; function exists(fsPath) { @@ -7790,7 +9759,7 @@ exports.getCmdPath = getCmdPath; /***/ }), -/***/ 1608: +/***/ 47351: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -7825,11 +9794,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.findInPath = exports.which = exports.mkdirP = exports.rmRF = exports.mv = exports.cp = void 0; -const assert_1 = __nccwpck_require__(9491); -const childProcess = __importStar(__nccwpck_require__(2081)); -const path = __importStar(__nccwpck_require__(1017)); -const util_1 = __nccwpck_require__(3837); -const ioUtil = __importStar(__nccwpck_require__(3017)); +const assert_1 = __nccwpck_require__(39491); +const childProcess = __importStar(__nccwpck_require__(32081)); +const path = __importStar(__nccwpck_require__(71017)); +const util_1 = __nccwpck_require__(73837); +const ioUtil = __importStar(__nccwpck_require__(81962)); const exec = util_1.promisify(childProcess.exec); const execFile = util_1.promisify(childProcess.execFile); /** @@ -8138,7 +10107,7 @@ function copyFile(srcFile, destFile, force) { /***/ }), -/***/ 9280: +/***/ 32473: /***/ (function(module, exports, __nccwpck_require__) { "use strict"; @@ -8173,13 +10142,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports._readLinuxVersionFile = exports._getOsVersion = exports._findMatch = void 0; -const semver = __importStar(__nccwpck_require__(7203)); -const core_1 = __nccwpck_require__(7334); +const semver = __importStar(__nccwpck_require__(85911)); +const core_1 = __nccwpck_require__(42186); // needs to be require for core node modules to be mocked /* eslint @typescript-eslint/no-require-imports: 0 */ -const os = __nccwpck_require__(2037); -const cp = __nccwpck_require__(2081); -const fs = __nccwpck_require__(7147); +const os = __nccwpck_require__(22037); +const cp = __nccwpck_require__(32081); +const fs = __nccwpck_require__(57147); function _findMatch(versionSpec, stable, candidates, archFilter) { return __awaiter(this, void 0, void 0, function* () { const platFilter = os.platform(); @@ -8273,7 +10242,7 @@ exports._readLinuxVersionFile = _readLinuxVersionFile; /***/ }), -/***/ 815: +/***/ 38279: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -8308,7 +10277,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.RetryHelper = void 0; -const core = __importStar(__nccwpck_require__(7334)); +const core = __importStar(__nccwpck_require__(42186)); /** * Internal class for retries */ @@ -8363,7 +10332,7 @@ exports.RetryHelper = RetryHelper; /***/ }), -/***/ 3635: +/***/ 27784: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -8401,20 +10370,20 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.evaluateVersions = exports.isExplicitVersion = exports.findFromManifest = exports.getManifestFromRepo = exports.findAllVersions = exports.find = exports.cacheFile = exports.cacheDir = exports.extractZip = exports.extractXar = exports.extractTar = exports.extract7z = exports.downloadTool = exports.HTTPError = void 0; -const core = __importStar(__nccwpck_require__(7334)); -const io = __importStar(__nccwpck_require__(1608)); -const fs = __importStar(__nccwpck_require__(7147)); -const mm = __importStar(__nccwpck_require__(9280)); -const os = __importStar(__nccwpck_require__(2037)); -const path = __importStar(__nccwpck_require__(1017)); -const httpm = __importStar(__nccwpck_require__(7436)); -const semver = __importStar(__nccwpck_require__(7203)); -const stream = __importStar(__nccwpck_require__(2781)); -const util = __importStar(__nccwpck_require__(3837)); -const v4_1 = __importDefault(__nccwpck_require__(9963)); -const exec_1 = __nccwpck_require__(6703); -const assert_1 = __nccwpck_require__(9491); -const retry_helper_1 = __nccwpck_require__(815); +const core = __importStar(__nccwpck_require__(42186)); +const io = __importStar(__nccwpck_require__(47351)); +const fs = __importStar(__nccwpck_require__(57147)); +const mm = __importStar(__nccwpck_require__(32473)); +const os = __importStar(__nccwpck_require__(22037)); +const path = __importStar(__nccwpck_require__(71017)); +const httpm = __importStar(__nccwpck_require__(37371)); +const semver = __importStar(__nccwpck_require__(85911)); +const stream = __importStar(__nccwpck_require__(12781)); +const util = __importStar(__nccwpck_require__(73837)); +const v4_1 = __importDefault(__nccwpck_require__(80824)); +const exec_1 = __nccwpck_require__(71514); +const assert_1 = __nccwpck_require__(39491); +const retry_helper_1 = __nccwpck_require__(38279); class HTTPError extends Error { constructor(httpStatusCode) { super(`Unexpected HTTP response: ${httpStatusCode}`); @@ -9035,15 +11004,15 @@ function _unique(values) { /***/ }), -/***/ 7436: +/***/ 37371: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const http = __nccwpck_require__(3685); -const https = __nccwpck_require__(5687); -const pm = __nccwpck_require__(236); +const http = __nccwpck_require__(13685); +const https = __nccwpck_require__(95687); +const pm = __nccwpck_require__(3118); let tunnel; var HttpCodes; (function (HttpCodes) { @@ -9462,7 +11431,7 @@ class HttpClient { if (useProxy) { // If using proxy, need tunnel if (!tunnel) { - tunnel = __nccwpck_require__(665); + tunnel = __nccwpck_require__(74294); } const agentOptions = { maxSockets: maxSockets, @@ -9580,7 +11549,7 @@ exports.HttpClient = HttpClient; /***/ }), -/***/ 236: +/***/ 3118: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -9645,7 +11614,7 @@ exports.checkBypass = checkBypass; /***/ }), -/***/ 1733: +/***/ 52557: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -9892,7 +11861,7 @@ exports.AbortSignal = AbortSignal; /***/ }), -/***/ 1335: +/***/ 39645: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -10115,7 +12084,7 @@ exports.isTokenCredential = isTokenCredential; /***/ }), -/***/ 2546: +/***/ 24607: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -10123,22 +12092,22 @@ exports.isTokenCredential = isTokenCredential; Object.defineProperty(exports, "__esModule", ({ value: true })); -var uuid = __nccwpck_require__(3408); -var util = __nccwpck_require__(3837); -var tslib = __nccwpck_require__(9262); -var xml2js = __nccwpck_require__(2857); -var abortController = __nccwpck_require__(1733); -var logger$1 = __nccwpck_require__(9241); -var coreAuth = __nccwpck_require__(1335); -var os = __nccwpck_require__(2037); -var http = __nccwpck_require__(3685); -var https = __nccwpck_require__(5687); -var tough = __nccwpck_require__(4624); -var tunnel = __nccwpck_require__(665); -var stream = __nccwpck_require__(2781); -var FormData = __nccwpck_require__(9250); -var node_fetch = __nccwpck_require__(4956); -var coreTracing = __nccwpck_require__(2848); +var uuid = __nccwpck_require__(43415); +var util = __nccwpck_require__(73837); +var tslib = __nccwpck_require__(82107); +var xml2js = __nccwpck_require__(10488); +var coreUtil = __nccwpck_require__(80637); +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__(52557); +var tunnel = __nccwpck_require__(74294); +var stream = __nccwpck_require__(12781); +var FormData = __nccwpck_require__(46279); +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 }; } @@ -10164,7 +12133,6 @@ var xml2js__namespace = /*#__PURE__*/_interopNamespace(xml2js); var os__namespace = /*#__PURE__*/_interopNamespace(os); var http__namespace = /*#__PURE__*/_interopNamespace(http); var https__namespace = /*#__PURE__*/_interopNamespace(https); -var tough__namespace = /*#__PURE__*/_interopNamespace(tough); var tunnel__namespace = /*#__PURE__*/_interopNamespace(tunnel); var FormData__default = /*#__PURE__*/_interopDefaultLegacy(FormData); var node_fetch__default = /*#__PURE__*/_interopDefaultLegacy(node_fetch); @@ -10216,7 +12184,7 @@ class HttpHeaders { set(headerName, headerValue) { this._headersMap[getHeaderKey(headerName)] = { name: headerName, - value: headerValue.toString(), + value: headerValue.toString().trim(), }; } /** @@ -10356,7 +12324,7 @@ const Constants = { /** * The core-http version */ - coreHttpVersion: "2.2.5", + coreHttpVersion: "3.0.4", /** * Specifies HTTP. */ @@ -10434,13 +12402,6 @@ const XML_CHARKEY = "_"; // Copyright (c) Microsoft Corporation. const validUuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i; -/** - * A constant that indicates whether the environment is node.js or browser based. - */ -const isNode = typeof process !== "undefined" && - !!process.version && - !!process.versions && - !!process.versions.node; /** * Encodes an URI. * @@ -10657,6 +12618,7 @@ class Serializer { * @param mapper - The definition of data models. * @param value - The value. * @param objectName - Name of the object. Used in the error messages. + * @deprecated Removing the constraints validation on client side. */ validateConstraints(mapper, value, objectName) { const failValidation = (constraintName, constraintValue) => { @@ -10755,8 +12717,6 @@ class Serializer { payload = object; } else { - // Validate Constraints if any - this.validateConstraints(mapper, object, objectName); if (mapperType.match(/^any$/i) !== null) { payload = object; } @@ -11274,7 +13234,8 @@ function isSpecialXmlProperty(propertyName, options) { return [XML_ATTRKEY, options.xmlCharKey].includes(propertyName); } function deserializeCompositeType(serializer, mapper, responseBody, objectName, options) { - var _a; + var _a, _b; + const xmlCharKey = (_a = options.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName"); } @@ -11305,6 +13266,16 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, if (propertyMapper.xmlIsAttribute && responseBody[XML_ATTRKEY]) { instance[key] = serializer.deserialize(propertyMapper, responseBody[XML_ATTRKEY][xmlName], propertyObjectName, options); } + else if (propertyMapper.xmlIsMsText) { + if (responseBody[xmlCharKey] !== undefined) { + instance[key] = responseBody[xmlCharKey]; + } + else if (typeof responseBody === "string") { + // The special case where xml parser parses "content" into JSON of + // `{ name: "content"}` instead of `{ name: { "_": "content" }}` + instance[key] = responseBody; + } + } else { const propertyName = xmlElementName || xmlName || serializedName; if (propertyMapper.xmlIsWrapped) { @@ -11323,12 +13294,14 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, xmlName is "Cors" and xmlElementName is"CorsRule". */ const wrapped = responseBody[xmlName]; - const elementList = (_a = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _a !== void 0 ? _a : []; + const elementList = (_b = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _b !== void 0 ? _b : []; instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName, options); + handledPropertyNames.push(xmlName); } else { const property = responseBody[propertyName]; instance[key] = serializer.deserialize(propertyMapper, property, propertyObjectName, options); + handledPropertyNames.push(propertyName); } } } @@ -12661,7 +14634,6 @@ class NodeFetchHttpClient { // a mapping of proxy settings string `${host}:${port}:${username}:${password}` to agent this.proxyAgentMap = new Map(); this.keepAliveAgents = {}; - this.cookieJar = new tough__namespace.CookieJar(undefined, { looseMode: true }); } /** * Provides minimum viable error handling and the logic that executes the abstract methods. @@ -12749,7 +14721,11 @@ class NodeFetchHttpClient { body = uploadReportStream; } const platformSpecificRequestInit = await this.prepareRequest(httpRequest); - const requestInit = Object.assign({ body: body, headers: httpRequest.headers.rawHeaders(), method: httpRequest.method, signal: abortController$1.signal, redirect: "manual" }, platformSpecificRequestInit); + const requestInit = Object.assign({ body: body, headers: httpRequest.headers.rawHeaders(), method: httpRequest.method, + // the types for RequestInit are from the browser, which expects AbortSignal to + // have `reason` and `throwIfAborted`, but these don't exist on our polyfill + // for Node. + signal: abortController$1.signal, redirect: "manual" }, platformSpecificRequestInit); let operationResponse; try { const response = await this.fetch(httpRequest.url, requestInit); @@ -12874,43 +14850,16 @@ class NodeFetchHttpClient { */ async prepareRequest(httpRequest) { const requestInit = {}; - if (this.cookieJar && !httpRequest.headers.get("Cookie")) { - const cookieString = await new Promise((resolve, reject) => { - this.cookieJar.getCookieString(httpRequest.url, (err, cookie) => { - if (err) { - reject(err); - } - else { - resolve(cookie); - } - }); - }); - httpRequest.headers.set("Cookie", cookieString); - } // Set the http(s) agent requestInit.agent = this.getOrCreateAgent(httpRequest); requestInit.compress = httpRequest.decompressResponse; return requestInit; } /** - * Process an HTTP response. Handles persisting a cookie for subsequent requests if the response has a "Set-Cookie" header. + * Process an HTTP response. */ - async processRequest(operationResponse) { - if (this.cookieJar) { - const setCookieHeader = operationResponse.headers.get("Set-Cookie"); - if (setCookieHeader !== undefined) { - await new Promise((resolve, reject) => { - this.cookieJar.setCookie(setCookieHeader, operationResponse.request.url, { ignoreError: true }, (err) => { - if (err) { - reject(err); - } - else { - resolve(); - } - }); - }); - } - } + async processRequest(_operationResponse) { + /* no_op */ } } @@ -13244,7 +15193,7 @@ function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, op parsedResponse.parsedBody = response.status >= 200 && response.status < 300; } if (responseSpec.headersMapper) { - parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.rawHeaders(), "operationRes.parsedHeaders", options); + parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.toJson(), "operationRes.parsedHeaders", options); } } return parsedResponse; @@ -13310,7 +15259,7 @@ function handleErrorResponse(parsedResponse, operationSpec, responseSpec) { } // If error response has headers, try to deserialize it using default header mapper if (parsedResponse.headers && defaultHeadersMapper) { - error.response.parsedHeaders = operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.rawHeaders(), "operationRes.parsedHeaders"); + error.response.parsedHeaders = operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.toJson(), "operationRes.parsedHeaders"); } } catch (defaultError) { @@ -13511,60 +15460,6 @@ function updateRetryData(retryOptions, retryData = { retryCount: 0, retryInterva return retryData; } -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * Helper TypeGuard that checks if the value is not null or undefined. - * @param thing - Anything - * @internal - */ -function isDefined(thing) { - return typeof thing !== "undefined" && thing !== null; -} - -// Copyright (c) Microsoft Corporation. -const StandardAbortMessage$1 = "The operation was aborted."; -/** - * A wrapper for setTimeout that resolves a promise after delayInMs milliseconds. - * @param delayInMs - The number of milliseconds to be delayed. - * @param value - The value to be resolved with after a timeout of t milliseconds. - * @param options - The options for delay - currently abort options - * @param abortSignal - The abortSignal associated with containing operation. - * @param abortErrorMsg - The abort error message associated with containing operation. - * @returns - Resolved promise - */ -function delay(delayInMs, value, options) { - return new Promise((resolve, reject) => { - let timer = undefined; - let onAborted = undefined; - const rejectOnAbort = () => { - return reject(new abortController.AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage$1)); - }; - const removeListeners = () => { - if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) { - options.abortSignal.removeEventListener("abort", onAborted); - } - }; - onAborted = () => { - if (isDefined(timer)) { - clearTimeout(timer); - } - removeListeners(); - return rejectOnAbort(); - }; - if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) { - return rejectOnAbort(); - } - timer = setTimeout(() => { - removeListeners(); - resolve(value); - }, delayInMs); - if (options === null || options === void 0 ? void 0 : options.abortSignal) { - options.abortSignal.addEventListener("abort", onAborted); - } - }); -} - // Copyright (c) Microsoft Corporation. /** * Policy that retries the request as many times as configured for as long as the max retry time interval specified, each retry waiting longer to begin than the last time. @@ -13645,7 +15540,7 @@ async function retry$1(policy, request, response, retryData, requestError) { if (!isAborted && shouldRetry(policy.retryCount, shouldPolicyRetry, retryData, response)) { logger.info(`Retrying request in ${retryData.retryInterval}`); try { - await delay(retryData.retryInterval); + await coreUtil.delay(retryData.retryInterval); const res = await policy._nextPolicy.sendRequest(request.clone()); return retry$1(policy, request, res, retryData); } @@ -13940,7 +15835,7 @@ async function beginRefresh(getAccessToken, retryIntervalInMs, timeoutInMs) { } let token = await tryGetAccessToken(); while (token === null) { - await delay(retryIntervalInMs); + await coreUtil.delay(retryIntervalInMs); token = await tryGetAccessToken(); } return token; @@ -14472,7 +16367,7 @@ async function getRegistrationStatus(policy, url, originalRequest) { return true; } else { - await delay(policy._retryTimeout * 1000); + await coreUtil.delay(policy._retryTimeout * 1000); return getRegistrationStatus(policy, url, originalRequest); } } @@ -14564,7 +16459,7 @@ async function retry(policy, request, operationResponse, err, retryData) { if (shouldRetry(policy.retryCount, shouldPolicyRetry, retryData, operationResponse, err)) { // If previous operation ended with an error and the policy allows a retry, do that try { - await delay(retryData.retryInterval); + await coreUtil.delay(retryData.retryInterval); return policy._nextPolicy.sendRequest(request.clone()); } catch (nestedErr) { @@ -14639,7 +16534,7 @@ class ThrottlingRetryPolicy extends BaseRequestPolicy { const delayInMs = ThrottlingRetryPolicy.parseRetryAfterHeader(retryAfterHeader); if (delayInMs) { this.numberOfRetries += 1; - await delay(delayInMs, undefined, { + await coreUtil.delay(delayInMs, { abortSignal: httpRequest.abortSignal, abortErrorMsg: StandardAbortMessage, }); @@ -15187,7 +17082,7 @@ function createDefaultRequestPolicyFactories(authPolicyFactory, options) { factories.push(throttlingRetryPolicy()); } factories.push(deserializationPolicy(options.deserializationContentTypes)); - if (isNode) { + if (coreUtil.isNode) { factories.push(proxyPolicy(options.proxySettings)); } factories.push(logPolicy({ logger: logger.info })); @@ -15219,7 +17114,7 @@ function createPipelineFromOptions(pipelineOptions, authPolicyFactory) { const keepAliveOptions = Object.assign(Object.assign({}, DefaultKeepAliveOptions), pipelineOptions.keepAliveOptions); const retryOptions = Object.assign(Object.assign({}, DefaultRetryOptions), pipelineOptions.retryOptions); const redirectOptions = Object.assign(Object.assign({}, DefaultRedirectOptions), pipelineOptions.redirectOptions); - if (isNode) { + if (coreUtil.isNode) { requestPolicyFactories.push(proxyPolicy(pipelineOptions.proxyOptions)); } const deserializationOptions = Object.assign(Object.assign({}, DefaultDeserializationOptions), pipelineOptions.deserializationOptions); @@ -15232,7 +17127,7 @@ function createPipelineFromOptions(pipelineOptions, authPolicyFactory) { requestPolicyFactories.push(authPolicyFactory); } requestPolicyFactories.push(logPolicy(loggingOptions)); - if (isNode && pipelineOptions.decompressResponse === false) { + if (coreUtil.isNode && pipelineOptions.decompressResponse === false) { requestPolicyFactories.push(disableResponseDecompressionPolicy()); } return { @@ -15363,10 +17258,7 @@ function flattenResponse(_response, responseSpec) { } function getCredentialScopes(options, baseUri) { if (options === null || options === void 0 ? void 0 : options.credentialScopes) { - const scopes = options.credentialScopes; - return Array.isArray(scopes) - ? scopes.map((scope) => new URL(scope).toString()) - : new URL(scopes).toString(); + return options.credentialScopes; } if (baseUri) { return `${baseUri}/.default`; @@ -15595,6 +17487,14 @@ class TopicCredentials extends ApiKeyCredentials { } } +Object.defineProperty(exports, "delay", ({ + enumerable: true, + get: function () { return coreUtil.delay; } +})); +Object.defineProperty(exports, "isNode", ({ + enumerable: true, + get: function () { return coreUtil.isNode; } +})); Object.defineProperty(exports, "isTokenCredential", ({ enumerable: true, get: function () { return coreAuth.isTokenCredential; } @@ -15622,7 +17522,6 @@ exports.applyMixins = applyMixins; exports.bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy; exports.createPipelineFromOptions = createPipelineFromOptions; exports.createSpanFunction = createSpanFunction; -exports.delay = delay; exports.deserializationPolicy = deserializationPolicy; exports.deserializeResponseBody = deserializeResponseBody; exports.disableResponseDecompressionPolicy = disableResponseDecompressionPolicy; @@ -15635,7 +17534,6 @@ exports.generateUuid = generateUuid; exports.getDefaultProxySettings = getDefaultProxySettings; exports.getDefaultUserAgentValue = getDefaultUserAgentValue; exports.isDuration = isDuration; -exports.isNode = isNode; exports.isValidUuid = isValidUuid; exports.keepAlivePolicy = keepAlivePolicy; exports.logPolicy = logPolicy; @@ -15659,20 +17557,20 @@ exports.userAgentPolicy = userAgentPolicy; /***/ }), -/***/ 9250: +/***/ 46279: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var CombinedStream = __nccwpck_require__(3086); -var util = __nccwpck_require__(3837); -var path = __nccwpck_require__(1017); -var http = __nccwpck_require__(3685); -var https = __nccwpck_require__(5687); -var parseUrl = (__nccwpck_require__(7310).parse); -var fs = __nccwpck_require__(7147); -var Stream = (__nccwpck_require__(2781).Stream); -var mime = __nccwpck_require__(4826); -var asynckit = __nccwpck_require__(1113); -var populate = __nccwpck_require__(6641); +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__(63971); // Public API module.exports = FormData; @@ -16167,7 +18065,7 @@ FormData.prototype.toString = function () { /***/ }), -/***/ 6641: +/***/ 63971: /***/ ((module) => { // populates missing values @@ -16184,2171 +18082,8 @@ module.exports = function(dst, src) { /***/ }), -/***/ 4624: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; -/*! - * Copyright (c) 2015, Salesforce.com, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. 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. - * - * 3. Neither the name of Salesforce.com 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 HOLDER 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. - */ - -const punycode = __nccwpck_require__(5477); -const urlParse = (__nccwpck_require__(7310).parse); -const util = __nccwpck_require__(3837); -const pubsuffix = __nccwpck_require__(5060); -const Store = (__nccwpck_require__(802)/* .Store */ .y); -const MemoryCookieStore = (__nccwpck_require__(8400)/* .MemoryCookieStore */ .m); -const pathMatch = (__nccwpck_require__(1610)/* .pathMatch */ .U); -const VERSION = __nccwpck_require__(7154); -const { fromCallback } = __nccwpck_require__(9602); - -// From RFC6265 S4.1.1 -// note that it excludes \x3B ";" -const COOKIE_OCTETS = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/; - -const CONTROL_CHARS = /[\x00-\x1F]/; - -// From Chromium // '\r', '\n' and '\0' should be treated as a terminator in -// the "relaxed" mode, see: -// https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L60 -const TERMINATORS = ["\n", "\r", "\0"]; - -// RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"' -// Note ';' is \x3B -const PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/; - -// date-time parsing constants (RFC6265 S5.1.1) - -const DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/; - -const MONTH_TO_NUM = { - jan: 0, - feb: 1, - mar: 2, - apr: 3, - may: 4, - jun: 5, - jul: 6, - aug: 7, - sep: 8, - oct: 9, - nov: 10, - dec: 11 -}; - -const MAX_TIME = 2147483647000; // 31-bit max -const MIN_TIME = 0; // 31-bit min -const SAME_SITE_CONTEXT_VAL_ERR = - 'Invalid sameSiteContext option for getCookies(); expected one of "strict", "lax", or "none"'; - -function checkSameSiteContext(value) { - const context = String(value).toLowerCase(); - if (context === "none" || context === "lax" || context === "strict") { - return context; - } else { - return null; - } -} - -const PrefixSecurityEnum = Object.freeze({ - SILENT: "silent", - STRICT: "strict", - DISABLED: "unsafe-disabled" -}); - -// Dumped from ip-regex@4.0.0, with the following changes: -// * all capturing groups converted to non-capturing -- "(?:)" -// * support for IPv6 Scoped Literal ("%eth1") removed -// * lowercase hexadecimal only -var IP_REGEX_LOWERCASE =/(?:^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$)|(?:^(?:(?:[a-f\d]{1,4}:){7}(?:[a-f\d]{1,4}|:)|(?:[a-f\d]{1,4}:){6}(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|:[a-f\d]{1,4}|:)|(?:[a-f\d]{1,4}:){5}(?::(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,2}|:)|(?:[a-f\d]{1,4}:){4}(?:(?::[a-f\d]{1,4}){0,1}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,3}|:)|(?:[a-f\d]{1,4}:){3}(?:(?::[a-f\d]{1,4}){0,2}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,4}|:)|(?:[a-f\d]{1,4}:){2}(?:(?::[a-f\d]{1,4}){0,3}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,5}|:)|(?:[a-f\d]{1,4}:){1}(?:(?::[a-f\d]{1,4}){0,4}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,6}|:)|(?::(?:(?::[a-f\d]{1,4}){0,5}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,7}|:)))$)/; - -/* - * Parses a Natural number (i.e., non-negative integer) with either the - * *DIGIT ( non-digit *OCTET ) - * or - * *DIGIT - * grammar (RFC6265 S5.1.1). - * - * The "trailingOK" boolean controls if the grammar accepts a - * "( non-digit *OCTET )" trailer. - */ -function parseDigits(token, minDigits, maxDigits, trailingOK) { - let count = 0; - while (count < token.length) { - const c = token.charCodeAt(count); - // "non-digit = %x00-2F / %x3A-FF" - if (c <= 0x2f || c >= 0x3a) { - break; - } - count++; - } - - // constrain to a minimum and maximum number of digits. - if (count < minDigits || count > maxDigits) { - return null; - } - - if (!trailingOK && count != token.length) { - return null; - } - - return parseInt(token.substr(0, count), 10); -} - -function parseTime(token) { - const parts = token.split(":"); - const result = [0, 0, 0]; - - /* RF6256 S5.1.1: - * time = hms-time ( non-digit *OCTET ) - * hms-time = time-field ":" time-field ":" time-field - * time-field = 1*2DIGIT - */ - - if (parts.length !== 3) { - return null; - } - - for (let i = 0; i < 3; i++) { - // "time-field" must be strictly "1*2DIGIT", HOWEVER, "hms-time" can be - // followed by "( non-digit *OCTET )" so therefore the last time-field can - // have a trailer - const trailingOK = i == 2; - const num = parseDigits(parts[i], 1, 2, trailingOK); - if (num === null) { - return null; - } - result[i] = num; - } - - return result; -} - -function parseMonth(token) { - token = String(token) - .substr(0, 3) - .toLowerCase(); - const num = MONTH_TO_NUM[token]; - return num >= 0 ? num : null; -} - -/* - * RFC6265 S5.1.1 date parser (see RFC for full grammar) - */ -function parseDate(str) { - if (!str) { - return; - } - - /* RFC6265 S5.1.1: - * 2. Process each date-token sequentially in the order the date-tokens - * appear in the cookie-date - */ - const tokens = str.split(DATE_DELIM); - if (!tokens) { - return; - } - - let hour = null; - let minute = null; - let second = null; - let dayOfMonth = null; - let month = null; - let year = null; - - for (let i = 0; i < tokens.length; i++) { - const token = tokens[i].trim(); - if (!token.length) { - continue; - } - - let result; - - /* 2.1. If the found-time flag is not set and the token matches the time - * production, set the found-time flag and set the hour- value, - * minute-value, and second-value to the numbers denoted by the digits in - * the date-token, respectively. Skip the remaining sub-steps and continue - * to the next date-token. - */ - if (second === null) { - result = parseTime(token); - if (result) { - hour = result[0]; - minute = result[1]; - second = result[2]; - continue; - } - } - - /* 2.2. If the found-day-of-month flag is not set and the date-token matches - * the day-of-month production, set the found-day-of- month flag and set - * the day-of-month-value to the number denoted by the date-token. Skip - * the remaining sub-steps and continue to the next date-token. - */ - if (dayOfMonth === null) { - // "day-of-month = 1*2DIGIT ( non-digit *OCTET )" - result = parseDigits(token, 1, 2, true); - if (result !== null) { - dayOfMonth = result; - continue; - } - } - - /* 2.3. If the found-month flag is not set and the date-token matches the - * month production, set the found-month flag and set the month-value to - * the month denoted by the date-token. Skip the remaining sub-steps and - * continue to the next date-token. - */ - if (month === null) { - result = parseMonth(token); - if (result !== null) { - month = result; - continue; - } - } - - /* 2.4. If the found-year flag is not set and the date-token matches the - * year production, set the found-year flag and set the year-value to the - * number denoted by the date-token. Skip the remaining sub-steps and - * continue to the next date-token. - */ - if (year === null) { - // "year = 2*4DIGIT ( non-digit *OCTET )" - result = parseDigits(token, 2, 4, true); - if (result !== null) { - year = result; - /* From S5.1.1: - * 3. If the year-value is greater than or equal to 70 and less - * than or equal to 99, increment the year-value by 1900. - * 4. If the year-value is greater than or equal to 0 and less - * than or equal to 69, increment the year-value by 2000. - */ - if (year >= 70 && year <= 99) { - year += 1900; - } else if (year >= 0 && year <= 69) { - year += 2000; - } - } - } - } - - /* RFC 6265 S5.1.1 - * "5. Abort these steps and fail to parse the cookie-date if: - * * at least one of the found-day-of-month, found-month, found- - * year, or found-time flags is not set, - * * the day-of-month-value is less than 1 or greater than 31, - * * the year-value is less than 1601, - * * the hour-value is greater than 23, - * * the minute-value is greater than 59, or - * * the second-value is greater than 59. - * (Note that leap seconds cannot be represented in this syntax.)" - * - * So, in order as above: - */ - if ( - dayOfMonth === null || - month === null || - year === null || - second === null || - dayOfMonth < 1 || - dayOfMonth > 31 || - year < 1601 || - hour > 23 || - minute > 59 || - second > 59 - ) { - return; - } - - return new Date(Date.UTC(year, month, dayOfMonth, hour, minute, second)); -} - -function formatDate(date) { - return date.toUTCString(); -} - -// S5.1.2 Canonicalized Host Names -function canonicalDomain(str) { - if (str == null) { - return null; - } - str = str.trim().replace(/^\./, ""); // S4.1.2.3 & S5.2.3: ignore leading . - - // convert to IDN if any non-ASCII characters - if (punycode && /[^\u0001-\u007f]/.test(str)) { - str = punycode.toASCII(str); - } - - return str.toLowerCase(); -} - -// S5.1.3 Domain Matching -function domainMatch(str, domStr, canonicalize) { - if (str == null || domStr == null) { - return null; - } - if (canonicalize !== false) { - str = canonicalDomain(str); - domStr = canonicalDomain(domStr); - } - - /* - * S5.1.3: - * "A string domain-matches a given domain string if at least one of the - * following conditions hold:" - * - * " o The domain string and the string are identical. (Note that both the - * domain string and the string will have been canonicalized to lower case at - * this point)" - */ - if (str == domStr) { - return true; - } - - /* " o All of the following [three] conditions hold:" */ - - /* "* The domain string is a suffix of the string" */ - const idx = str.indexOf(domStr); - if (idx <= 0) { - return false; // it's a non-match (-1) or prefix (0) - } - - // next, check it's a proper suffix - // e.g., "a.b.c".indexOf("b.c") === 2 - // 5 === 3+2 - if (str.length !== domStr.length + idx) { - return false; // it's not a suffix - } - - /* " * The last character of the string that is not included in the - * domain string is a %x2E (".") character." */ - if (str.substr(idx-1,1) !== '.') { - return false; // doesn't align on "." - } - - /* " * The string is a host name (i.e., not an IP address)." */ - if (IP_REGEX_LOWERCASE.test(str)) { - return false; // it's an IP address - } - - return true; -} - -// RFC6265 S5.1.4 Paths and Path-Match - -/* - * "The user agent MUST use an algorithm equivalent to the following algorithm - * to compute the default-path of a cookie:" - * - * Assumption: the path (and not query part or absolute uri) is passed in. - */ -function defaultPath(path) { - // "2. If the uri-path is empty or if the first character of the uri-path is not - // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps. - if (!path || path.substr(0, 1) !== "/") { - return "/"; - } - - // "3. If the uri-path contains no more than one %x2F ("/") character, output - // %x2F ("/") and skip the remaining step." - if (path === "/") { - return path; - } - - const rightSlash = path.lastIndexOf("/"); - if (rightSlash === 0) { - return "/"; - } - - // "4. Output the characters of the uri-path from the first character up to, - // but not including, the right-most %x2F ("/")." - return path.slice(0, rightSlash); -} - -function trimTerminator(str) { - for (let t = 0; t < TERMINATORS.length; t++) { - const terminatorIdx = str.indexOf(TERMINATORS[t]); - if (terminatorIdx !== -1) { - str = str.substr(0, terminatorIdx); - } - } - - return str; -} - -function parseCookiePair(cookiePair, looseMode) { - cookiePair = trimTerminator(cookiePair); - - let firstEq = cookiePair.indexOf("="); - if (looseMode) { - if (firstEq === 0) { - // '=' is immediately at start - cookiePair = cookiePair.substr(1); - firstEq = cookiePair.indexOf("="); // might still need to split on '=' - } - } else { - // non-loose mode - if (firstEq <= 0) { - // no '=' or is at start - return; // needs to have non-empty "cookie-name" - } - } - - let cookieName, cookieValue; - if (firstEq <= 0) { - cookieName = ""; - cookieValue = cookiePair.trim(); - } else { - cookieName = cookiePair.substr(0, firstEq).trim(); - cookieValue = cookiePair.substr(firstEq + 1).trim(); - } - - if (CONTROL_CHARS.test(cookieName) || CONTROL_CHARS.test(cookieValue)) { - return; - } - - const c = new Cookie(); - c.key = cookieName; - c.value = cookieValue; - return c; -} - -function parse(str, options) { - if (!options || typeof options !== "object") { - options = {}; - } - str = str.trim(); - - // We use a regex to parse the "name-value-pair" part of S5.2 - const firstSemi = str.indexOf(";"); // S5.2 step 1 - const cookiePair = firstSemi === -1 ? str : str.substr(0, firstSemi); - const c = parseCookiePair(cookiePair, !!options.loose); - if (!c) { - return; - } - - if (firstSemi === -1) { - return c; - } - - // S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string - // (including the %x3B (";") in question)." plus later on in the same section - // "discard the first ";" and trim". - const unparsed = str.slice(firstSemi + 1).trim(); - - // "If the unparsed-attributes string is empty, skip the rest of these - // steps." - if (unparsed.length === 0) { - return c; - } - - /* - * S5.2 says that when looping over the items "[p]rocess the attribute-name - * and attribute-value according to the requirements in the following - * subsections" for every item. Plus, for many of the individual attributes - * in S5.3 it says to use the "attribute-value of the last attribute in the - * cookie-attribute-list". Therefore, in this implementation, we overwrite - * the previous value. - */ - const cookie_avs = unparsed.split(";"); - while (cookie_avs.length) { - const av = cookie_avs.shift().trim(); - if (av.length === 0) { - // happens if ";;" appears - continue; - } - const av_sep = av.indexOf("="); - let av_key, av_value; - - if (av_sep === -1) { - av_key = av; - av_value = null; - } else { - av_key = av.substr(0, av_sep); - av_value = av.substr(av_sep + 1); - } - - av_key = av_key.trim().toLowerCase(); - - if (av_value) { - av_value = av_value.trim(); - } - - switch (av_key) { - case "expires": // S5.2.1 - if (av_value) { - const exp = parseDate(av_value); - // "If the attribute-value failed to parse as a cookie date, ignore the - // cookie-av." - if (exp) { - // over and underflow not realistically a concern: V8's getTime() seems to - // store something larger than a 32-bit time_t (even with 32-bit node) - c.expires = exp; - } - } - break; - - case "max-age": // S5.2.2 - if (av_value) { - // "If the first character of the attribute-value is not a DIGIT or a "-" - // character ...[or]... If the remainder of attribute-value contains a - // non-DIGIT character, ignore the cookie-av." - if (/^-?[0-9]+$/.test(av_value)) { - const delta = parseInt(av_value, 10); - // "If delta-seconds is less than or equal to zero (0), let expiry-time - // be the earliest representable date and time." - c.setMaxAge(delta); - } - } - break; - - case "domain": // S5.2.3 - // "If the attribute-value is empty, the behavior is undefined. However, - // the user agent SHOULD ignore the cookie-av entirely." - if (av_value) { - // S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E - // (".") character." - const domain = av_value.trim().replace(/^\./, ""); - if (domain) { - // "Convert the cookie-domain to lower case." - c.domain = domain.toLowerCase(); - } - } - break; - - case "path": // S5.2.4 - /* - * "If the attribute-value is empty or if the first character of the - * attribute-value is not %x2F ("/"): - * Let cookie-path be the default-path. - * Otherwise: - * Let cookie-path be the attribute-value." - * - * We'll represent the default-path as null since it depends on the - * context of the parsing. - */ - c.path = av_value && av_value[0] === "/" ? av_value : null; - break; - - case "secure": // S5.2.5 - /* - * "If the attribute-name case-insensitively matches the string "Secure", - * the user agent MUST append an attribute to the cookie-attribute-list - * with an attribute-name of Secure and an empty attribute-value." - */ - c.secure = true; - break; - - case "httponly": // S5.2.6 -- effectively the same as 'secure' - c.httpOnly = true; - break; - - case "samesite": // RFC6265bis-02 S5.3.7 - const enforcement = av_value ? av_value.toLowerCase() : ""; - switch (enforcement) { - case "strict": - c.sameSite = "strict"; - break; - case "lax": - c.sameSite = "lax"; - break; - default: - // RFC6265bis-02 S5.3.7 step 1: - // "If cookie-av's attribute-value is not a case-insensitive match - // for "Strict" or "Lax", ignore the "cookie-av"." - // This effectively sets it to 'none' from the prototype. - break; - } - break; - - default: - c.extensions = c.extensions || []; - c.extensions.push(av); - break; - } - } - - return c; -} - -/** - * If the cookie-name begins with a case-sensitive match for the - * string "__Secure-", abort these steps and ignore the cookie - * entirely unless the cookie's secure-only-flag is true. - * @param cookie - * @returns boolean - */ -function isSecurePrefixConditionMet(cookie) { - return !cookie.key.startsWith("__Secure-") || cookie.secure; -} - -/** - * If the cookie-name begins with a case-sensitive match for the - * string "__Host-", abort these steps and ignore the cookie - * entirely unless the cookie meets all the following criteria: - * 1. The cookie's secure-only-flag is true. - * 2. The cookie's host-only-flag is true. - * 3. The cookie-attribute-list contains an attribute with an - * attribute-name of "Path", and the cookie's path is "/". - * @param cookie - * @returns boolean - */ -function isHostPrefixConditionMet(cookie) { - return ( - !cookie.key.startsWith("__Host-") || - (cookie.secure && - cookie.hostOnly && - cookie.path != null && - cookie.path === "/") - ); -} - -// avoid the V8 deoptimization monster! -function jsonParse(str) { - let obj; - try { - obj = JSON.parse(str); - } catch (e) { - return e; - } - return obj; -} - -function fromJSON(str) { - if (!str) { - return null; - } - - let obj; - if (typeof str === "string") { - obj = jsonParse(str); - if (obj instanceof Error) { - return null; - } - } else { - // assume it's an Object - obj = str; - } - - const c = new Cookie(); - for (let i = 0; i < Cookie.serializableProperties.length; i++) { - const prop = Cookie.serializableProperties[i]; - if (obj[prop] === undefined || obj[prop] === cookieDefaults[prop]) { - continue; // leave as prototype default - } - - if (prop === "expires" || prop === "creation" || prop === "lastAccessed") { - if (obj[prop] === null) { - c[prop] = null; - } else { - c[prop] = obj[prop] == "Infinity" ? "Infinity" : new Date(obj[prop]); - } - } else { - c[prop] = obj[prop]; - } - } - - return c; -} - -/* Section 5.4 part 2: - * "* Cookies with longer paths are listed before cookies with - * shorter paths. - * - * * Among cookies that have equal-length path fields, cookies with - * earlier creation-times are listed before cookies with later - * creation-times." - */ - -function cookieCompare(a, b) { - let cmp = 0; - - // descending for length: b CMP a - const aPathLen = a.path ? a.path.length : 0; - const bPathLen = b.path ? b.path.length : 0; - cmp = bPathLen - aPathLen; - if (cmp !== 0) { - return cmp; - } - - // ascending for time: a CMP b - const aTime = a.creation ? a.creation.getTime() : MAX_TIME; - const bTime = b.creation ? b.creation.getTime() : MAX_TIME; - cmp = aTime - bTime; - if (cmp !== 0) { - return cmp; - } - - // break ties for the same millisecond (precision of JavaScript's clock) - cmp = a.creationIndex - b.creationIndex; - - return cmp; -} - -// Gives the permutation of all possible pathMatch()es of a given path. The -// array is in longest-to-shortest order. Handy for indexing. -function permutePath(path) { - if (path === "/") { - return ["/"]; - } - const permutations = [path]; - while (path.length > 1) { - const lindex = path.lastIndexOf("/"); - if (lindex === 0) { - break; - } - path = path.substr(0, lindex); - permutations.push(path); - } - permutations.push("/"); - return permutations; -} - -function getCookieContext(url) { - if (url instanceof Object) { - return url; - } - // NOTE: decodeURI will throw on malformed URIs (see GH-32). - // Therefore, we will just skip decoding for such URIs. - try { - url = decodeURI(url); - } catch (err) { - // Silently swallow error - } - - return urlParse(url); -} - -const cookieDefaults = { - // the order in which the RFC has them: - key: "", - value: "", - expires: "Infinity", - maxAge: null, - domain: null, - path: null, - secure: false, - httpOnly: false, - extensions: null, - // set by the CookieJar: - hostOnly: null, - pathIsDefault: null, - creation: null, - lastAccessed: null, - sameSite: "none" -}; - -class Cookie { - constructor(options = {}) { - if (util.inspect.custom) { - this[util.inspect.custom] = this.inspect; - } - - Object.assign(this, cookieDefaults, options); - this.creation = this.creation || new Date(); - - // used to break creation ties in cookieCompare(): - Object.defineProperty(this, "creationIndex", { - configurable: false, - enumerable: false, // important for assert.deepEqual checks - writable: true, - value: ++Cookie.cookiesCreated - }); - } - - inspect() { - const now = Date.now(); - const hostOnly = this.hostOnly != null ? this.hostOnly : "?"; - const createAge = this.creation - ? `${now - this.creation.getTime()}ms` - : "?"; - const accessAge = this.lastAccessed - ? `${now - this.lastAccessed.getTime()}ms` - : "?"; - return `Cookie="${this.toString()}; hostOnly=${hostOnly}; aAge=${accessAge}; cAge=${createAge}"`; - } - - toJSON() { - const obj = {}; - - for (const prop of Cookie.serializableProperties) { - if (this[prop] === cookieDefaults[prop]) { - continue; // leave as prototype default - } - - if ( - prop === "expires" || - prop === "creation" || - prop === "lastAccessed" - ) { - if (this[prop] === null) { - obj[prop] = null; - } else { - obj[prop] = - this[prop] == "Infinity" // intentionally not === - ? "Infinity" - : this[prop].toISOString(); - } - } else if (prop === "maxAge") { - if (this[prop] !== null) { - // again, intentionally not === - obj[prop] = - this[prop] == Infinity || this[prop] == -Infinity - ? this[prop].toString() - : this[prop]; - } - } else { - if (this[prop] !== cookieDefaults[prop]) { - obj[prop] = this[prop]; - } - } - } - - return obj; - } - - clone() { - return fromJSON(this.toJSON()); - } - - validate() { - if (!COOKIE_OCTETS.test(this.value)) { - return false; - } - if ( - this.expires != Infinity && - !(this.expires instanceof Date) && - !parseDate(this.expires) - ) { - return false; - } - if (this.maxAge != null && this.maxAge <= 0) { - return false; // "Max-Age=" non-zero-digit *DIGIT - } - if (this.path != null && !PATH_VALUE.test(this.path)) { - return false; - } - - const cdomain = this.cdomain(); - if (cdomain) { - if (cdomain.match(/\.$/)) { - return false; // S4.1.2.3 suggests that this is bad. domainMatch() tests confirm this - } - const suffix = pubsuffix.getPublicSuffix(cdomain); - if (suffix == null) { - // it's a public suffix - return false; - } - } - return true; - } - - setExpires(exp) { - if (exp instanceof Date) { - this.expires = exp; - } else { - this.expires = parseDate(exp) || "Infinity"; - } - } - - setMaxAge(age) { - if (age === Infinity || age === -Infinity) { - this.maxAge = age.toString(); // so JSON.stringify() works - } else { - this.maxAge = age; - } - } - - cookieString() { - let val = this.value; - if (val == null) { - val = ""; - } - if (this.key === "") { - return val; - } - return `${this.key}=${val}`; - } - - // gives Set-Cookie header format - toString() { - let str = this.cookieString(); - - if (this.expires != Infinity) { - if (this.expires instanceof Date) { - str += `; Expires=${formatDate(this.expires)}`; - } else { - str += `; Expires=${this.expires}`; - } - } - - if (this.maxAge != null && this.maxAge != Infinity) { - str += `; Max-Age=${this.maxAge}`; - } - - if (this.domain && !this.hostOnly) { - str += `; Domain=${this.domain}`; - } - if (this.path) { - str += `; Path=${this.path}`; - } - - if (this.secure) { - str += "; Secure"; - } - if (this.httpOnly) { - str += "; HttpOnly"; - } - if (this.sameSite && this.sameSite !== "none") { - const ssCanon = Cookie.sameSiteCanonical[this.sameSite.toLowerCase()]; - str += `; SameSite=${ssCanon ? ssCanon : this.sameSite}`; - } - if (this.extensions) { - this.extensions.forEach(ext => { - str += `; ${ext}`; - }); - } - - return str; - } - - // TTL() partially replaces the "expiry-time" parts of S5.3 step 3 (setCookie() - // elsewhere) - // S5.3 says to give the "latest representable date" for which we use Infinity - // For "expired" we use 0 - TTL(now) { - /* RFC6265 S4.1.2.2 If a cookie has both the Max-Age and the Expires - * attribute, the Max-Age attribute has precedence and controls the - * expiration date of the cookie. - * (Concurs with S5.3 step 3) - */ - if (this.maxAge != null) { - return this.maxAge <= 0 ? 0 : this.maxAge * 1000; - } - - let expires = this.expires; - if (expires != Infinity) { - if (!(expires instanceof Date)) { - expires = parseDate(expires) || Infinity; - } - - if (expires == Infinity) { - return Infinity; - } - - return expires.getTime() - (now || Date.now()); - } - - return Infinity; - } - - // expiryTime() replaces the "expiry-time" parts of S5.3 step 3 (setCookie() - // elsewhere) - expiryTime(now) { - if (this.maxAge != null) { - const relativeTo = now || this.creation || new Date(); - const age = this.maxAge <= 0 ? -Infinity : this.maxAge * 1000; - return relativeTo.getTime() + age; - } - - if (this.expires == Infinity) { - return Infinity; - } - return this.expires.getTime(); - } - - // expiryDate() replaces the "expiry-time" parts of S5.3 step 3 (setCookie() - // elsewhere), except it returns a Date - expiryDate(now) { - const millisec = this.expiryTime(now); - if (millisec == Infinity) { - return new Date(MAX_TIME); - } else if (millisec == -Infinity) { - return new Date(MIN_TIME); - } else { - return new Date(millisec); - } - } - - // This replaces the "persistent-flag" parts of S5.3 step 3 - isPersistent() { - return this.maxAge != null || this.expires != Infinity; - } - - // Mostly S5.1.2 and S5.2.3: - canonicalizedDomain() { - if (this.domain == null) { - return null; - } - return canonicalDomain(this.domain); - } - - cdomain() { - return this.canonicalizedDomain(); - } -} - -Cookie.cookiesCreated = 0; -Cookie.parse = parse; -Cookie.fromJSON = fromJSON; -Cookie.serializableProperties = Object.keys(cookieDefaults); -Cookie.sameSiteLevel = { - strict: 3, - lax: 2, - none: 1 -}; - -Cookie.sameSiteCanonical = { - strict: "Strict", - lax: "Lax" -}; - -function getNormalizedPrefixSecurity(prefixSecurity) { - if (prefixSecurity != null) { - const normalizedPrefixSecurity = prefixSecurity.toLowerCase(); - /* The three supported options */ - switch (normalizedPrefixSecurity) { - case PrefixSecurityEnum.STRICT: - case PrefixSecurityEnum.SILENT: - case PrefixSecurityEnum.DISABLED: - return normalizedPrefixSecurity; - } - } - /* Default is SILENT */ - return PrefixSecurityEnum.SILENT; -} - -class CookieJar { - constructor(store, options = { rejectPublicSuffixes: true }) { - if (typeof options === "boolean") { - options = { rejectPublicSuffixes: options }; - } - this.rejectPublicSuffixes = options.rejectPublicSuffixes; - this.enableLooseMode = !!options.looseMode; - this.allowSpecialUseDomain = !!options.allowSpecialUseDomain; - this.store = store || new MemoryCookieStore(); - this.prefixSecurity = getNormalizedPrefixSecurity(options.prefixSecurity); - this._cloneSync = syncWrap("clone"); - this._importCookiesSync = syncWrap("_importCookies"); - this.getCookiesSync = syncWrap("getCookies"); - this.getCookieStringSync = syncWrap("getCookieString"); - this.getSetCookieStringsSync = syncWrap("getSetCookieStrings"); - this.removeAllCookiesSync = syncWrap("removeAllCookies"); - this.setCookieSync = syncWrap("setCookie"); - this.serializeSync = syncWrap("serialize"); - } - - setCookie(cookie, url, options, cb) { - let err; - const context = getCookieContext(url); - if (typeof options === "function") { - cb = options; - options = {}; - } - - const host = canonicalDomain(context.hostname); - const loose = options.loose || this.enableLooseMode; - - let sameSiteContext = null; - if (options.sameSiteContext) { - sameSiteContext = checkSameSiteContext(options.sameSiteContext); - if (!sameSiteContext) { - return cb(new Error(SAME_SITE_CONTEXT_VAL_ERR)); - } - } - - // S5.3 step 1 - if (typeof cookie === "string" || cookie instanceof String) { - cookie = Cookie.parse(cookie, { loose: loose }); - if (!cookie) { - err = new Error("Cookie failed to parse"); - return cb(options.ignoreError ? null : err); - } - } else if (!(cookie instanceof Cookie)) { - // If you're seeing this error, and are passing in a Cookie object, - // it *might* be a Cookie object from another loaded version of tough-cookie. - err = new Error( - "First argument to setCookie must be a Cookie object or string" - ); - return cb(options.ignoreError ? null : err); - } - - // S5.3 step 2 - const now = options.now || new Date(); // will assign later to save effort in the face of errors - - // S5.3 step 3: NOOP; persistent-flag and expiry-time is handled by getCookie() - - // S5.3 step 4: NOOP; domain is null by default - - // S5.3 step 5: public suffixes - if (this.rejectPublicSuffixes && cookie.domain) { - const suffix = pubsuffix.getPublicSuffix(cookie.cdomain()); - if (suffix == null) { - // e.g. "com" - err = new Error("Cookie has domain set to a public suffix"); - return cb(options.ignoreError ? null : err); - } - } - - // S5.3 step 6: - if (cookie.domain) { - if (!domainMatch(host, cookie.cdomain(), false)) { - err = new Error( - `Cookie not in this host's domain. Cookie:${cookie.cdomain()} Request:${host}` - ); - return cb(options.ignoreError ? null : err); - } - - if (cookie.hostOnly == null) { - // don't reset if already set - cookie.hostOnly = false; - } - } else { - cookie.hostOnly = true; - cookie.domain = host; - } - - //S5.2.4 If the attribute-value is empty or if the first character of the - //attribute-value is not %x2F ("/"): - //Let cookie-path be the default-path. - if (!cookie.path || cookie.path[0] !== "/") { - cookie.path = defaultPath(context.pathname); - cookie.pathIsDefault = true; - } - - // S5.3 step 8: NOOP; secure attribute - // S5.3 step 9: NOOP; httpOnly attribute - - // S5.3 step 10 - if (options.http === false && cookie.httpOnly) { - err = new Error("Cookie is HttpOnly and this isn't an HTTP API"); - return cb(options.ignoreError ? null : err); - } - - // 6252bis-02 S5.4 Step 13 & 14: - if (cookie.sameSite !== "none" && sameSiteContext) { - // "If the cookie's "same-site-flag" is not "None", and the cookie - // is being set from a context whose "site for cookies" is not an - // exact match for request-uri's host's registered domain, then - // abort these steps and ignore the newly created cookie entirely." - if (sameSiteContext === "none") { - err = new Error( - "Cookie is SameSite but this is a cross-origin request" - ); - return cb(options.ignoreError ? null : err); - } - } - - /* 6265bis-02 S5.4 Steps 15 & 16 */ - const ignoreErrorForPrefixSecurity = - this.prefixSecurity === PrefixSecurityEnum.SILENT; - const prefixSecurityDisabled = - this.prefixSecurity === PrefixSecurityEnum.DISABLED; - /* If prefix checking is not disabled ...*/ - if (!prefixSecurityDisabled) { - let errorFound = false; - let errorMsg; - /* Check secure prefix condition */ - if (!isSecurePrefixConditionMet(cookie)) { - errorFound = true; - errorMsg = "Cookie has __Secure prefix but Secure attribute is not set"; - } else if (!isHostPrefixConditionMet(cookie)) { - /* Check host prefix condition */ - errorFound = true; - errorMsg = - "Cookie has __Host prefix but either Secure or HostOnly attribute is not set or Path is not '/'"; - } - if (errorFound) { - return cb( - options.ignoreError || ignoreErrorForPrefixSecurity - ? null - : new Error(errorMsg) - ); - } - } - - const store = this.store; - - if (!store.updateCookie) { - store.updateCookie = function(oldCookie, newCookie, cb) { - this.putCookie(newCookie, cb); - }; - } - - function withCookie(err, oldCookie) { - if (err) { - return cb(err); - } - - const next = function(err) { - if (err) { - return cb(err); - } else { - cb(null, cookie); - } - }; - - if (oldCookie) { - // S5.3 step 11 - "If the cookie store contains a cookie with the same name, - // domain, and path as the newly created cookie:" - if (options.http === false && oldCookie.httpOnly) { - // step 11.2 - err = new Error("old Cookie is HttpOnly and this isn't an HTTP API"); - return cb(options.ignoreError ? null : err); - } - cookie.creation = oldCookie.creation; // step 11.3 - cookie.creationIndex = oldCookie.creationIndex; // preserve tie-breaker - cookie.lastAccessed = now; - // Step 11.4 (delete cookie) is implied by just setting the new one: - store.updateCookie(oldCookie, cookie, next); // step 12 - } else { - cookie.creation = cookie.lastAccessed = now; - store.putCookie(cookie, next); // step 12 - } - } - - store.findCookie(cookie.domain, cookie.path, cookie.key, withCookie); - } - - // RFC6365 S5.4 - getCookies(url, options, cb) { - const context = getCookieContext(url); - if (typeof options === "function") { - cb = options; - options = {}; - } - - const host = canonicalDomain(context.hostname); - const path = context.pathname || "/"; - - let secure = options.secure; - if ( - secure == null && - context.protocol && - (context.protocol == "https:" || context.protocol == "wss:") - ) { - secure = true; - } - - let sameSiteLevel = 0; - if (options.sameSiteContext) { - const sameSiteContext = checkSameSiteContext(options.sameSiteContext); - sameSiteLevel = Cookie.sameSiteLevel[sameSiteContext]; - if (!sameSiteLevel) { - return cb(new Error(SAME_SITE_CONTEXT_VAL_ERR)); - } - } - - let http = options.http; - if (http == null) { - http = true; - } - - const now = options.now || Date.now(); - const expireCheck = options.expire !== false; - const allPaths = !!options.allPaths; - const store = this.store; - - function matchingCookie(c) { - // "Either: - // The cookie's host-only-flag is true and the canonicalized - // request-host is identical to the cookie's domain. - // Or: - // The cookie's host-only-flag is false and the canonicalized - // request-host domain-matches the cookie's domain." - if (c.hostOnly) { - if (c.domain != host) { - return false; - } - } else { - if (!domainMatch(host, c.domain, false)) { - return false; - } - } - - // "The request-uri's path path-matches the cookie's path." - if (!allPaths && !pathMatch(path, c.path)) { - return false; - } - - // "If the cookie's secure-only-flag is true, then the request-uri's - // scheme must denote a "secure" protocol" - if (c.secure && !secure) { - return false; - } - - // "If the cookie's http-only-flag is true, then exclude the cookie if the - // cookie-string is being generated for a "non-HTTP" API" - if (c.httpOnly && !http) { - return false; - } - - // RFC6265bis-02 S5.3.7 - if (sameSiteLevel) { - const cookieLevel = Cookie.sameSiteLevel[c.sameSite || "none"]; - if (cookieLevel > sameSiteLevel) { - // only allow cookies at or below the request level - return false; - } - } - - // deferred from S5.3 - // non-RFC: allow retention of expired cookies by choice - if (expireCheck && c.expiryTime() <= now) { - store.removeCookie(c.domain, c.path, c.key, () => {}); // result ignored - return false; - } - - return true; - } - - store.findCookies( - host, - allPaths ? null : path, - this.allowSpecialUseDomain, - (err, cookies) => { - if (err) { - return cb(err); - } - - cookies = cookies.filter(matchingCookie); - - // sorting of S5.4 part 2 - if (options.sort !== false) { - cookies = cookies.sort(cookieCompare); - } - - // S5.4 part 3 - const now = new Date(); - for (const cookie of cookies) { - cookie.lastAccessed = now; - } - // TODO persist lastAccessed - - cb(null, cookies); - } - ); - } - - getCookieString(...args) { - const cb = args.pop(); - const next = function(err, cookies) { - if (err) { - cb(err); - } else { - cb( - null, - cookies - .sort(cookieCompare) - .map(c => c.cookieString()) - .join("; ") - ); - } - }; - args.push(next); - this.getCookies.apply(this, args); - } - - getSetCookieStrings(...args) { - const cb = args.pop(); - const next = function(err, cookies) { - if (err) { - cb(err); - } else { - cb( - null, - cookies.map(c => { - return c.toString(); - }) - ); - } - }; - args.push(next); - this.getCookies.apply(this, args); - } - - serialize(cb) { - let type = this.store.constructor.name; - if (type === "Object") { - type = null; - } - - // update README.md "Serialization Format" if you change this, please! - const serialized = { - // The version of tough-cookie that serialized this jar. Generally a good - // practice since future versions can make data import decisions based on - // known past behavior. When/if this matters, use `semver`. - version: `tough-cookie@${VERSION}`, - - // add the store type, to make humans happy: - storeType: type, - - // CookieJar configuration: - rejectPublicSuffixes: !!this.rejectPublicSuffixes, - - // this gets filled from getAllCookies: - cookies: [] - }; - - if ( - !( - this.store.getAllCookies && - typeof this.store.getAllCookies === "function" - ) - ) { - return cb( - new Error( - "store does not support getAllCookies and cannot be serialized" - ) - ); - } - - this.store.getAllCookies((err, cookies) => { - if (err) { - return cb(err); - } - - serialized.cookies = cookies.map(cookie => { - // convert to serialized 'raw' cookies - cookie = cookie instanceof Cookie ? cookie.toJSON() : cookie; - - // Remove the index so new ones get assigned during deserialization - delete cookie.creationIndex; - - return cookie; - }); - - return cb(null, serialized); - }); - } - - toJSON() { - return this.serializeSync(); - } - - // use the class method CookieJar.deserialize instead of calling this directly - _importCookies(serialized, cb) { - let cookies = serialized.cookies; - if (!cookies || !Array.isArray(cookies)) { - return cb(new Error("serialized jar has no cookies array")); - } - cookies = cookies.slice(); // do not modify the original - - const putNext = err => { - if (err) { - return cb(err); - } - - if (!cookies.length) { - return cb(err, this); - } - - let cookie; - try { - cookie = fromJSON(cookies.shift()); - } catch (e) { - return cb(e); - } - - if (cookie === null) { - return putNext(null); // skip this cookie - } - - this.store.putCookie(cookie, putNext); - }; - - putNext(); - } - - clone(newStore, cb) { - if (arguments.length === 1) { - cb = newStore; - newStore = null; - } - - this.serialize((err, serialized) => { - if (err) { - return cb(err); - } - CookieJar.deserialize(serialized, newStore, cb); - }); - } - - cloneSync(newStore) { - if (arguments.length === 0) { - return this._cloneSync(); - } - if (!newStore.synchronous) { - throw new Error( - "CookieJar clone destination store is not synchronous; use async API instead." - ); - } - return this._cloneSync(newStore); - } - - removeAllCookies(cb) { - const store = this.store; - - // Check that the store implements its own removeAllCookies(). The default - // implementation in Store will immediately call the callback with a "not - // implemented" Error. - if ( - typeof store.removeAllCookies === "function" && - store.removeAllCookies !== Store.prototype.removeAllCookies - ) { - return store.removeAllCookies(cb); - } - - store.getAllCookies((err, cookies) => { - if (err) { - return cb(err); - } - - if (cookies.length === 0) { - return cb(null); - } - - let completedCount = 0; - const removeErrors = []; - - function removeCookieCb(removeErr) { - if (removeErr) { - removeErrors.push(removeErr); - } - - completedCount++; - - if (completedCount === cookies.length) { - return cb(removeErrors.length ? removeErrors[0] : null); - } - } - - cookies.forEach(cookie => { - store.removeCookie( - cookie.domain, - cookie.path, - cookie.key, - removeCookieCb - ); - }); - }); - } - - static deserialize(strOrObj, store, cb) { - if (arguments.length !== 3) { - // store is optional - cb = store; - store = null; - } - - let serialized; - if (typeof strOrObj === "string") { - serialized = jsonParse(strOrObj); - if (serialized instanceof Error) { - return cb(serialized); - } - } else { - serialized = strOrObj; - } - - const jar = new CookieJar(store, serialized.rejectPublicSuffixes); - jar._importCookies(serialized, err => { - if (err) { - return cb(err); - } - cb(null, jar); - }); - } - - static deserializeSync(strOrObj, store) { - const serialized = - typeof strOrObj === "string" ? JSON.parse(strOrObj) : strOrObj; - const jar = new CookieJar(store, serialized.rejectPublicSuffixes); - - // catch this mistake early: - if (!jar.store.synchronous) { - throw new Error( - "CookieJar store is not synchronous; use async API instead." - ); - } - - jar._importCookiesSync(serialized); - return jar; - } -} -CookieJar.fromJSON = CookieJar.deserializeSync; - -[ - "_importCookies", - "clone", - "getCookies", - "getCookieString", - "getSetCookieStrings", - "removeAllCookies", - "serialize", - "setCookie" -].forEach(name => { - CookieJar.prototype[name] = fromCallback(CookieJar.prototype[name]); -}); -CookieJar.deserialize = fromCallback(CookieJar.deserialize); - -// Use a closure to provide a true imperative API for synchronous stores. -function syncWrap(method) { - return function(...args) { - if (!this.store.synchronous) { - throw new Error( - "CookieJar store is not synchronous; use async API instead." - ); - } - - let syncErr, syncResult; - this[method](...args, (err, result) => { - syncErr = err; - syncResult = result; - }); - - if (syncErr) { - throw syncErr; - } - return syncResult; - }; -} - -exports.version = VERSION; -exports.CookieJar = CookieJar; -exports.Cookie = Cookie; -exports.Store = Store; -exports.MemoryCookieStore = MemoryCookieStore; -exports.parseDate = parseDate; -exports.formatDate = formatDate; -exports.parse = parse; -exports.fromJSON = fromJSON; -exports.domainMatch = domainMatch; -exports.defaultPath = defaultPath; -exports.pathMatch = pathMatch; -exports.getPublicSuffix = pubsuffix.getPublicSuffix; -exports.cookieCompare = cookieCompare; -exports.permuteDomain = __nccwpck_require__(1271).permuteDomain; -exports.permutePath = permutePath; -exports.canonicalDomain = canonicalDomain; -exports.PrefixSecurityEnum = PrefixSecurityEnum; - - -/***/ }), - -/***/ 8400: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; -/*! - * Copyright (c) 2015, Salesforce.com, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. 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. - * - * 3. Neither the name of Salesforce.com 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 HOLDER 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. - */ - -const { fromCallback } = __nccwpck_require__(9602); -const Store = (__nccwpck_require__(802)/* .Store */ .y); -const permuteDomain = (__nccwpck_require__(1271).permuteDomain); -const pathMatch = (__nccwpck_require__(1610)/* .pathMatch */ .U); -const util = __nccwpck_require__(3837); - -class MemoryCookieStore extends Store { - constructor() { - super(); - this.synchronous = true; - this.idx = {}; - if (util.inspect.custom) { - this[util.inspect.custom] = this.inspect; - } - } - - inspect() { - return `{ idx: ${util.inspect(this.idx, false, 2)} }`; - } - - findCookie(domain, path, key, cb) { - if (!this.idx[domain]) { - return cb(null, undefined); - } - if (!this.idx[domain][path]) { - return cb(null, undefined); - } - return cb(null, this.idx[domain][path][key] || null); - } - findCookies(domain, path, allowSpecialUseDomain, cb) { - const results = []; - if (typeof allowSpecialUseDomain === "function") { - cb = allowSpecialUseDomain; - allowSpecialUseDomain = false; - } - if (!domain) { - return cb(null, []); - } - - let pathMatcher; - if (!path) { - // null means "all paths" - pathMatcher = function matchAll(domainIndex) { - for (const curPath in domainIndex) { - const pathIndex = domainIndex[curPath]; - for (const key in pathIndex) { - results.push(pathIndex[key]); - } - } - }; - } else { - pathMatcher = function matchRFC(domainIndex) { - //NOTE: we should use path-match algorithm from S5.1.4 here - //(see : https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/canonical_cookie.cc#L299) - Object.keys(domainIndex).forEach(cookiePath => { - if (pathMatch(path, cookiePath)) { - const pathIndex = domainIndex[cookiePath]; - for (const key in pathIndex) { - results.push(pathIndex[key]); - } - } - }); - }; - } - - const domains = permuteDomain(domain, allowSpecialUseDomain) || [domain]; - const idx = this.idx; - domains.forEach(curDomain => { - const domainIndex = idx[curDomain]; - if (!domainIndex) { - return; - } - pathMatcher(domainIndex); - }); - - cb(null, results); - } - - putCookie(cookie, cb) { - if (!this.idx[cookie.domain]) { - this.idx[cookie.domain] = {}; - } - if (!this.idx[cookie.domain][cookie.path]) { - this.idx[cookie.domain][cookie.path] = {}; - } - this.idx[cookie.domain][cookie.path][cookie.key] = cookie; - cb(null); - } - updateCookie(oldCookie, newCookie, cb) { - // updateCookie() may avoid updating cookies that are identical. For example, - // lastAccessed may not be important to some stores and an equality - // comparison could exclude that field. - this.putCookie(newCookie, cb); - } - removeCookie(domain, path, key, cb) { - if ( - this.idx[domain] && - this.idx[domain][path] && - this.idx[domain][path][key] - ) { - delete this.idx[domain][path][key]; - } - cb(null); - } - removeCookies(domain, path, cb) { - if (this.idx[domain]) { - if (path) { - delete this.idx[domain][path]; - } else { - delete this.idx[domain]; - } - } - return cb(null); - } - removeAllCookies(cb) { - this.idx = {}; - return cb(null); - } - getAllCookies(cb) { - const cookies = []; - const idx = this.idx; - - const domains = Object.keys(idx); - domains.forEach(domain => { - const paths = Object.keys(idx[domain]); - paths.forEach(path => { - const keys = Object.keys(idx[domain][path]); - keys.forEach(key => { - if (key !== null) { - cookies.push(idx[domain][path][key]); - } - }); - }); - }); - - // Sort by creationIndex so deserializing retains the creation order. - // When implementing your own store, this SHOULD retain the order too - cookies.sort((a, b) => { - return (a.creationIndex || 0) - (b.creationIndex || 0); - }); - - cb(null, cookies); - } -} - -[ - "findCookie", - "findCookies", - "putCookie", - "updateCookie", - "removeCookie", - "removeCookies", - "removeAllCookies", - "getAllCookies" -].forEach(name => { - MemoryCookieStore[name] = fromCallback(MemoryCookieStore.prototype[name]); -}); - -exports.m = MemoryCookieStore; - - -/***/ }), - -/***/ 1610: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; -/*! - * Copyright (c) 2015, Salesforce.com, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. 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. - * - * 3. Neither the name of Salesforce.com 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 HOLDER 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. - */ - -/* - * "A request-path path-matches a given cookie-path if at least one of the - * following conditions holds:" - */ -function pathMatch(reqPath, cookiePath) { - // "o The cookie-path and the request-path are identical." - if (cookiePath === reqPath) { - return true; - } - - const idx = reqPath.indexOf(cookiePath); - if (idx === 0) { - // "o The cookie-path is a prefix of the request-path, and the last - // character of the cookie-path is %x2F ("/")." - if (cookiePath.substr(-1) === "/") { - return true; - } - - // " o The cookie-path is a prefix of the request-path, and the first - // character of the request-path that is not included in the cookie- path - // is a %x2F ("/") character." - if (reqPath.substr(cookiePath.length, 1) === "/") { - return true; - } - } - - return false; -} - -exports.U = pathMatch; - - -/***/ }), - -/***/ 1271: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; -/*! - * Copyright (c) 2015, Salesforce.com, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. 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. - * - * 3. Neither the name of Salesforce.com 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 HOLDER 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. - */ - -const pubsuffix = __nccwpck_require__(5060); - -// Gives the permutation of all possible domainMatch()es of a given domain. The -// array is in shortest-to-longest order. Handy for indexing. -const SPECIAL_USE_DOMAINS = ["local"]; // RFC 6761 -function permuteDomain(domain, allowSpecialUseDomain) { - let pubSuf = null; - if (allowSpecialUseDomain) { - const domainParts = domain.split("."); - if (SPECIAL_USE_DOMAINS.includes(domainParts[domainParts.length - 1])) { - pubSuf = `${domainParts[domainParts.length - 2]}.${ - domainParts[domainParts.length - 1] - }`; - } else { - pubSuf = pubsuffix.getPublicSuffix(domain); - } - } else { - pubSuf = pubsuffix.getPublicSuffix(domain); - } - - if (!pubSuf) { - return null; - } - if (pubSuf == domain) { - return [domain]; - } - - const prefix = domain.slice(0, -(pubSuf.length + 1)); // ".example.com" - const parts = prefix.split(".").reverse(); - let cur = pubSuf; - const permutations = [cur]; - while (parts.length) { - cur = `${parts.shift()}.${cur}`; - permutations.push(cur); - } - return permutations; -} - -exports.permuteDomain = permuteDomain; - - -/***/ }), - -/***/ 5060: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; -/*! - * Copyright (c) 2018, Salesforce.com, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. 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. - * - * 3. Neither the name of Salesforce.com 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 HOLDER 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. - */ - -const psl = __nccwpck_require__(1464); - -function getPublicSuffix(domain) { - return psl.get(domain); -} - -exports.getPublicSuffix = getPublicSuffix; - - -/***/ }), - -/***/ 802: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; -/*! - * Copyright (c) 2015, Salesforce.com, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. 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. - * - * 3. Neither the name of Salesforce.com 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 HOLDER 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. - */ - -/*jshint unused:false */ - -class Store { - constructor() { - this.synchronous = false; - } - - findCookie(domain, path, key, cb) { - throw new Error("findCookie is not implemented"); - } - - findCookies(domain, path, allowSpecialUseDomain, cb) { - throw new Error("findCookies is not implemented"); - } - - putCookie(cookie, cb) { - throw new Error("putCookie is not implemented"); - } - - updateCookie(oldCookie, newCookie, cb) { - // recommended default implementation: - // return this.putCookie(newCookie, cb); - throw new Error("updateCookie is not implemented"); - } - - removeCookie(domain, path, key, cb) { - throw new Error("removeCookie is not implemented"); - } - - removeCookies(domain, path, cb) { - throw new Error("removeCookies is not implemented"); - } - - removeAllCookies(cb) { - throw new Error("removeAllCookies is not implemented"); - } - - getAllCookies(cb) { - throw new Error( - "getAllCookies is not implemented (therefore jar cannot be serialized)" - ); - } -} - -exports.y = Store; - - -/***/ }), - -/***/ 7154: -/***/ ((module) => { - -// generated by genversion -module.exports = '4.0.0' - - -/***/ }), - -/***/ 9262: -/***/ ((module) => { +/***/ 82107: +/***/ ((module) => { /****************************************************************************** Copyright (c) Microsoft Corporation. @@ -18364,12 +18099,16 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ -/* global global, define, System, Reflect, Promise */ +/* global global, define, Symbol, Reflect, Promise, SuppressedError */ var __extends; var __assign; var __rest; var __decorate; var __param; +var __esDecorate; +var __runInitializers; +var __propKey; +var __setFunctionName; var __metadata; var __awaiter; var __generator; @@ -18390,6 +18129,8 @@ var __classPrivateFieldGet; var __classPrivateFieldSet; var __classPrivateFieldIn; var __createBinding; +var __addDisposableResource; +var __disposeResources; (function (factory) { var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; if (typeof define === "function" && define.amd) { @@ -18457,8 +18198,53 @@ var __createBinding; return function (target, key) { decorator(target, key, paramIndex); } }; - __metadata = function (metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; + }; + + __runInitializers = function (thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; + }; + + __propKey = function (x) { + return typeof x === "symbol" ? x : "".concat(x); + }; + + __setFunctionName = function (f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); + }; + + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); }; __awaiter = function (thisArg, _arguments, P, generator) { @@ -18477,7 +18263,7 @@ var __createBinding; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); - while (_) try { + while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { @@ -18589,7 +18375,7 @@ var __createBinding; __asyncDelegator = function (o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } }; __asyncValues = function (o) { @@ -18641,11 +18427,62 @@ var __createBinding; return typeof state === "function" ? receiver === state : state.has(receiver); }; + __addDisposableResource = function (env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + env.stack.push({ value: value, dispose: dispose, async: async }); + } + else if (async) { + env.stack.push({ async: true }); + } + return value; + }; + + var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; + }; + + __disposeResources = function (env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + function next() { + while (env.stack.length) { + var rec = env.stack.pop(); + try { + var result = rec.dispose && rec.dispose.call(rec.value); + if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); + } + catch (e) { + fail(e); + } + } + if (env.hasError) throw env.error; + } + return next(); + }; + exporter("__extends", __extends); exporter("__assign", __assign); exporter("__rest", __rest); exporter("__decorate", __decorate); exporter("__param", __param); + exporter("__esDecorate", __esDecorate); + exporter("__runInitializers", __runInitializers); + exporter("__propKey", __propKey); + exporter("__setFunctionName", __setFunctionName); exporter("__metadata", __metadata); exporter("__awaiter", __awaiter); exporter("__generator", __generator); @@ -18666,12 +18503,14 @@ var __createBinding; exporter("__classPrivateFieldGet", __classPrivateFieldGet); exporter("__classPrivateFieldSet", __classPrivateFieldSet); exporter("__classPrivateFieldIn", __classPrivateFieldIn); + exporter("__addDisposableResource", __addDisposableResource); + exporter("__disposeResources", __disposeResources); }); /***/ }), -/***/ 3408: +/***/ 43415: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -18735,29 +18574,29 @@ Object.defineProperty(exports, "parse", ({ } })); -var _v = _interopRequireDefault(__nccwpck_require__(1262)); +var _v = _interopRequireDefault(__nccwpck_require__(14757)); -var _v2 = _interopRequireDefault(__nccwpck_require__(2378)); +var _v2 = _interopRequireDefault(__nccwpck_require__(19982)); -var _v3 = _interopRequireDefault(__nccwpck_require__(1020)); +var _v3 = _interopRequireDefault(__nccwpck_require__(85393)); -var _v4 = _interopRequireDefault(__nccwpck_require__(8737)); +var _v4 = _interopRequireDefault(__nccwpck_require__(48788)); -var _nil = _interopRequireDefault(__nccwpck_require__(6543)); +var _nil = _interopRequireDefault(__nccwpck_require__(657)); -var _version = _interopRequireDefault(__nccwpck_require__(6890)); +var _version = _interopRequireDefault(__nccwpck_require__(37909)); -var _validate = _interopRequireDefault(__nccwpck_require__(5290)); +var _validate = _interopRequireDefault(__nccwpck_require__(64418)); -var _stringify = _interopRequireDefault(__nccwpck_require__(7158)); +var _stringify = _interopRequireDefault(__nccwpck_require__(74794)); -var _parse = _interopRequireDefault(__nccwpck_require__(2483)); +var _parse = _interopRequireDefault(__nccwpck_require__(67079)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /***/ }), -/***/ 2440: +/***/ 64153: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -18787,7 +18626,7 @@ exports["default"] = _default; /***/ }), -/***/ 6543: +/***/ 657: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -18802,7 +18641,7 @@ exports["default"] = _default; /***/ }), -/***/ 2483: +/***/ 67079: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -18813,7 +18652,7 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _validate = _interopRequireDefault(__nccwpck_require__(5290)); +var _validate = _interopRequireDefault(__nccwpck_require__(64418)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -18854,7 +18693,7 @@ exports["default"] = _default; /***/ }), -/***/ 8054: +/***/ 90690: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -18869,7 +18708,7 @@ exports["default"] = _default; /***/ }), -/***/ 8399: +/***/ 10979: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -18900,7 +18739,7 @@ function rng() { /***/ }), -/***/ 6379: +/***/ 36631: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -18930,7 +18769,7 @@ exports["default"] = _default; /***/ }), -/***/ 7158: +/***/ 74794: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -18941,7 +18780,7 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _validate = _interopRequireDefault(__nccwpck_require__(5290)); +var _validate = _interopRequireDefault(__nccwpck_require__(64418)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -18976,7 +18815,7 @@ exports["default"] = _default; /***/ }), -/***/ 1262: +/***/ 14757: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -18987,9 +18826,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _rng = _interopRequireDefault(__nccwpck_require__(8399)); +var _rng = _interopRequireDefault(__nccwpck_require__(10979)); -var _stringify = _interopRequireDefault(__nccwpck_require__(7158)); +var _stringify = _interopRequireDefault(__nccwpck_require__(74794)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -19090,7 +18929,7 @@ exports["default"] = _default; /***/ }), -/***/ 2378: +/***/ 19982: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -19101,9 +18940,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _v = _interopRequireDefault(__nccwpck_require__(5521)); +var _v = _interopRequireDefault(__nccwpck_require__(44085)); -var _md = _interopRequireDefault(__nccwpck_require__(2440)); +var _md = _interopRequireDefault(__nccwpck_require__(64153)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -19113,7 +18952,7 @@ exports["default"] = _default; /***/ }), -/***/ 5521: +/***/ 44085: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -19125,9 +18964,9 @@ Object.defineProperty(exports, "__esModule", ({ exports["default"] = _default; exports.URL = exports.DNS = void 0; -var _stringify = _interopRequireDefault(__nccwpck_require__(7158)); +var _stringify = _interopRequireDefault(__nccwpck_require__(74794)); -var _parse = _interopRequireDefault(__nccwpck_require__(2483)); +var _parse = _interopRequireDefault(__nccwpck_require__(67079)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -19198,7 +19037,7 @@ function _default(name, version, hashfunc) { /***/ }), -/***/ 1020: +/***/ 85393: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -19209,9 +19048,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _rng = _interopRequireDefault(__nccwpck_require__(8399)); +var _rng = _interopRequireDefault(__nccwpck_require__(10979)); -var _stringify = _interopRequireDefault(__nccwpck_require__(7158)); +var _stringify = _interopRequireDefault(__nccwpck_require__(74794)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -19242,7 +19081,7 @@ exports["default"] = _default; /***/ }), -/***/ 8737: +/***/ 48788: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -19253,9 +19092,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _v = _interopRequireDefault(__nccwpck_require__(5521)); +var _v = _interopRequireDefault(__nccwpck_require__(44085)); -var _sha = _interopRequireDefault(__nccwpck_require__(6379)); +var _sha = _interopRequireDefault(__nccwpck_require__(36631)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -19265,7 +19104,7 @@ exports["default"] = _default; /***/ }), -/***/ 5290: +/***/ 64418: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -19276,7 +19115,7 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _regex = _interopRequireDefault(__nccwpck_require__(8054)); +var _regex = _interopRequireDefault(__nccwpck_require__(90690)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -19289,7 +19128,7 @@ exports["default"] = _default; /***/ }), -/***/ 6890: +/***/ 37909: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -19300,7 +19139,7 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _validate = _interopRequireDefault(__nccwpck_require__(5290)); +var _validate = _interopRequireDefault(__nccwpck_require__(64418)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -19317,766 +19156,718 @@ exports["default"] = _default; /***/ }), -/***/ 3563: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 21002: +/***/ (function(__unused_webpack_module, exports) { -"use strict"; +// Generated by CoffeeScript 1.12.7 +(function() { + "use strict"; + exports.stripBOM = function(str) { + if (str[0] === '\uFEFF') { + return str.substring(1); + } else { + return str; + } + }; +}).call(this); -Object.defineProperty(exports, "__esModule", ({ value: true })); -var logger$1 = __nccwpck_require__(9241); +/***/ }), -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * When a poller is manually stopped through the `stopPolling` method, - * the poller will be rejected with an instance of the PollerStoppedError. - */ -class PollerStoppedError extends Error { - constructor(message) { - super(message); - this.name = "PollerStoppedError"; - Object.setPrototypeOf(this, PollerStoppedError.prototype); - } -} -/** - * When a poller is cancelled through the `cancelOperation` method, - * the poller will be rejected with an instance of the PollerCancelledError. - */ -class PollerCancelledError extends Error { - constructor(message) { - super(message); - this.name = "PollerCancelledError"; - Object.setPrototypeOf(this, PollerCancelledError.prototype); - } -} -/** - * A class that represents the definition of a program that polls through consecutive requests - * until it reaches a state of completion. - * - * A poller can be executed manually, by polling request by request by calling to the `poll()` method repeatedly, until its operation is completed. - * It also provides a way to wait until the operation completes, by calling `pollUntilDone()` and waiting until the operation finishes. - * Pollers can also request the cancellation of the ongoing process to whom is providing the underlying long running operation. - * - * ```ts - * const poller = new MyPoller(); - * - * // Polling just once: - * await poller.poll(); - * - * // We can try to cancel the request here, by calling: - * // - * // await poller.cancelOperation(); - * // - * - * // Getting the final result: - * const result = await poller.pollUntilDone(); - * ``` - * - * The Poller is defined by two types, a type representing the state of the poller, which - * must include a basic set of properties from `PollOperationState`, - * and a return type defined by `TResult`, which can be anything. - * - * The Poller class implements the `PollerLike` interface, which allows poller implementations to avoid having - * to export the Poller's class directly, and instead only export the already instantiated poller with the PollerLike type. - * - * ```ts - * class Client { - * public async makePoller: PollerLike { - * const poller = new MyPoller({}); - * // It might be preferred to return the poller after the first request is made, - * // so that some information can be obtained right away. - * await poller.poll(); - * return poller; - * } - * } - * - * const poller: PollerLike = myClient.makePoller(); - * ``` - * - * A poller can be created through its constructor, then it can be polled until it's completed. - * At any point in time, the state of the poller can be obtained without delay through the getOperationState method. - * At any point in time, the intermediate forms of the result type can be requested without delay. - * Once the underlying operation is marked as completed, the poller will stop and the final value will be returned. - * - * ```ts - * const poller = myClient.makePoller(); - * const state: MyOperationState = poller.getOperationState(); - * - * // The intermediate result can be obtained at any time. - * const result: MyResult | undefined = poller.getResult(); - * - * // The final result can only be obtained after the poller finishes. - * const result: MyResult = await poller.pollUntilDone(); - * ``` - * - */ -// eslint-disable-next-line no-use-before-define -class Poller { - /** - * A poller needs to be initialized by passing in at least the basic properties of the `PollOperation`. - * - * When writing an implementation of a Poller, this implementation needs to deal with the initialization - * of any custom state beyond the basic definition of the poller. The basic poller assumes that the poller's - * operation has already been defined, at least its basic properties. The code below shows how to approach - * the definition of the constructor of a new custom poller. - * - * ```ts - * export class MyPoller extends Poller { - * constructor({ - * // Anything you might need outside of the basics - * }) { - * let state: MyOperationState = { - * privateProperty: private, - * publicProperty: public, - * }; - * - * const operation = { - * state, - * update, - * cancel, - * toString - * } - * - * // Sending the operation to the parent's constructor. - * super(operation); - * - * // You can assign more local properties here. - * } - * } - * ``` - * - * Inside of this constructor, a new promise is created. This will be used to - * tell the user when the poller finishes (see `pollUntilDone()`). The promise's - * resolve and reject methods are also used internally to control when to resolve - * or reject anyone waiting for the poller to finish. - * - * The constructor of a custom implementation of a poller is where any serialized version of - * a previous poller's operation should be deserialized into the operation sent to the - * base constructor. For example: - * - * ```ts - * export class MyPoller extends Poller { - * constructor( - * baseOperation: string | undefined - * ) { - * let state: MyOperationState = {}; - * if (baseOperation) { - * state = { - * ...JSON.parse(baseOperation).state, - * ...state - * }; - * } - * const operation = { - * state, - * // ... - * } - * super(operation); - * } - * } - * ``` - * - * @param operation - Must contain the basic properties of `PollOperation`. - */ - constructor(operation) { - this.stopped = true; - this.pollProgressCallbacks = []; - this.operation = operation; - this.promise = new Promise((resolve, reject) => { - this.resolve = resolve; - this.reject = reject; - }); - // This prevents the UnhandledPromiseRejectionWarning in node.js from being thrown. - // The above warning would get thrown if `poller.poll` is called, it returns an error, - // and pullUntilDone did not have a .catch or await try/catch on it's return value. - this.promise.catch(() => { - /* intentionally blank */ - }); - } - /** - * Starts a loop that will break only if the poller is done - * or if the poller is stopped. - */ - async startPolling() { - if (this.stopped) { - this.stopped = false; - } - while (!this.isStopped() && !this.isDone()) { - await this.poll(); - await this.delay(); - } +/***/ 9737: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +// Generated by CoffeeScript 1.12.7 +(function() { + "use strict"; + var builder, defaults, escapeCDATA, requiresCDATA, wrapCDATA, + hasProp = {}.hasOwnProperty; + + builder = __nccwpck_require__(52958); + + defaults = (__nccwpck_require__(8613).defaults); + + requiresCDATA = function(entry) { + return typeof entry === "string" && (entry.indexOf('&') >= 0 || entry.indexOf('>') >= 0 || entry.indexOf('<') >= 0); + }; + + wrapCDATA = function(entry) { + return ""; + }; + + escapeCDATA = function(entry) { + return entry.replace(']]>', ']]]]>'); + }; + + exports.Builder = (function() { + function Builder(opts) { + var key, ref, value; + this.options = {}; + ref = defaults["0.2"]; + for (key in ref) { + if (!hasProp.call(ref, key)) continue; + value = ref[key]; + this.options[key] = value; + } + for (key in opts) { + if (!hasProp.call(opts, key)) continue; + value = opts[key]; + this.options[key] = value; + } } - /** - * pollOnce does one polling, by calling to the update method of the underlying - * poll operation to make any relevant change effective. - * - * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike. - * - * @param options - Optional properties passed to the operation's update method. - */ - async pollOnce(options = {}) { - try { - if (!this.isDone()) { - this.operation = await this.operation.update({ - abortSignal: options.abortSignal, - fireProgress: this.fireProgress.bind(this), - }); - if (this.isDone() && this.resolve) { - // If the poller has finished polling, this means we now have a result. - // However, it can be the case that TResult is instantiated to void, so - // we are not expecting a result anyway. To assert that we might not - // have a result eventually after finishing polling, we cast the result - // to TResult. - this.resolve(this.operation.state.result); - } + + Builder.prototype.buildObject = function(rootObj) { + var attrkey, charkey, render, rootElement, rootName; + attrkey = this.options.attrkey; + charkey = this.options.charkey; + if ((Object.keys(rootObj).length === 1) && (this.options.rootName === defaults['0.2'].rootName)) { + rootName = Object.keys(rootObj)[0]; + rootObj = rootObj[rootName]; + } else { + rootName = this.options.rootName; + } + render = (function(_this) { + return function(element, obj) { + var attr, child, entry, index, key, value; + if (typeof obj !== 'object') { + if (_this.options.cdata && requiresCDATA(obj)) { + element.raw(wrapCDATA(obj)); + } else { + element.txt(obj); } - } - catch (e) { - this.operation.state.error = e; - if (this.reject) { - this.reject(e); + } else if (Array.isArray(obj)) { + for (index in obj) { + if (!hasProp.call(obj, index)) continue; + child = obj[index]; + for (key in child) { + entry = child[key]; + element = render(element.ele(key), entry).up(); + } } - throw e; - } - } - /** - * fireProgress calls the functions passed in via onProgress the method of the poller. - * - * It loops over all of the callbacks received from onProgress, and executes them, sending them - * the current operation state. - * - * @param state - The current operation state. - */ - fireProgress(state) { - for (const callback of this.pollProgressCallbacks) { - callback(state); - } - } - /** - * Invokes the underlying operation's cancel method, and rejects the - * pollUntilDone promise. - */ - async cancelOnce(options = {}) { - this.operation = await this.operation.cancel(options); - if (this.reject) { - this.reject(new PollerCancelledError("Poller cancelled")); - } - } - /** - * Returns a promise that will resolve once a single polling request finishes. - * It does this by calling the update method of the Poller's operation. - * - * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike. - * - * @param options - Optional properties passed to the operation's update method. - */ - poll(options = {}) { - if (!this.pollOncePromise) { - this.pollOncePromise = this.pollOnce(options); - const clearPollOncePromise = () => { - this.pollOncePromise = undefined; - }; - this.pollOncePromise.then(clearPollOncePromise, clearPollOncePromise).catch(this.reject); - } - return this.pollOncePromise; - } - /** - * Returns a promise that will resolve once the underlying operation is completed. - */ - async pollUntilDone() { - if (this.stopped) { - this.startPolling().catch(this.reject); - } - return this.promise; - } - /** - * Invokes the provided callback after each polling is completed, - * sending the current state of the poller's operation. - * - * It returns a method that can be used to stop receiving updates on the given callback function. - */ - onProgress(callback) { - this.pollProgressCallbacks.push(callback); - return () => { - this.pollProgressCallbacks = this.pollProgressCallbacks.filter((c) => c !== callback); + } else { + for (key in obj) { + if (!hasProp.call(obj, key)) continue; + child = obj[key]; + if (key === attrkey) { + if (typeof child === "object") { + for (attr in child) { + value = child[attr]; + element = element.att(attr, value); + } + } + } else if (key === charkey) { + if (_this.options.cdata && requiresCDATA(child)) { + element = element.raw(wrapCDATA(child)); + } else { + element = element.txt(child); + } + } else if (Array.isArray(child)) { + for (index in child) { + if (!hasProp.call(child, index)) continue; + entry = child[index]; + if (typeof entry === 'string') { + if (_this.options.cdata && requiresCDATA(entry)) { + element = element.ele(key).raw(wrapCDATA(entry)).up(); + } else { + element = element.ele(key, entry).up(); + } + } else { + element = render(element.ele(key), entry).up(); + } + } + } else if (typeof child === "object") { + element = render(element.ele(key), child).up(); + } else { + if (typeof child === 'string' && _this.options.cdata && requiresCDATA(child)) { + element = element.ele(key).raw(wrapCDATA(child)).up(); + } else { + if (child == null) { + child = ''; + } + element = element.ele(key, child.toString()).up(); + } + } + } + } + return element; }; + })(this); + rootElement = builder.create(rootName, this.options.xmldec, this.options.doctype, { + headless: this.options.headless, + allowSurrogateChars: this.options.allowSurrogateChars + }); + return render(rootElement, rootObj).end(this.options.renderOpts); + }; + + return Builder; + + })(); + +}).call(this); + + +/***/ }), + +/***/ 8613: +/***/ (function(__unused_webpack_module, exports) { + +// Generated by CoffeeScript 1.12.7 +(function() { + exports.defaults = { + "0.1": { + explicitCharkey: false, + trim: true, + normalize: true, + normalizeTags: false, + attrkey: "@", + charkey: "#", + explicitArray: false, + ignoreAttrs: false, + mergeAttrs: false, + explicitRoot: false, + validator: null, + xmlns: false, + explicitChildren: false, + childkey: '@@', + charsAsChildren: false, + includeWhiteChars: false, + async: false, + strict: true, + attrNameProcessors: null, + attrValueProcessors: null, + tagNameProcessors: null, + valueProcessors: null, + emptyTag: '' + }, + "0.2": { + explicitCharkey: false, + trim: false, + normalize: false, + normalizeTags: false, + attrkey: "$", + charkey: "_", + explicitArray: true, + ignoreAttrs: false, + mergeAttrs: false, + explicitRoot: true, + validator: null, + xmlns: false, + explicitChildren: false, + preserveChildrenOrder: false, + childkey: '$$', + charsAsChildren: false, + includeWhiteChars: false, + async: false, + strict: true, + attrNameProcessors: null, + attrValueProcessors: null, + tagNameProcessors: null, + valueProcessors: null, + rootName: 'root', + xmldec: { + 'version': '1.0', + 'encoding': 'UTF-8', + 'standalone': true + }, + doctype: null, + renderOpts: { + 'pretty': true, + 'indent': ' ', + 'newline': '\n' + }, + headless: false, + chunkSize: 10000, + emptyTag: '', + cdata: false } - /** - * Returns true if the poller has finished polling. - */ - isDone() { - const state = this.operation.state; - return Boolean(state.isCompleted || state.isCancelled || state.error); - } - /** - * Stops the poller from continuing to poll. - */ - stopPolling() { - if (!this.stopped) { - this.stopped = true; - if (this.reject) { - this.reject(new PollerStoppedError("This poller is already stopped")); - } - } - } - /** - * Returns true if the poller is stopped. - */ - isStopped() { - return this.stopped; - } - /** - * Attempts to cancel the underlying operation. - * - * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike. - * - * If it's called again before it finishes, it will throw an error. - * - * @param options - Optional properties passed to the operation's update method. - */ - cancelOperation(options = {}) { - if (!this.stopped) { - this.stopped = true; - } - if (!this.cancelPromise) { - this.cancelPromise = this.cancelOnce(options); - } - else if (options.abortSignal) { - throw new Error("A cancel request is currently pending"); - } - return this.cancelPromise; - } - /** - * Returns the state of the operation. - * - * Even though TState will be the same type inside any of the methods of any extension of the Poller class, - * implementations of the pollers can customize what's shared with the public by writing their own - * version of the `getOperationState` method, and by defining two types, one representing the internal state of the poller - * and a public type representing a safe to share subset of the properties of the internal state. - * Their definition of getOperationState can then return their public type. - * - * Example: - * - * ```ts - * // Let's say we have our poller's operation state defined as: - * interface MyOperationState extends PollOperationState { - * privateProperty?: string; - * publicProperty?: string; - * } - * - * // To allow us to have a true separation of public and private state, we have to define another interface: - * interface PublicState extends PollOperationState { - * publicProperty?: string; - * } - * - * // Then, we define our Poller as follows: - * export class MyPoller extends Poller { - * // ... More content is needed here ... - * - * public getOperationState(): PublicState { - * const state: PublicState = this.operation.state; - * return { - * // Properties from PollOperationState - * isStarted: state.isStarted, - * isCompleted: state.isCompleted, - * isCancelled: state.isCancelled, - * error: state.error, - * result: state.result, - * - * // The only other property needed by PublicState. - * publicProperty: state.publicProperty - * } - * } - * } - * ``` - * - * You can see this in the tests of this repository, go to the file: - * `../test/utils/testPoller.ts` - * and look for the getOperationState implementation. - */ - getOperationState() { - return this.operation.state; - } - /** - * Returns the result value of the operation, - * regardless of the state of the poller. - * It can return undefined or an incomplete form of the final TResult value - * depending on the implementation. - */ - getResult() { - const state = this.operation.state; - return state.result; - } - /** - * Returns a serialized version of the poller's operation - * by invoking the operation's toString method. - */ - toString() { - return this.operation.toString(); - } -} + }; -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * Detects where the continuation token is and returns it. Notice that azure-asyncoperation - * must be checked first before the other location headers because there are scenarios - * where both azure-asyncoperation and location could be present in the same response but - * azure-asyncoperation should be the one to use for polling. - */ -function getPollingUrl(rawResponse, defaultPath) { - var _a, _b, _c; - return ((_c = (_b = (_a = getAzureAsyncOperation(rawResponse)) !== null && _a !== void 0 ? _a : getOperationLocation(rawResponse)) !== null && _b !== void 0 ? _b : getLocation(rawResponse)) !== null && _c !== void 0 ? _c : defaultPath); -} -function getLocation(rawResponse) { - return rawResponse.headers["location"]; -} -function getOperationLocation(rawResponse) { - return rawResponse.headers["operation-location"]; -} -function getAzureAsyncOperation(rawResponse) { - return rawResponse.headers["azure-asyncoperation"]; -} -function findResourceLocation(requestMethod, rawResponse, requestPath) { - switch (requestMethod) { - case "PUT": { - return requestPath; - } - case "POST": - case "PATCH": { - return getLocation(rawResponse); - } - default: { - return undefined; - } - } -} -function inferLroMode(requestPath, requestMethod, rawResponse) { - if (getAzureAsyncOperation(rawResponse) !== undefined || - getOperationLocation(rawResponse) !== undefined) { - return { - mode: "Location", - resourceLocation: findResourceLocation(requestMethod, rawResponse, requestPath), - }; - } - else if (getLocation(rawResponse) !== undefined) { - return { - mode: "Location", - }; - } - else if (["PUT", "PATCH"].includes(requestMethod)) { - return { - mode: "Body", - }; - } - return {}; -} -class SimpleRestError extends Error { - constructor(message, statusCode) { - super(message); - this.name = "RestError"; - this.statusCode = statusCode; - Object.setPrototypeOf(this, SimpleRestError.prototype); - } -} -function isUnexpectedInitialResponse(rawResponse) { - const code = rawResponse.statusCode; - if (![203, 204, 202, 201, 200, 500].includes(code)) { - throw new SimpleRestError(`Received unexpected HTTP status code ${code} in the initial response. This may indicate a server issue.`, code); - } - return false; -} -function isUnexpectedPollingResponse(rawResponse) { - const code = rawResponse.statusCode; - if (![202, 201, 200, 500].includes(code)) { - throw new SimpleRestError(`Received unexpected HTTP status code ${code} while polling. This may indicate a server issue.`, code); - } - return false; -} +}).call(this); -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -const successStates = ["succeeded"]; -const failureStates = ["failed", "canceled", "cancelled"]; -// Copyright (c) Microsoft Corporation. -function getProvisioningState(rawResponse) { - var _a, _b; - const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; - const state = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState; - return typeof state === "string" ? state.toLowerCase() : "succeeded"; -} -function isBodyPollingDone(rawResponse) { - const state = getProvisioningState(rawResponse); - if (isUnexpectedPollingResponse(rawResponse) || failureStates.includes(state)) { - throw new Error(`The long running operation has failed. The provisioning state: ${state}.`); - } - return successStates.includes(state); -} -/** - * Creates a polling strategy based on BodyPolling which uses the provisioning state - * from the result to determine the current operation state - */ -function processBodyPollingOperationResult(response) { - return Object.assign(Object.assign({}, response), { done: isBodyPollingDone(response.rawResponse) }); -} +/***/ }), -// Copyright (c) Microsoft Corporation. -/** - * The `@azure/logger` configuration for this package. - * @internal - */ -const logger = logger$1.createClientLogger("core-lro"); +/***/ 43063: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -// Copyright (c) Microsoft Corporation. -function isPollingDone(rawResponse) { - var _a; - if (isUnexpectedPollingResponse(rawResponse) || rawResponse.statusCode === 202) { - return false; - } - const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; - const state = typeof status === "string" ? status.toLowerCase() : "succeeded"; - if (isUnexpectedPollingResponse(rawResponse) || failureStates.includes(state)) { - throw new Error(`The long running operation has failed. The provisioning state: ${state}.`); - } - return successStates.includes(state); -} -/** - * Sends a request to the URI of the provisioned resource if needed. - */ -async function sendFinalRequest(lro, resourceLocation, lroResourceLocationConfig) { - switch (lroResourceLocationConfig) { - case "original-uri": - return lro.sendPollRequest(lro.requestPath); - case "azure-async-operation": - return undefined; - case "location": - default: - return lro.sendPollRequest(resourceLocation !== null && resourceLocation !== void 0 ? resourceLocation : lro.requestPath); +// Generated by CoffeeScript 1.12.7 +(function() { + "use strict"; + var bom, defaults, events, isEmpty, processItem, processors, sax, setImmediate, + bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + sax = __nccwpck_require__(72043); + + events = __nccwpck_require__(82361); + + bom = __nccwpck_require__(21002); + + processors = __nccwpck_require__(99634); + + setImmediate = (__nccwpck_require__(39512).setImmediate); + + defaults = (__nccwpck_require__(8613).defaults); + + isEmpty = function(thing) { + return typeof thing === "object" && (thing != null) && Object.keys(thing).length === 0; + }; + + processItem = function(processors, item, key) { + var i, len, process; + for (i = 0, len = processors.length; i < len; i++) { + process = processors[i]; + item = process(item, key); } -} -function processLocationPollingOperationResult(lro, resourceLocation, lroResourceLocationConfig) { - return (response) => { - if (isPollingDone(response.rawResponse)) { - if (resourceLocation === undefined) { - return Object.assign(Object.assign({}, response), { done: true }); - } - else { - return Object.assign(Object.assign({}, response), { done: false, next: async () => { - const finalResponse = await sendFinalRequest(lro, resourceLocation, lroResourceLocationConfig); - return Object.assign(Object.assign({}, (finalResponse !== null && finalResponse !== void 0 ? finalResponse : response)), { done: true }); - } }); - } - } - return Object.assign(Object.assign({}, response), { done: false }); - }; -} + return item; + }; -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -function processPassthroughOperationResult(response) { - return Object.assign(Object.assign({}, response), { done: true }); -} + exports.Parser = (function(superClass) { + extend(Parser, superClass); -// Copyright (c) Microsoft Corporation. -/** - * creates a stepping function that maps an LRO state to another. - */ -function createGetLroStatusFromResponse(lroPrimitives, config, lroResourceLocationConfig) { - switch (config.mode) { - case "Location": { - return processLocationPollingOperationResult(lroPrimitives, config.resourceLocation, lroResourceLocationConfig); - } - case "Body": { - return processBodyPollingOperationResult; - } - default: { - return processPassthroughOperationResult; + function Parser(opts) { + this.parseStringPromise = bind(this.parseStringPromise, this); + this.parseString = bind(this.parseString, this); + this.reset = bind(this.reset, this); + this.assignOrPush = bind(this.assignOrPush, this); + this.processAsync = bind(this.processAsync, this); + var key, ref, value; + if (!(this instanceof exports.Parser)) { + return new exports.Parser(opts); + } + this.options = {}; + ref = defaults["0.2"]; + for (key in ref) { + if (!hasProp.call(ref, key)) continue; + value = ref[key]; + this.options[key] = value; + } + for (key in opts) { + if (!hasProp.call(opts, key)) continue; + value = opts[key]; + this.options[key] = value; + } + if (this.options.xmlns) { + this.options.xmlnskey = this.options.attrkey + "ns"; + } + if (this.options.normalizeTags) { + if (!this.options.tagNameProcessors) { + this.options.tagNameProcessors = []; } + this.options.tagNameProcessors.unshift(processors.normalize); + } + this.reset(); } -} -/** - * Creates a polling operation. - */ -function createPoll(lroPrimitives) { - return async (path, pollerConfig, getLroStatusFromResponse) => { - const response = await lroPrimitives.sendPollRequest(path); - const retryAfter = response.rawResponse.headers["retry-after"]; - if (retryAfter !== undefined) { - // Retry-After header value is either in HTTP date format, or in seconds - const retryAfterInSeconds = parseInt(retryAfter); - pollerConfig.intervalInMs = isNaN(retryAfterInSeconds) - ? calculatePollingIntervalFromDate(new Date(retryAfter), pollerConfig.intervalInMs) - : retryAfterInSeconds * 1000; + + Parser.prototype.processAsync = function() { + var chunk, err; + try { + if (this.remaining.length <= this.options.chunkSize) { + chunk = this.remaining; + this.remaining = ''; + this.saxParser = this.saxParser.write(chunk); + return this.saxParser.close(); + } else { + chunk = this.remaining.substr(0, this.options.chunkSize); + this.remaining = this.remaining.substr(this.options.chunkSize, this.remaining.length); + this.saxParser = this.saxParser.write(chunk); + return setImmediate(this.processAsync); } - return getLroStatusFromResponse(response); - }; -} -function calculatePollingIntervalFromDate(retryAfterDate, defaultIntervalInMs) { - const timeNow = Math.floor(new Date().getTime()); - const retryAfterTime = retryAfterDate.getTime(); - if (timeNow < retryAfterTime) { - return retryAfterTime - timeNow; - } - return defaultIntervalInMs; -} -/** - * Creates a callback to be used to initialize the polling operation state. - * @param state - of the polling operation - * @param operationSpec - of the LRO - * @param callback - callback to be called when the operation is done - * @returns callback that initializes the state of the polling operation - */ -function createInitializeState(state, requestPath, requestMethod) { - return (response) => { - if (isUnexpectedInitialResponse(response.rawResponse)) - ; - state.initialRawResponse = response.rawResponse; - state.isStarted = true; - state.pollingURL = getPollingUrl(state.initialRawResponse, requestPath); - state.config = inferLroMode(requestPath, requestMethod, state.initialRawResponse); - /** short circuit polling if body polling is done in the initial request */ - if (state.config.mode === undefined || - (state.config.mode === "Body" && isBodyPollingDone(state.initialRawResponse))) { - state.result = response.flatResponse; - state.isCompleted = true; + } catch (error1) { + err = error1; + if (!this.saxParser.errThrown) { + this.saxParser.errThrown = true; + return this.emit(err); } - logger.verbose(`LRO: initial state: ${JSON.stringify(state)}`); - return Boolean(state.isCompleted); + } }; -} -// Copyright (c) Microsoft Corporation. -class GenericPollOperation { - constructor(state, lro, lroResourceLocationConfig, processResult, updateState, isDone) { - this.state = state; - this.lro = lro; - this.lroResourceLocationConfig = lroResourceLocationConfig; - this.processResult = processResult; - this.updateState = updateState; - this.isDone = isDone; - } - setPollerConfig(pollerConfig) { - this.pollerConfig = pollerConfig; - } - /** - * General update function for LROPoller, the general process is as follows - * 1. Check initial operation result to determine the strategy to use - * - Strategies: Location, Azure-AsyncOperation, Original Uri - * 2. Check if the operation result has a terminal state - * - Terminal state will be determined by each strategy - * 2.1 If it is terminal state Check if a final GET request is required, if so - * send final GET request and return result from operation. If no final GET - * is required, just return the result from operation. - * - Determining what to call for final request is responsibility of each strategy - * 2.2 If it is not terminal state, call the polling operation and go to step 1 - * - Determining what to call for polling is responsibility of each strategy - * - Strategies will always use the latest URI for polling if provided otherwise - * the last known one - */ - async update(options) { - var _a, _b, _c; - const state = this.state; - let lastResponse = undefined; - if (!state.isStarted) { - const initializeState = createInitializeState(state, this.lro.requestPath, this.lro.requestMethod); - lastResponse = await this.lro.sendInitialRequest(); - initializeState(lastResponse); - } - if (!state.isCompleted) { - if (!this.poll || !this.getLroStatusFromResponse) { - if (!state.config) { - throw new Error("Bad state: LRO mode is undefined. Please check if the serialized state is well-formed."); - } - const isDone = this.isDone; - this.getLroStatusFromResponse = isDone - ? (response) => (Object.assign(Object.assign({}, response), { done: isDone(response.flatResponse, this.state) })) - : createGetLroStatusFromResponse(this.lro, state.config, this.lroResourceLocationConfig); - this.poll = createPoll(this.lro); - } - if (!state.pollingURL) { - throw new Error("Bad state: polling URL is undefined. Please check if the serialized state is well-formed."); - } - const currentState = await this.poll(state.pollingURL, this.pollerConfig, this.getLroStatusFromResponse); - logger.verbose(`LRO: polling response: ${JSON.stringify(currentState.rawResponse)}`); - if (currentState.done) { - state.result = this.processResult - ? this.processResult(currentState.flatResponse, state) - : currentState.flatResponse; - state.isCompleted = true; - } - else { - this.poll = (_a = currentState.next) !== null && _a !== void 0 ? _a : this.poll; - state.pollingURL = getPollingUrl(currentState.rawResponse, state.pollingURL); - } - lastResponse = currentState; - } - logger.verbose(`LRO: current state: ${JSON.stringify(state)}`); - if (lastResponse) { - (_b = this.updateState) === null || _b === void 0 ? void 0 : _b.call(this, state, lastResponse === null || lastResponse === void 0 ? void 0 : lastResponse.rawResponse); + Parser.prototype.assignOrPush = function(obj, key, newValue) { + if (!(key in obj)) { + if (!this.options.explicitArray) { + return obj[key] = newValue; + } else { + return obj[key] = [newValue]; } - else { - logger.error(`LRO: no response was received`); + } else { + if (!(obj[key] instanceof Array)) { + obj[key] = [obj[key]]; } - (_c = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _c === void 0 ? void 0 : _c.call(options, state); - return this; - } - async cancel() { - this.state.isCancelled = true; - return this; - } - /** - * Serializes the Poller operation. - */ - toString() { - return JSON.stringify({ - state: this.state, - }); - } -} + return obj[key].push(newValue); + } + }; -// Copyright (c) Microsoft Corporation. -function deserializeState(serializedState) { - try { - return JSON.parse(serializedState).state; + Parser.prototype.reset = function() { + var attrkey, charkey, ontext, stack; + this.removeAllListeners(); + this.saxParser = sax.parser(this.options.strict, { + trim: false, + normalize: false, + xmlns: this.options.xmlns + }); + this.saxParser.errThrown = false; + this.saxParser.onerror = (function(_this) { + return function(error) { + _this.saxParser.resume(); + if (!_this.saxParser.errThrown) { + _this.saxParser.errThrown = true; + return _this.emit("error", error); + } + }; + })(this); + this.saxParser.onend = (function(_this) { + return function() { + if (!_this.saxParser.ended) { + _this.saxParser.ended = true; + return _this.emit("end", _this.resultObject); + } + }; + })(this); + this.saxParser.ended = false; + this.EXPLICIT_CHARKEY = this.options.explicitCharkey; + this.resultObject = null; + stack = []; + attrkey = this.options.attrkey; + charkey = this.options.charkey; + this.saxParser.onopentag = (function(_this) { + return function(node) { + var key, newValue, obj, processedKey, ref; + obj = Object.create(null); + obj[charkey] = ""; + if (!_this.options.ignoreAttrs) { + ref = node.attributes; + for (key in ref) { + if (!hasProp.call(ref, key)) continue; + if (!(attrkey in obj) && !_this.options.mergeAttrs) { + obj[attrkey] = Object.create(null); + } + newValue = _this.options.attrValueProcessors ? processItem(_this.options.attrValueProcessors, node.attributes[key], key) : node.attributes[key]; + processedKey = _this.options.attrNameProcessors ? processItem(_this.options.attrNameProcessors, key) : key; + if (_this.options.mergeAttrs) { + _this.assignOrPush(obj, processedKey, newValue); + } else { + obj[attrkey][processedKey] = newValue; + } + } + } + obj["#name"] = _this.options.tagNameProcessors ? processItem(_this.options.tagNameProcessors, node.name) : node.name; + if (_this.options.xmlns) { + obj[_this.options.xmlnskey] = { + uri: node.uri, + local: node.local + }; + } + return stack.push(obj); + }; + })(this); + this.saxParser.onclosetag = (function(_this) { + return function() { + var cdata, emptyStr, key, node, nodeName, obj, objClone, old, s, xpath; + obj = stack.pop(); + nodeName = obj["#name"]; + if (!_this.options.explicitChildren || !_this.options.preserveChildrenOrder) { + delete obj["#name"]; + } + if (obj.cdata === true) { + cdata = obj.cdata; + delete obj.cdata; + } + s = stack[stack.length - 1]; + if (obj[charkey].match(/^\s*$/) && !cdata) { + emptyStr = obj[charkey]; + delete obj[charkey]; + } else { + if (_this.options.trim) { + obj[charkey] = obj[charkey].trim(); + } + if (_this.options.normalize) { + obj[charkey] = obj[charkey].replace(/\s{2,}/g, " ").trim(); + } + obj[charkey] = _this.options.valueProcessors ? processItem(_this.options.valueProcessors, obj[charkey], nodeName) : obj[charkey]; + if (Object.keys(obj).length === 1 && charkey in obj && !_this.EXPLICIT_CHARKEY) { + obj = obj[charkey]; + } + } + if (isEmpty(obj)) { + if (typeof _this.options.emptyTag === 'function') { + obj = _this.options.emptyTag(); + } else { + obj = _this.options.emptyTag !== '' ? _this.options.emptyTag : emptyStr; + } + } + if (_this.options.validator != null) { + xpath = "/" + ((function() { + var i, len, results; + results = []; + for (i = 0, len = stack.length; i < len; i++) { + node = stack[i]; + results.push(node["#name"]); + } + return results; + })()).concat(nodeName).join("/"); + (function() { + var err; + try { + return obj = _this.options.validator(xpath, s && s[nodeName], obj); + } catch (error1) { + err = error1; + return _this.emit("error", err); + } + })(); + } + if (_this.options.explicitChildren && !_this.options.mergeAttrs && typeof obj === 'object') { + if (!_this.options.preserveChildrenOrder) { + node = Object.create(null); + if (_this.options.attrkey in obj) { + node[_this.options.attrkey] = obj[_this.options.attrkey]; + delete obj[_this.options.attrkey]; + } + if (!_this.options.charsAsChildren && _this.options.charkey in obj) { + node[_this.options.charkey] = obj[_this.options.charkey]; + delete obj[_this.options.charkey]; + } + if (Object.getOwnPropertyNames(obj).length > 0) { + node[_this.options.childkey] = obj; + } + obj = node; + } else if (s) { + s[_this.options.childkey] = s[_this.options.childkey] || []; + objClone = Object.create(null); + for (key in obj) { + if (!hasProp.call(obj, key)) continue; + objClone[key] = obj[key]; + } + s[_this.options.childkey].push(objClone); + delete obj["#name"]; + if (Object.keys(obj).length === 1 && charkey in obj && !_this.EXPLICIT_CHARKEY) { + obj = obj[charkey]; + } + } + } + if (stack.length > 0) { + return _this.assignOrPush(s, nodeName, obj); + } else { + if (_this.options.explicitRoot) { + old = obj; + obj = Object.create(null); + obj[nodeName] = old; + } + _this.resultObject = obj; + _this.saxParser.ended = true; + return _this.emit("end", _this.resultObject); + } + }; + })(this); + ontext = (function(_this) { + return function(text) { + var charChild, s; + s = stack[stack.length - 1]; + if (s) { + s[charkey] += text; + if (_this.options.explicitChildren && _this.options.preserveChildrenOrder && _this.options.charsAsChildren && (_this.options.includeWhiteChars || text.replace(/\\n/g, '').trim() !== '')) { + s[_this.options.childkey] = s[_this.options.childkey] || []; + charChild = { + '#name': '__text__' + }; + charChild[charkey] = text; + if (_this.options.normalize) { + charChild[charkey] = charChild[charkey].replace(/\s{2,}/g, " ").trim(); + } + s[_this.options.childkey].push(charChild); + } + return s; + } + }; + })(this); + this.saxParser.ontext = ontext; + return this.saxParser.oncdata = (function(_this) { + return function(text) { + var s; + s = ontext(text); + if (s) { + return s.cdata = true; + } + }; + })(this); + }; + + Parser.prototype.parseString = function(str, cb) { + var err; + if ((cb != null) && typeof cb === "function") { + this.on("end", function(result) { + this.reset(); + return cb(null, result); + }); + this.on("error", function(err) { + this.reset(); + return cb(err); + }); + } + try { + str = str.toString(); + if (str.trim() === '') { + this.emit("end", null); + return true; + } + str = bom.stripBOM(str); + if (this.options.async) { + this.remaining = str; + setImmediate(this.processAsync); + return this.saxParser; + } + return this.saxParser.write(str).close(); + } catch (error1) { + err = error1; + if (!(this.saxParser.errThrown || this.saxParser.ended)) { + this.emit('error', err); + return this.saxParser.errThrown = true; + } else if (this.saxParser.ended) { + throw err; + } + } + }; + + Parser.prototype.parseStringPromise = function(str) { + return new Promise((function(_this) { + return function(resolve, reject) { + return _this.parseString(str, function(err, value) { + if (err) { + return reject(err); + } else { + return resolve(value); + } + }); + }; + })(this)); + }; + + return Parser; + + })(events); + + exports.parseString = function(str, a, b) { + var cb, options, parser; + if (b != null) { + if (typeof b === 'function') { + cb = b; + } + if (typeof a === 'object') { + options = a; + } + } else { + if (typeof a === 'function') { + cb = a; + } + options = {}; } - catch (e) { - throw new Error(`LroEngine: Unable to deserialize state: ${serializedState}`); + parser = new exports.Parser(options); + return parser.parseString(str, cb); + }; + + exports.parseStringPromise = function(str, a) { + var options, parser; + if (typeof a === 'object') { + options = a; } -} -/** - * The LRO Engine, a class that performs polling. - */ -class LroEngine extends Poller { - constructor(lro, options) { - const { intervalInMs = 2000, resumeFrom } = options || {}; - const state = resumeFrom - ? deserializeState(resumeFrom) - : {}; - const operation = new GenericPollOperation(state, lro, options === null || options === void 0 ? void 0 : options.lroResourceLocationConfig, options === null || options === void 0 ? void 0 : options.processResult, options === null || options === void 0 ? void 0 : options.updateState, options === null || options === void 0 ? void 0 : options.isDone); - super(operation); - this.config = { intervalInMs: intervalInMs }; - operation.setPollerConfig(this.config); + parser = new exports.Parser(options); + return parser.parseStringPromise(str); + }; + +}).call(this); + + +/***/ }), + +/***/ 99634: +/***/ (function(__unused_webpack_module, exports) { + +// Generated by CoffeeScript 1.12.7 +(function() { + "use strict"; + var prefixMatch; + + prefixMatch = new RegExp(/(?!xmlns)^.*:/); + + exports.normalize = function(str) { + return str.toLowerCase(); + }; + + exports.firstCharLowerCase = function(str) { + return str.charAt(0).toLowerCase() + str.slice(1); + }; + + exports.stripPrefix = function(str) { + return str.replace(prefixMatch, ''); + }; + + exports.parseNumbers = function(str) { + if (!isNaN(str)) { + str = str % 1 === 0 ? parseInt(str, 10) : parseFloat(str); } - /** - * The method used by the poller to wait before attempting to update its operation. - */ - delay() { - return new Promise((resolve) => setTimeout(() => resolve(), this.config.intervalInMs)); + return str; + }; + + exports.parseBooleans = function(str) { + if (/^(?:true|false)$/i.test(str)) { + str = str.toLowerCase() === 'true'; } -} + return str; + }; -exports.LroEngine = LroEngine; -exports.Poller = Poller; -exports.PollerCancelledError = PollerCancelledError; -exports.PollerStoppedError = PollerStoppedError; -//# sourceMappingURL=index.js.map +}).call(this); + + +/***/ }), + +/***/ 10488: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +// Generated by CoffeeScript 1.12.7 +(function() { + "use strict"; + var builder, defaults, parser, processors, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + defaults = __nccwpck_require__(8613); + + builder = __nccwpck_require__(9737); + + parser = __nccwpck_require__(43063); + + processors = __nccwpck_require__(99634); + + exports.defaults = defaults.defaults; + + exports.processors = processors; + + exports.ValidationError = (function(superClass) { + extend(ValidationError, superClass); + + function ValidationError(message) { + this.message = message; + } + + return ValidationError; + + })(Error); + + exports.Builder = builder.Builder; + + exports.Parser = parser.Parser; + + exports.parseString = parser.parseString; + + exports.parseStringPromise = parser.parseStringPromise; + +}).call(this); /***/ }), -/***/ 7162: +/***/ 27094: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -20084,854 +19875,758 @@ exports.PollerStoppedError = PollerStoppedError; Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib = __nccwpck_require__(5781); +var logger$1 = __nccwpck_require__(3233); // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. /** - * returns an async iterator that iterates over results. It also has a `byPage` - * method that returns pages of items at once. - * - * @param pagedResult - an object that specifies how to get pages. - * @returns a paged async iterator that iterates over results. + * When a poller is manually stopped through the `stopPolling` method, + * the poller will be rejected with an instance of the PollerStoppedError. */ -function getPagedAsyncIterator(pagedResult) { - var _a; - const iter = getItemAsyncIterator(pagedResult); - return { - next() { - return iter.next(); - }, - [Symbol.asyncIterator]() { - return this; - }, - byPage: (_a = pagedResult === null || pagedResult === void 0 ? void 0 : pagedResult.byPage) !== null && _a !== void 0 ? _a : ((settings) => { - const { continuationToken, maxPageSize } = settings !== null && settings !== void 0 ? settings : {}; - return getPageAsyncIterator(pagedResult, { - pageLink: continuationToken, - maxPageSize, - }); - }), - }; -} -function getItemAsyncIterator(pagedResult) { - return tslib.__asyncGenerator(this, arguments, function* getItemAsyncIterator_1() { - var e_1, _a; - const pages = getPageAsyncIterator(pagedResult); - const firstVal = yield tslib.__await(pages.next()); - // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is - if (!Array.isArray(firstVal.value)) { - yield yield tslib.__await(firstVal.value); - // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case - yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(pages))); - } - else { - yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(firstVal.value))); - try { - for (var pages_1 = tslib.__asyncValues(pages), pages_1_1; pages_1_1 = yield tslib.__await(pages_1.next()), !pages_1_1.done;) { - const page = pages_1_1.value; - // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, - // it must be the case that `TPage = TElement[]` - yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(page))); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (pages_1_1 && !pages_1_1.done && (_a = pages_1.return)) yield tslib.__await(_a.call(pages_1)); - } - finally { if (e_1) throw e_1.error; } - } - } - }); +class PollerStoppedError extends Error { + constructor(message) { + super(message); + this.name = "PollerStoppedError"; + Object.setPrototypeOf(this, PollerStoppedError.prototype); + } } -function getPageAsyncIterator(pagedResult, options = {}) { - return tslib.__asyncGenerator(this, arguments, function* getPageAsyncIterator_1() { - const { pageLink, maxPageSize } = options; - let response = yield tslib.__await(pagedResult.getPage(pageLink !== null && pageLink !== void 0 ? pageLink : pagedResult.firstPageLink, maxPageSize)); - yield yield tslib.__await(response.page); - while (response.nextPageLink) { - response = yield tslib.__await(pagedResult.getPage(response.nextPageLink, maxPageSize)); - yield yield tslib.__await(response.page); - } - }); +/** + * When a poller is cancelled through the `cancelOperation` method, + * the poller will be rejected with an instance of the PollerCancelledError. + */ +class PollerCancelledError extends Error { + constructor(message) { + super(message); + this.name = "PollerCancelledError"; + Object.setPrototypeOf(this, PollerCancelledError.prototype); + } } - -exports.getPagedAsyncIterator = getPagedAsyncIterator; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 5781: -/***/ ((module) => { - -/****************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global global, define, System, Reflect, Promise */ -var __extends; -var __assign; -var __rest; -var __decorate; -var __param; -var __metadata; -var __awaiter; -var __generator; -var __exportStar; -var __values; -var __read; -var __spread; -var __spreadArrays; -var __spreadArray; -var __await; -var __asyncGenerator; -var __asyncDelegator; -var __asyncValues; -var __makeTemplateObject; -var __importStar; -var __importDefault; -var __classPrivateFieldGet; -var __classPrivateFieldSet; -var __classPrivateFieldIn; -var __createBinding; -(function (factory) { - var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; - if (typeof define === "function" && define.amd) { - define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); - } - else if ( true && typeof module.exports === "object") { - factory(createExporter(root, createExporter(module.exports))); - } - else { - factory(createExporter(root)); - } - function createExporter(exports, previous) { - if (exports !== root) { - if (typeof Object.create === "function") { - Object.defineProperty(exports, "__esModule", { value: true }); - } - else { - exports.__esModule = true; - } - } - return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; - } -}) -(function (exporter) { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - - __extends = function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - - __assign = Object.assign || function (t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - - __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; - }; - - __decorate = function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - - __param = function (paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } - }; - - __metadata = function (metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); - }; - - __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()); - }); - }; - - __generator = function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - - __exportStar = function(m, o) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); - }; - - __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]; - }); - - __values = function (o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - - __read = function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - - /** @deprecated */ - __spread = function () { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; - }; - - /** @deprecated */ - __spreadArrays = function () { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; - }; - - __spreadArray = function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - - __await = function (v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); - }; - - __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]); } - }; - - __asyncDelegator = function (o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } - }; - - __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); } - }; - - __makeTemplateObject = function (cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; - }; - - var __setModuleDefault = Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }; - - __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; - }; - - __importDefault = function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - - __classPrivateFieldGet = function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); - }; - - __classPrivateFieldSet = function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; - }; - - __classPrivateFieldIn = function (state, receiver) { - if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); - return typeof state === "function" ? receiver === state : state.has(receiver); - }; - - exporter("__extends", __extends); - exporter("__assign", __assign); - exporter("__rest", __rest); - exporter("__decorate", __decorate); - exporter("__param", __param); - exporter("__metadata", __metadata); - exporter("__awaiter", __awaiter); - exporter("__generator", __generator); - exporter("__exportStar", __exportStar); - exporter("__createBinding", __createBinding); - exporter("__values", __values); - exporter("__read", __read); - exporter("__spread", __spread); - exporter("__spreadArrays", __spreadArrays); - exporter("__spreadArray", __spreadArray); - exporter("__await", __await); - exporter("__asyncGenerator", __asyncGenerator); - exporter("__asyncDelegator", __asyncDelegator); - exporter("__asyncValues", __asyncValues); - exporter("__makeTemplateObject", __makeTemplateObject); - exporter("__importStar", __importStar); - exporter("__importDefault", __importDefault); - exporter("__classPrivateFieldGet", __classPrivateFieldGet); - exporter("__classPrivateFieldSet", __classPrivateFieldSet); - exporter("__classPrivateFieldIn", __classPrivateFieldIn); -}); - - -/***/ }), - -/***/ 2848: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var api = __nccwpck_require__(5653); - -// Copyright (c) Microsoft Corporation. -(function (SpanKind) { - /** Default value. Indicates that the span is used internally. */ - SpanKind[SpanKind["INTERNAL"] = 0] = "INTERNAL"; - /** - * Indicates that the span covers server-side handling of an RPC or other - * remote request. - */ - SpanKind[SpanKind["SERVER"] = 1] = "SERVER"; - /** - * Indicates that the span covers the client-side wrapper around an RPC or - * other remote request. - */ - SpanKind[SpanKind["CLIENT"] = 2] = "CLIENT"; - /** - * Indicates that the span describes producer sending a message to a - * broker. Unlike client and server, there is no direct critical path latency - * relationship between producer and consumer spans. - */ - SpanKind[SpanKind["PRODUCER"] = 3] = "PRODUCER"; - /** - * Indicates that the span describes consumer receiving a message from a - * broker. Unlike client and server, there is no direct critical path latency - * relationship between producer and consumer spans. - */ - SpanKind[SpanKind["CONSUMER"] = 4] = "CONSUMER"; -})(exports.SpanKind || (exports.SpanKind = {})); /** - * Return the span if one exists + * A class that represents the definition of a program that polls through consecutive requests + * until it reaches a state of completion. * - * @param context - context to get span from - */ -function getSpan(context) { - return api.trace.getSpan(context); -} -/** - * Set the span on a context + * A poller can be executed manually, by polling request by request by calling to the `poll()` method repeatedly, until its operation is completed. + * It also provides a way to wait until the operation completes, by calling `pollUntilDone()` and waiting until the operation finishes. + * Pollers can also request the cancellation of the ongoing process to whom is providing the underlying long running operation. * - * @param context - context to use as parent - * @param span - span to set active - */ -function setSpan(context, span) { - return api.trace.setSpan(context, span); -} -/** - * Wrap span context in a NoopSpan and set as span in a new - * context + * ```ts + * const poller = new MyPoller(); * - * @param context - context to set active span on - * @param spanContext - span context to be wrapped - */ -function setSpanContext(context, spanContext) { - return api.trace.setSpanContext(context, spanContext); -} -/** - * Get the span context of the span if it exists. + * // Polling just once: + * await poller.poll(); * - * @param context - context to get values from - */ -function getSpanContext(context) { - return api.trace.getSpanContext(context); -} -/** - * Returns true of the given {@link SpanContext} is valid. - * A valid {@link SpanContext} is one which has a valid trace ID and span ID as per the spec. + * // We can try to cancel the request here, by calling: + * // + * // await poller.cancelOperation(); + * // * - * @param context - the {@link SpanContext} to validate. + * // Getting the final result: + * const result = await poller.pollUntilDone(); + * ``` + * + * The Poller is defined by two types, a type representing the state of the poller, which + * must include a basic set of properties from `PollOperationState`, + * and a return type defined by `TResult`, which can be anything. + * + * The Poller class implements the `PollerLike` interface, which allows poller implementations to avoid having + * to export the Poller's class directly, and instead only export the already instantiated poller with the PollerLike type. + * + * ```ts + * class Client { + * public async makePoller: PollerLike { + * const poller = new MyPoller({}); + * // It might be preferred to return the poller after the first request is made, + * // so that some information can be obtained right away. + * await poller.poll(); + * return poller; + * } + * } + * + * const poller: PollerLike = myClient.makePoller(); + * ``` + * + * A poller can be created through its constructor, then it can be polled until it's completed. + * At any point in time, the state of the poller can be obtained without delay through the getOperationState method. + * At any point in time, the intermediate forms of the result type can be requested without delay. + * Once the underlying operation is marked as completed, the poller will stop and the final value will be returned. + * + * ```ts + * const poller = myClient.makePoller(); + * const state: MyOperationState = poller.getOperationState(); + * + * // The intermediate result can be obtained at any time. + * const result: MyResult | undefined = poller.getResult(); + * + * // The final result can only be obtained after the poller finishes. + * const result: MyResult = await poller.pollUntilDone(); + * ``` * - * @returns true if the {@link SpanContext} is valid, false otherwise. */ -function isSpanContextValid(context) { - return api.trace.isSpanContextValid(context); -} -function getTracer(name, version) { - return api.trace.getTracer(name || "azure/core-tracing", version); -} -/** Entrypoint for context API */ -const context = api.context; -(function (SpanStatusCode) { +// eslint-disable-next-line no-use-before-define +class Poller { /** - * The default status. + * A poller needs to be initialized by passing in at least the basic properties of the `PollOperation`. + * + * When writing an implementation of a Poller, this implementation needs to deal with the initialization + * of any custom state beyond the basic definition of the poller. The basic poller assumes that the poller's + * operation has already been defined, at least its basic properties. The code below shows how to approach + * the definition of the constructor of a new custom poller. + * + * ```ts + * export class MyPoller extends Poller { + * constructor({ + * // Anything you might need outside of the basics + * }) { + * let state: MyOperationState = { + * privateProperty: private, + * publicProperty: public, + * }; + * + * const operation = { + * state, + * update, + * cancel, + * toString + * } + * + * // Sending the operation to the parent's constructor. + * super(operation); + * + * // You can assign more local properties here. + * } + * } + * ``` + * + * Inside of this constructor, a new promise is created. This will be used to + * tell the user when the poller finishes (see `pollUntilDone()`). The promise's + * resolve and reject methods are also used internally to control when to resolve + * or reject anyone waiting for the poller to finish. + * + * The constructor of a custom implementation of a poller is where any serialized version of + * a previous poller's operation should be deserialized into the operation sent to the + * base constructor. For example: + * + * ```ts + * export class MyPoller extends Poller { + * constructor( + * baseOperation: string | undefined + * ) { + * let state: MyOperationState = {}; + * if (baseOperation) { + * state = { + * ...JSON.parse(baseOperation).state, + * ...state + * }; + * } + * const operation = { + * state, + * // ... + * } + * super(operation); + * } + * } + * ``` + * + * @param operation - Must contain the basic properties of `PollOperation`. */ - SpanStatusCode[SpanStatusCode["UNSET"] = 0] = "UNSET"; + constructor(operation) { + this.stopped = true; + this.pollProgressCallbacks = []; + this.operation = operation; + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + // This prevents the UnhandledPromiseRejectionWarning in node.js from being thrown. + // The above warning would get thrown if `poller.poll` is called, it returns an error, + // and pullUntilDone did not have a .catch or await try/catch on it's return value. + this.promise.catch(() => { + /* intentionally blank */ + }); + } /** - * The operation has been validated by an Application developer or - * Operator to have completed successfully. + * Starts a loop that will break only if the poller is done + * or if the poller is stopped. */ - SpanStatusCode[SpanStatusCode["OK"] = 1] = "OK"; + async startPolling() { + if (this.stopped) { + this.stopped = false; + } + while (!this.isStopped() && !this.isDone()) { + await this.poll(); + await this.delay(); + } + } /** - * The operation contains an error. + * pollOnce does one polling, by calling to the update method of the underlying + * poll operation to make any relevant change effective. + * + * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike. + * + * @param options - Optional properties passed to the operation's update method. */ - SpanStatusCode[SpanStatusCode["ERROR"] = 2] = "ERROR"; -})(exports.SpanStatusCode || (exports.SpanStatusCode = {})); - -// Copyright (c) Microsoft Corporation. -function isTracingDisabled() { - var _a; - if (typeof process === "undefined") { - // not supported in browser for now without polyfills - return false; - } - const azureTracingDisabledValue = (_a = process.env.AZURE_TRACING_DISABLED) === null || _a === void 0 ? void 0 : _a.toLowerCase(); - if (azureTracingDisabledValue === "false" || azureTracingDisabledValue === "0") { - return false; + async pollOnce(options = {}) { + try { + if (!this.isDone()) { + this.operation = await this.operation.update({ + abortSignal: options.abortSignal, + fireProgress: this.fireProgress.bind(this), + }); + if (this.isDone() && this.resolve) { + // If the poller has finished polling, this means we now have a result. + // However, it can be the case that TResult is instantiated to void, so + // we are not expecting a result anyway. To assert that we might not + // have a result eventually after finishing polling, we cast the result + // to TResult. + this.resolve(this.operation.state.result); + } + } + } + catch (e) { + this.operation.state.error = e; + if (this.reject) { + this.reject(e); + } + throw e; + } } - return Boolean(azureTracingDisabledValue); -} -/** - * Creates a function that can be used to create spans using the global tracer. - * - * Usage: - * - * ```typescript - * // once - * const createSpan = createSpanFunction({ packagePrefix: "Azure.Data.AppConfiguration", namespace: "Microsoft.AppConfiguration" }); - * - * // in each operation - * const span = createSpan("deleteConfigurationSetting", operationOptions); - * // code... - * span.end(); - * ``` - * - * @hidden - * @param args - allows configuration of the prefix for each span as well as the az.namespace field. - */ -function createSpanFunction(args) { - return function (operationName, operationOptions) { - const tracer = getTracer(); - const tracingOptions = (operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions) || {}; - const spanOptions = Object.assign({ kind: exports.SpanKind.INTERNAL }, tracingOptions.spanOptions); - const spanName = args.packagePrefix ? `${args.packagePrefix}.${operationName}` : operationName; - let span; - if (isTracingDisabled()) { - span = api.trace.wrapSpanContext(api.INVALID_SPAN_CONTEXT); + /** + * fireProgress calls the functions passed in via onProgress the method of the poller. + * + * It loops over all of the callbacks received from onProgress, and executes them, sending them + * the current operation state. + * + * @param state - The current operation state. + */ + fireProgress(state) { + for (const callback of this.pollProgressCallbacks) { + callback(state); } - else { - span = tracer.startSpan(spanName, spanOptions, tracingOptions.tracingContext); + } + /** + * Invokes the underlying operation's cancel method, and rejects the + * pollUntilDone promise. + */ + async cancelOnce(options = {}) { + this.operation = await this.operation.cancel(options); + if (this.reject) { + this.reject(new PollerCancelledError("Poller cancelled")); } - if (args.namespace) { - span.setAttribute("az.namespace", args.namespace); + } + /** + * Returns a promise that will resolve once a single polling request finishes. + * It does this by calling the update method of the Poller's operation. + * + * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike. + * + * @param options - Optional properties passed to the operation's update method. + */ + poll(options = {}) { + if (!this.pollOncePromise) { + this.pollOncePromise = this.pollOnce(options); + const clearPollOncePromise = () => { + this.pollOncePromise = undefined; + }; + this.pollOncePromise.then(clearPollOncePromise, clearPollOncePromise).catch(this.reject); } - let newSpanOptions = tracingOptions.spanOptions || {}; - if (span.isRecording() && args.namespace) { - newSpanOptions = Object.assign(Object.assign({}, tracingOptions.spanOptions), { attributes: Object.assign(Object.assign({}, spanOptions.attributes), { "az.namespace": args.namespace }) }); + return this.pollOncePromise; + } + /** + * Returns a promise that will resolve once the underlying operation is completed. + */ + async pollUntilDone() { + if (this.stopped) { + this.startPolling().catch(this.reject); } - const newTracingOptions = Object.assign(Object.assign({}, tracingOptions), { spanOptions: newSpanOptions, tracingContext: setSpan(tracingOptions.tracingContext || context.active(), span) }); - const newOperationOptions = Object.assign(Object.assign({}, operationOptions), { tracingOptions: newTracingOptions }); - return { - span, - updatedOptions: newOperationOptions + return this.promise; + } + /** + * Invokes the provided callback after each polling is completed, + * sending the current state of the poller's operation. + * + * It returns a method that can be used to stop receiving updates on the given callback function. + */ + onProgress(callback) { + this.pollProgressCallbacks.push(callback); + return () => { + this.pollProgressCallbacks = this.pollProgressCallbacks.filter((c) => c !== callback); }; - }; -} - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -const VERSION = "00"; -/** - * Generates a `SpanContext` given a `traceparent` header value. - * @param traceParent - Serialized span context data as a `traceparent` header value. - * @returns The `SpanContext` generated from the `traceparent` value. - */ -function extractSpanContextFromTraceParentHeader(traceParentHeader) { - const parts = traceParentHeader.split("-"); - if (parts.length !== 4) { - return; } - const [version, traceId, spanId, traceOptions] = parts; - if (version !== VERSION) { - return; + /** + * Returns true if the poller has finished polling. + */ + isDone() { + const state = this.operation.state; + return Boolean(state.isCompleted || state.isCancelled || state.error); } - const traceFlags = parseInt(traceOptions, 16); - const spanContext = { - spanId, - traceId, - traceFlags - }; - return spanContext; -} -/** - * Generates a `traceparent` value given a span context. - * @param spanContext - Contains context for a specific span. - * @returns The `spanContext` represented as a `traceparent` value. - */ -function getTraceParentHeader(spanContext) { - const missingFields = []; - if (!spanContext.traceId) { - missingFields.push("traceId"); + /** + * Stops the poller from continuing to poll. + */ + stopPolling() { + if (!this.stopped) { + this.stopped = true; + if (this.reject) { + this.reject(new PollerStoppedError("This poller is already stopped")); + } + } } - if (!spanContext.spanId) { - missingFields.push("spanId"); + /** + * Returns true if the poller is stopped. + */ + isStopped() { + return this.stopped; } - if (missingFields.length) { - return; + /** + * Attempts to cancel the underlying operation. + * + * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike. + * + * If it's called again before it finishes, it will throw an error. + * + * @param options - Optional properties passed to the operation's update method. + */ + cancelOperation(options = {}) { + if (!this.stopped) { + this.stopped = true; + } + if (!this.cancelPromise) { + this.cancelPromise = this.cancelOnce(options); + } + else if (options.abortSignal) { + throw new Error("A cancel request is currently pending"); + } + return this.cancelPromise; + } + /** + * Returns the state of the operation. + * + * Even though TState will be the same type inside any of the methods of any extension of the Poller class, + * implementations of the pollers can customize what's shared with the public by writing their own + * version of the `getOperationState` method, and by defining two types, one representing the internal state of the poller + * and a public type representing a safe to share subset of the properties of the internal state. + * Their definition of getOperationState can then return their public type. + * + * Example: + * + * ```ts + * // Let's say we have our poller's operation state defined as: + * interface MyOperationState extends PollOperationState { + * privateProperty?: string; + * publicProperty?: string; + * } + * + * // To allow us to have a true separation of public and private state, we have to define another interface: + * interface PublicState extends PollOperationState { + * publicProperty?: string; + * } + * + * // Then, we define our Poller as follows: + * export class MyPoller extends Poller { + * // ... More content is needed here ... + * + * public getOperationState(): PublicState { + * const state: PublicState = this.operation.state; + * return { + * // Properties from PollOperationState + * isStarted: state.isStarted, + * isCompleted: state.isCompleted, + * isCancelled: state.isCancelled, + * error: state.error, + * result: state.result, + * + * // The only other property needed by PublicState. + * publicProperty: state.publicProperty + * } + * } + * } + * ``` + * + * You can see this in the tests of this repository, go to the file: + * `../test/utils/testPoller.ts` + * and look for the getOperationState implementation. + */ + getOperationState() { + return this.operation.state; + } + /** + * Returns the result value of the operation, + * regardless of the state of the poller. + * It can return undefined or an incomplete form of the final TResult value + * depending on the implementation. + */ + getResult() { + const state = this.operation.state; + return state.result; + } + /** + * Returns a serialized version of the poller's operation + * by invoking the operation's toString method. + */ + toString() { + return this.operation.toString(); } - const flags = spanContext.traceFlags || 0 /* NONE */; - const hexFlags = flags.toString(16); - const traceFlags = hexFlags.length === 1 ? `0${hexFlags}` : hexFlags; - // https://www.w3.org/TR/trace-context/#traceparent-header-field-values - return `${VERSION}-${spanContext.traceId}-${spanContext.spanId}-${traceFlags}`; } -exports.context = context; -exports.createSpanFunction = createSpanFunction; -exports.extractSpanContextFromTraceParentHeader = extractSpanContextFromTraceParentHeader; -exports.getSpan = getSpan; -exports.getSpanContext = getSpanContext; -exports.getTraceParentHeader = getTraceParentHeader; -exports.getTracer = getTracer; -exports.isSpanContextValid = isSpanContextValid; -exports.setSpan = setSpan; -exports.setSpanContext = setSpanContext; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 9241: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var util = _interopDefault(__nccwpck_require__(3837)); -var os = __nccwpck_require__(2037); - // Copyright (c) Microsoft Corporation. -function log(message, ...args) { - process.stderr.write(`${util.format(message, ...args)}${os.EOL}`); +// Licensed under the MIT license. +/** + * Detects where the continuation token is and returns it. Notice that azure-asyncoperation + * must be checked first before the other location headers because there are scenarios + * where both azure-asyncoperation and location could be present in the same response but + * azure-asyncoperation should be the one to use for polling. + */ +function getPollingUrl(rawResponse, defaultPath) { + var _a, _b, _c; + return ((_c = (_b = (_a = getAzureAsyncOperation(rawResponse)) !== null && _a !== void 0 ? _a : getOperationLocation(rawResponse)) !== null && _b !== void 0 ? _b : getLocation(rawResponse)) !== null && _c !== void 0 ? _c : defaultPath); } - -// Copyright (c) Microsoft Corporation. -const debugEnvVariable = (typeof process !== "undefined" && process.env && process.env.DEBUG) || undefined; -let enabledString; -let enabledNamespaces = []; -let skippedNamespaces = []; -const debuggers = []; -if (debugEnvVariable) { - enable(debugEnvVariable); +function getLocation(rawResponse) { + return rawResponse.headers["location"]; } -const debugObj = Object.assign((namespace) => { - return createDebugger(namespace); -}, { - enable, - enabled, - disable, - log -}); -function enable(namespaces) { - enabledString = namespaces; - enabledNamespaces = []; - skippedNamespaces = []; - const wildcard = /\*/g; - const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?")); - for (const ns of namespaceList) { - if (ns.startsWith("-")) { - skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`)); +function getOperationLocation(rawResponse) { + return rawResponse.headers["operation-location"]; +} +function getAzureAsyncOperation(rawResponse) { + return rawResponse.headers["azure-asyncoperation"]; +} +function findResourceLocation(requestMethod, rawResponse, requestPath) { + switch (requestMethod) { + case "PUT": { + return requestPath; } - else { - enabledNamespaces.push(new RegExp(`^${ns}$`)); + case "POST": + case "PATCH": { + return getLocation(rawResponse); + } + default: { + return undefined; } - } - for (const instance of debuggers) { - instance.enabled = enabled(instance.namespace); } } -function enabled(namespace) { - if (namespace.endsWith("*")) { - return true; +function inferLroMode(requestPath, requestMethod, rawResponse) { + if (getAzureAsyncOperation(rawResponse) !== undefined || + getOperationLocation(rawResponse) !== undefined) { + return { + mode: "Location", + resourceLocation: findResourceLocation(requestMethod, rawResponse, requestPath), + }; } - for (const skipped of skippedNamespaces) { - if (skipped.test(namespace)) { - return false; - } + else if (getLocation(rawResponse) !== undefined) { + return { + mode: "Location", + }; } - for (const enabledNamespace of enabledNamespaces) { - if (enabledNamespace.test(namespace)) { - return true; - } + else if (["PUT", "PATCH"].includes(requestMethod)) { + return { + mode: "Body", + }; } - return false; + return {}; } -function disable() { - const result = enabledString || ""; - enable(""); - return result; +class SimpleRestError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "RestError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, SimpleRestError.prototype); + } } -function createDebugger(namespace) { - const newDebugger = Object.assign(debug, { - enabled: enabled(namespace), - destroy, - log: debugObj.log, - namespace, - extend - }); - function debug(...args) { - if (!newDebugger.enabled) { - return; - } - if (args.length > 0) { - args[0] = `${namespace} ${args[0]}`; - } - newDebugger.log(...args); +function isUnexpectedInitialResponse(rawResponse) { + const code = rawResponse.statusCode; + if (![203, 204, 202, 201, 200, 500].includes(code)) { + throw new SimpleRestError(`Received unexpected HTTP status code ${code} in the initial response. This may indicate a server issue.`, code); } - debuggers.push(newDebugger); - return newDebugger; + return false; } -function destroy() { - const index = debuggers.indexOf(this); - if (index >= 0) { - debuggers.splice(index, 1); - return true; +function isUnexpectedPollingResponse(rawResponse) { + const code = rawResponse.statusCode; + if (![202, 201, 200, 500].includes(code)) { + throw new SimpleRestError(`Received unexpected HTTP status code ${code} while polling. This may indicate a server issue.`, code); } return false; } -function extend(namespace) { - const newDebugger = createDebugger(`${this.namespace}:${namespace}`); - newDebugger.log = this.log; - return newDebugger; + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +const successStates = ["succeeded"]; +const failureStates = ["failed", "canceled", "cancelled"]; + +// Copyright (c) Microsoft Corporation. +function getProvisioningState(rawResponse) { + var _a, _b; + const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; + const state = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState; + return typeof state === "string" ? state.toLowerCase() : "succeeded"; +} +function isBodyPollingDone(rawResponse) { + const state = getProvisioningState(rawResponse); + if (isUnexpectedPollingResponse(rawResponse) || failureStates.includes(state)) { + throw new Error(`The long running operation has failed. The provisioning state: ${state}.`); + } + return successStates.includes(state); +} +/** + * Creates a polling strategy based on BodyPolling which uses the provisioning state + * from the result to determine the current operation state + */ +function processBodyPollingOperationResult(response) { + return Object.assign(Object.assign({}, response), { done: isBodyPollingDone(response.rawResponse) }); } // Copyright (c) Microsoft Corporation. -const registeredLoggers = new Set(); -const logLevelFromEnv = (typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL) || undefined; -let azureLogLevel; /** - * The AzureLogger provides a mechanism for overriding where logs are output to. - * By default, logs are sent to stderr. - * Override the `log` method to redirect logs to another location. + * The `@azure/logger` configuration for this package. + * @internal */ -const AzureLogger = debugObj("azure"); -AzureLogger.log = (...args) => { - debugObj.log(...args); -}; -const AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; -if (logLevelFromEnv) { - // avoid calling setLogLevel because we don't want a mis-set environment variable to crash - if (isAzureLogLevel(logLevelFromEnv)) { - setLogLevel(logLevelFromEnv); +const logger = logger$1.createClientLogger("core-lro"); + +// Copyright (c) Microsoft Corporation. +function isPollingDone(rawResponse) { + var _a; + if (isUnexpectedPollingResponse(rawResponse) || rawResponse.statusCode === 202) { + return false; } - else { - console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`); + const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; + const state = typeof status === "string" ? status.toLowerCase() : "succeeded"; + if (isUnexpectedPollingResponse(rawResponse) || failureStates.includes(state)) { + throw new Error(`The long running operation has failed. The provisioning state: ${state}.`); } + return successStates.includes(state); } /** - * Immediately enables logging at the specified log level. - * @param level - The log level to enable for logging. - * Options from most verbose to least verbose are: - * - verbose - * - info - * - warning - * - error + * Sends a request to the URI of the provisioned resource if needed. */ -function setLogLevel(level) { - if (level && !isAzureLogLevel(level)) { - throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`); +async function sendFinalRequest(lro, resourceLocation, lroResourceLocationConfig) { + switch (lroResourceLocationConfig) { + case "original-uri": + return lro.sendPollRequest(lro.requestPath); + case "azure-async-operation": + return undefined; + case "location": + default: + return lro.sendPollRequest(resourceLocation !== null && resourceLocation !== void 0 ? resourceLocation : lro.requestPath); } - azureLogLevel = level; - const enabledNamespaces = []; - for (const logger of registeredLoggers) { - if (shouldEnable(logger)) { - enabledNamespaces.push(logger.namespace); +} +function processLocationPollingOperationResult(lro, resourceLocation, lroResourceLocationConfig) { + return (response) => { + if (isPollingDone(response.rawResponse)) { + if (resourceLocation === undefined) { + return Object.assign(Object.assign({}, response), { done: true }); + } + else { + return Object.assign(Object.assign({}, response), { done: false, next: async () => { + const finalResponse = await sendFinalRequest(lro, resourceLocation, lroResourceLocationConfig); + return Object.assign(Object.assign({}, (finalResponse !== null && finalResponse !== void 0 ? finalResponse : response)), { done: true }); + } }); + } } - } - debugObj.enable(enabledNamespaces.join(",")); + return Object.assign(Object.assign({}, response), { done: false }); + }; +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +function processPassthroughOperationResult(response) { + return Object.assign(Object.assign({}, response), { done: true }); } + +// Copyright (c) Microsoft Corporation. /** - * Retrieves the currently specified log level. + * creates a stepping function that maps an LRO state to another. */ -function getLogLevel() { - return azureLogLevel; +function createGetLroStatusFromResponse(lroPrimitives, config, lroResourceLocationConfig) { + switch (config.mode) { + case "Location": { + return processLocationPollingOperationResult(lroPrimitives, config.resourceLocation, lroResourceLocationConfig); + } + case "Body": { + return processBodyPollingOperationResult; + } + default: { + return processPassthroughOperationResult; + } + } } -const levelMap = { - verbose: 400, - info: 300, - warning: 200, - error: 100 -}; /** - * Creates a logger for use by the Azure SDKs that inherits from `AzureLogger`. - * @param namespace - The name of the SDK package. - * @hidden + * Creates a polling operation. */ -function createClientLogger(namespace) { - const clientRootLogger = AzureLogger.extend(namespace); - patchLogMethod(AzureLogger, clientRootLogger); - return { - error: createLogger(clientRootLogger, "error"), - warning: createLogger(clientRootLogger, "warning"), - info: createLogger(clientRootLogger, "info"), - verbose: createLogger(clientRootLogger, "verbose") +function createPoll(lroPrimitives) { + return async (path, pollerConfig, getLroStatusFromResponse) => { + const response = await lroPrimitives.sendPollRequest(path); + const retryAfter = response.rawResponse.headers["retry-after"]; + if (retryAfter !== undefined) { + // Retry-After header value is either in HTTP date format, or in seconds + const retryAfterInSeconds = parseInt(retryAfter); + pollerConfig.intervalInMs = isNaN(retryAfterInSeconds) + ? calculatePollingIntervalFromDate(new Date(retryAfter), pollerConfig.intervalInMs) + : retryAfterInSeconds * 1000; + } + return getLroStatusFromResponse(response); }; } -function patchLogMethod(parent, child) { - child.log = (...args) => { - parent.log(...args); +function calculatePollingIntervalFromDate(retryAfterDate, defaultIntervalInMs) { + const timeNow = Math.floor(new Date().getTime()); + const retryAfterTime = retryAfterDate.getTime(); + if (timeNow < retryAfterTime) { + return retryAfterTime - timeNow; + } + return defaultIntervalInMs; +} +/** + * Creates a callback to be used to initialize the polling operation state. + * @param state - of the polling operation + * @param operationSpec - of the LRO + * @param callback - callback to be called when the operation is done + * @returns callback that initializes the state of the polling operation + */ +function createInitializeState(state, requestPath, requestMethod) { + return (response) => { + if (isUnexpectedInitialResponse(response.rawResponse)) + ; + state.initialRawResponse = response.rawResponse; + state.isStarted = true; + state.pollingURL = getPollingUrl(state.initialRawResponse, requestPath); + state.config = inferLroMode(requestPath, requestMethod, state.initialRawResponse); + /** short circuit polling if body polling is done in the initial request */ + if (state.config.mode === undefined || + (state.config.mode === "Body" && isBodyPollingDone(state.initialRawResponse))) { + state.result = response.flatResponse; + state.isCompleted = true; + } + logger.verbose(`LRO: initial state: ${JSON.stringify(state)}`); + return Boolean(state.isCompleted); }; } -function createLogger(parent, level) { - const logger = Object.assign(parent.extend(level), { - level - }); - patchLogMethod(parent, logger); - if (shouldEnable(logger)) { - const enabledNamespaces = debugObj.disable(); - debugObj.enable(enabledNamespaces + "," + logger.namespace); + +// Copyright (c) Microsoft Corporation. +class GenericPollOperation { + constructor(state, lro, lroResourceLocationConfig, processResult, updateState, isDone) { + this.state = state; + this.lro = lro; + this.lroResourceLocationConfig = lroResourceLocationConfig; + this.processResult = processResult; + this.updateState = updateState; + this.isDone = isDone; + } + setPollerConfig(pollerConfig) { + this.pollerConfig = pollerConfig; + } + /** + * General update function for LROPoller, the general process is as follows + * 1. Check initial operation result to determine the strategy to use + * - Strategies: Location, Azure-AsyncOperation, Original Uri + * 2. Check if the operation result has a terminal state + * - Terminal state will be determined by each strategy + * 2.1 If it is terminal state Check if a final GET request is required, if so + * send final GET request and return result from operation. If no final GET + * is required, just return the result from operation. + * - Determining what to call for final request is responsibility of each strategy + * 2.2 If it is not terminal state, call the polling operation and go to step 1 + * - Determining what to call for polling is responsibility of each strategy + * - Strategies will always use the latest URI for polling if provided otherwise + * the last known one + */ + async update(options) { + var _a, _b, _c; + const state = this.state; + let lastResponse = undefined; + if (!state.isStarted) { + const initializeState = createInitializeState(state, this.lro.requestPath, this.lro.requestMethod); + lastResponse = await this.lro.sendInitialRequest(); + initializeState(lastResponse); + } + if (!state.isCompleted) { + if (!this.poll || !this.getLroStatusFromResponse) { + if (!state.config) { + throw new Error("Bad state: LRO mode is undefined. Please check if the serialized state is well-formed."); + } + const isDone = this.isDone; + this.getLroStatusFromResponse = isDone + ? (response) => (Object.assign(Object.assign({}, response), { done: isDone(response.flatResponse, this.state) })) + : createGetLroStatusFromResponse(this.lro, state.config, this.lroResourceLocationConfig); + this.poll = createPoll(this.lro); + } + if (!state.pollingURL) { + throw new Error("Bad state: polling URL is undefined. Please check if the serialized state is well-formed."); + } + const currentState = await this.poll(state.pollingURL, this.pollerConfig, this.getLroStatusFromResponse); + logger.verbose(`LRO: polling response: ${JSON.stringify(currentState.rawResponse)}`); + if (currentState.done) { + state.result = this.processResult + ? this.processResult(currentState.flatResponse, state) + : currentState.flatResponse; + state.isCompleted = true; + } + else { + this.poll = (_a = currentState.next) !== null && _a !== void 0 ? _a : this.poll; + state.pollingURL = getPollingUrl(currentState.rawResponse, state.pollingURL); + } + lastResponse = currentState; + } + logger.verbose(`LRO: current state: ${JSON.stringify(state)}`); + if (lastResponse) { + (_b = this.updateState) === null || _b === void 0 ? void 0 : _b.call(this, state, lastResponse === null || lastResponse === void 0 ? void 0 : lastResponse.rawResponse); + } + else { + logger.error(`LRO: no response was received`); + } + (_c = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _c === void 0 ? void 0 : _c.call(options, state); + return this; + } + async cancel() { + this.state.isCancelled = true; + return this; + } + /** + * Serializes the Poller operation. + */ + toString() { + return JSON.stringify({ + state: this.state, + }); } - registeredLoggers.add(logger); - return logger; } -function shouldEnable(logger) { - if (azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]) { - return true; + +// Copyright (c) Microsoft Corporation. +function deserializeState(serializedState) { + try { + return JSON.parse(serializedState).state; } - else { - return false; + catch (e) { + throw new Error(`LroEngine: Unable to deserialize state: ${serializedState}`); } } -function isAzureLogLevel(logLevel) { - return AZURE_LOG_LEVELS.includes(logLevel); +/** + * The LRO Engine, a class that performs polling. + */ +class LroEngine extends Poller { + constructor(lro, options) { + const { intervalInMs = 2000, resumeFrom } = options || {}; + const state = resumeFrom + ? deserializeState(resumeFrom) + : {}; + const operation = new GenericPollOperation(state, lro, options === null || options === void 0 ? void 0 : options.lroResourceLocationConfig, options === null || options === void 0 ? void 0 : options.processResult, options === null || options === void 0 ? void 0 : options.updateState, options === null || options === void 0 ? void 0 : options.isDone); + super(operation); + this.config = { intervalInMs: intervalInMs }; + operation.setPollerConfig(this.config); + } + /** + * The method used by the poller to wait before attempting to update its operation. + */ + delay() { + return new Promise((resolve) => setTimeout(() => resolve(), this.config.intervalInMs)); + } } -exports.AzureLogger = AzureLogger; -exports.createClientLogger = createClientLogger; -exports.getLogLevel = getLogLevel; -exports.setLogLevel = setLogLevel; +exports.LroEngine = LroEngine; +exports.Poller = Poller; +exports.PollerCancelledError = PollerCancelledError; +exports.PollerStoppedError = PollerStoppedError; //# sourceMappingURL=index.js.map /***/ }), -/***/ 9900: +/***/ 74559: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -20939,384 +20634,1239 @@ exports.setLogLevel = setLogLevel; Object.defineProperty(exports, "__esModule", ({ value: true })); -var coreHttp = __nccwpck_require__(2546); -var tslib = __nccwpck_require__(4882); -var coreTracing = __nccwpck_require__(2848); -var logger$1 = __nccwpck_require__(9241); -var abortController = __nccwpck_require__(1733); -var os = __nccwpck_require__(2037); -var crypto = __nccwpck_require__(6113); -var stream = __nccwpck_require__(2781); -__nccwpck_require__(7162); -var coreLro = __nccwpck_require__(3563); -var events = __nccwpck_require__(2361); -var fs = __nccwpck_require__(7147); -var util = __nccwpck_require__(3837); - -function _interopNamespace(e) { - if (e && e.__esModule) return e; - var n = Object.create(null); - if (e) { - Object.keys(e).forEach(function (k) { - if (k !== 'default') { - var d = Object.getOwnPropertyDescriptor(e, k); - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: function () { return e[k]; } - }); - } - }); - } - n["default"] = e; - return Object.freeze(n); -} - -var coreHttp__namespace = /*#__PURE__*/_interopNamespace(coreHttp); -var os__namespace = /*#__PURE__*/_interopNamespace(os); -var fs__namespace = /*#__PURE__*/_interopNamespace(fs); -var util__namespace = /*#__PURE__*/_interopNamespace(util); +var tslib = __nccwpck_require__(26429); -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. +// Copyright (c) Microsoft Corporation. +/** + * returns an async iterator that iterates over results. It also has a `byPage` + * method that returns pages of items at once. * - * Code generated by Microsoft (R) AutoRest Code Generator. - * Changes may cause incorrect behavior and will be lost if the code is regenerated. + * @param pagedResult - an object that specifies how to get pages. + * @returns a paged async iterator that iterates over results. */ -const BlobServiceProperties = { - serializedName: "BlobServiceProperties", - xmlName: "StorageServiceProperties", - type: { - name: "Composite", - className: "BlobServiceProperties", - modelProperties: { - blobAnalyticsLogging: { - serializedName: "Logging", - xmlName: "Logging", - type: { - name: "Composite", - className: "Logging" - } - }, - hourMetrics: { - serializedName: "HourMetrics", - xmlName: "HourMetrics", - type: { - name: "Composite", - className: "Metrics" - } - }, - minuteMetrics: { - serializedName: "MinuteMetrics", - xmlName: "MinuteMetrics", - type: { - name: "Composite", - className: "Metrics" - } - }, - cors: { - serializedName: "Cors", - xmlName: "Cors", - xmlIsWrapped: true, - xmlElementName: "CorsRule", - type: { - name: "Sequence", - element: { - type: { - name: "Composite", - className: "CorsRule" - } - } - } - }, - defaultServiceVersion: { - serializedName: "DefaultServiceVersion", - xmlName: "DefaultServiceVersion", - type: { - name: "String" - } - }, - deleteRetentionPolicy: { - serializedName: "DeleteRetentionPolicy", - xmlName: "DeleteRetentionPolicy", - type: { - name: "Composite", - className: "RetentionPolicy" - } - }, - staticWebsite: { - serializedName: "StaticWebsite", - xmlName: "StaticWebsite", - type: { - name: "Composite", - className: "StaticWebsite" - } - } +function getPagedAsyncIterator(pagedResult) { + var _a; + const iter = getItemAsyncIterator(pagedResult); + return { + next() { + return iter.next(); + }, + [Symbol.asyncIterator]() { + return this; + }, + byPage: (_a = pagedResult === null || pagedResult === void 0 ? void 0 : pagedResult.byPage) !== null && _a !== void 0 ? _a : ((settings) => { + const { continuationToken, maxPageSize } = settings !== null && settings !== void 0 ? settings : {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken, + maxPageSize, + }); + }), + }; +} +function getItemAsyncIterator(pagedResult) { + return tslib.__asyncGenerator(this, arguments, function* getItemAsyncIterator_1() { + var e_1, _a; + const pages = getPageAsyncIterator(pagedResult); + const firstVal = yield tslib.__await(pages.next()); + // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is + if (!Array.isArray(firstVal.value)) { + yield yield tslib.__await(firstVal.value); + // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(pages))); } - } -}; -const Logging = { - serializedName: "Logging", - type: { - name: "Composite", - className: "Logging", - modelProperties: { - version: { - serializedName: "Version", - required: true, - xmlName: "Version", - type: { - name: "String" - } - }, - deleteProperty: { - serializedName: "Delete", - required: true, - xmlName: "Delete", - type: { - name: "Boolean" - } - }, - read: { - serializedName: "Read", - required: true, - xmlName: "Read", - type: { - name: "Boolean" - } - }, - write: { - serializedName: "Write", - required: true, - xmlName: "Write", - type: { - name: "Boolean" - } - }, - retentionPolicy: { - serializedName: "RetentionPolicy", - xmlName: "RetentionPolicy", - type: { - name: "Composite", - className: "RetentionPolicy" + else { + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(firstVal.value))); + try { + for (var pages_1 = tslib.__asyncValues(pages), pages_1_1; pages_1_1 = yield tslib.__await(pages_1.next()), !pages_1_1.done;) { + const page = pages_1_1.value; + // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, + // it must be the case that `TPage = TElement[]` + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(page))); } } - } - } -}; -const RetentionPolicy = { - serializedName: "RetentionPolicy", - type: { - name: "Composite", - className: "RetentionPolicy", - modelProperties: { - enabled: { - serializedName: "Enabled", - required: true, - xmlName: "Enabled", - type: { - name: "Boolean" - } - }, - days: { - constraints: { - InclusiveMinimum: 1 - }, - serializedName: "Days", - xmlName: "Days", - type: { - name: "Number" + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (pages_1_1 && !pages_1_1.done && (_a = pages_1.return)) yield tslib.__await(_a.call(pages_1)); } + finally { if (e_1) throw e_1.error; } } } - } -}; -const Metrics = { - serializedName: "Metrics", - type: { - name: "Composite", - className: "Metrics", - modelProperties: { - version: { - serializedName: "Version", - xmlName: "Version", - type: { - name: "String" - } - }, - enabled: { - serializedName: "Enabled", - required: true, - xmlName: "Enabled", - type: { - name: "Boolean" - } - }, - includeAPIs: { - serializedName: "IncludeAPIs", - xmlName: "IncludeAPIs", - type: { - name: "Boolean" - } - }, - retentionPolicy: { - serializedName: "RetentionPolicy", - xmlName: "RetentionPolicy", - type: { - name: "Composite", - className: "RetentionPolicy" - } - } + }); +} +function getPageAsyncIterator(pagedResult, options = {}) { + return tslib.__asyncGenerator(this, arguments, function* getPageAsyncIterator_1() { + const { pageLink, maxPageSize } = options; + let response = yield tslib.__await(pagedResult.getPage(pageLink !== null && pageLink !== void 0 ? pageLink : pagedResult.firstPageLink, maxPageSize)); + yield yield tslib.__await(response.page); + while (response.nextPageLink) { + response = yield tslib.__await(pagedResult.getPage(response.nextPageLink, maxPageSize)); + yield yield tslib.__await(response.page); } + }); +} + +exports.getPagedAsyncIterator = getPagedAsyncIterator; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 26429: +/***/ ((module) => { + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global global, define, System, Reflect, Promise */ +var __extends; +var __assign; +var __rest; +var __decorate; +var __param; +var __metadata; +var __awaiter; +var __generator; +var __exportStar; +var __values; +var __read; +var __spread; +var __spreadArrays; +var __spreadArray; +var __await; +var __asyncGenerator; +var __asyncDelegator; +var __asyncValues; +var __makeTemplateObject; +var __importStar; +var __importDefault; +var __classPrivateFieldGet; +var __classPrivateFieldSet; +var __classPrivateFieldIn; +var __createBinding; +(function (factory) { + var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; + if (typeof define === "function" && define.amd) { + define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); + } + else if ( true && typeof module.exports === "object") { + factory(createExporter(root, createExporter(module.exports))); + } + else { + factory(createExporter(root)); + } + function createExporter(exports, previous) { + if (exports !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports, "__esModule", { value: true }); + } + else { + exports.__esModule = true; + } + } + return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; + } +}) +(function (exporter) { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + + __extends = function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + + __assign = Object.assign || function (t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + + __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; + }; + + __decorate = function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + + __param = function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + }; + + __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()); + }); + }; + + __generator = function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + + __exportStar = function(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); + }; + + __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]; + }); + + __values = function (o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + + __read = function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + + /** @deprecated */ + __spread = function () { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; + }; + + /** @deprecated */ + __spreadArrays = function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; + }; + + __spreadArray = function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + + __await = function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + + __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]); } + }; + + __asyncDelegator = function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } + }; + + __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); } + }; + + __makeTemplateObject = function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; + }; + + var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }; + + __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; + }; + + __importDefault = function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + + __classPrivateFieldGet = function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); + }; + + __classPrivateFieldSet = function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; + }; + + __classPrivateFieldIn = function (state, receiver) { + if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); + }; + + exporter("__extends", __extends); + exporter("__assign", __assign); + exporter("__rest", __rest); + exporter("__decorate", __decorate); + exporter("__param", __param); + exporter("__metadata", __metadata); + exporter("__awaiter", __awaiter); + exporter("__generator", __generator); + exporter("__exportStar", __exportStar); + exporter("__createBinding", __createBinding); + exporter("__values", __values); + exporter("__read", __read); + exporter("__spread", __spread); + exporter("__spreadArrays", __spreadArrays); + exporter("__spreadArray", __spreadArray); + exporter("__await", __await); + exporter("__asyncGenerator", __asyncGenerator); + exporter("__asyncDelegator", __asyncDelegator); + exporter("__asyncValues", __asyncValues); + exporter("__makeTemplateObject", __makeTemplateObject); + exporter("__importStar", __importStar); + exporter("__importDefault", __importDefault); + exporter("__classPrivateFieldGet", __classPrivateFieldGet); + exporter("__classPrivateFieldSet", __classPrivateFieldSet); + exporter("__classPrivateFieldIn", __classPrivateFieldIn); +}); + + +/***/ }), + +/***/ 94175: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var api = __nccwpck_require__(65163); + +// Copyright (c) Microsoft Corporation. +(function (SpanKind) { + /** Default value. Indicates that the span is used internally. */ + SpanKind[SpanKind["INTERNAL"] = 0] = "INTERNAL"; + /** + * Indicates that the span covers server-side handling of an RPC or other + * remote request. + */ + SpanKind[SpanKind["SERVER"] = 1] = "SERVER"; + /** + * Indicates that the span covers the client-side wrapper around an RPC or + * other remote request. + */ + SpanKind[SpanKind["CLIENT"] = 2] = "CLIENT"; + /** + * Indicates that the span describes producer sending a message to a + * broker. Unlike client and server, there is no direct critical path latency + * relationship between producer and consumer spans. + */ + SpanKind[SpanKind["PRODUCER"] = 3] = "PRODUCER"; + /** + * Indicates that the span describes consumer receiving a message from a + * broker. Unlike client and server, there is no direct critical path latency + * relationship between producer and consumer spans. + */ + SpanKind[SpanKind["CONSUMER"] = 4] = "CONSUMER"; +})(exports.SpanKind || (exports.SpanKind = {})); +/** + * Return the span if one exists + * + * @param context - context to get span from + */ +function getSpan(context) { + return api.trace.getSpan(context); +} +/** + * Set the span on a context + * + * @param context - context to use as parent + * @param span - span to set active + */ +function setSpan(context, span) { + return api.trace.setSpan(context, span); +} +/** + * Wrap span context in a NoopSpan and set as span in a new + * context + * + * @param context - context to set active span on + * @param spanContext - span context to be wrapped + */ +function setSpanContext(context, spanContext) { + return api.trace.setSpanContext(context, spanContext); +} +/** + * Get the span context of the span if it exists. + * + * @param context - context to get values from + */ +function getSpanContext(context) { + return api.trace.getSpanContext(context); +} +/** + * Returns true of the given {@link SpanContext} is valid. + * A valid {@link SpanContext} is one which has a valid trace ID and span ID as per the spec. + * + * @param context - the {@link SpanContext} to validate. + * + * @returns true if the {@link SpanContext} is valid, false otherwise. + */ +function isSpanContextValid(context) { + return api.trace.isSpanContextValid(context); +} +function getTracer(name, version) { + return api.trace.getTracer(name || "azure/core-tracing", version); +} +/** Entrypoint for context API */ +const context = api.context; +(function (SpanStatusCode) { + /** + * The default status. + */ + SpanStatusCode[SpanStatusCode["UNSET"] = 0] = "UNSET"; + /** + * The operation has been validated by an Application developer or + * Operator to have completed successfully. + */ + SpanStatusCode[SpanStatusCode["OK"] = 1] = "OK"; + /** + * The operation contains an error. + */ + SpanStatusCode[SpanStatusCode["ERROR"] = 2] = "ERROR"; +})(exports.SpanStatusCode || (exports.SpanStatusCode = {})); + +// Copyright (c) Microsoft Corporation. +function isTracingDisabled() { + var _a; + if (typeof process === "undefined") { + // not supported in browser for now without polyfills + return false; } -}; -const CorsRule = { - serializedName: "CorsRule", - type: { - name: "Composite", - className: "CorsRule", - modelProperties: { - allowedOrigins: { - serializedName: "AllowedOrigins", - required: true, - xmlName: "AllowedOrigins", - type: { - name: "String" - } - }, - allowedMethods: { - serializedName: "AllowedMethods", - required: true, - xmlName: "AllowedMethods", - type: { - name: "String" - } - }, - allowedHeaders: { - serializedName: "AllowedHeaders", - required: true, - xmlName: "AllowedHeaders", - type: { - name: "String" - } - }, - exposedHeaders: { - serializedName: "ExposedHeaders", - required: true, - xmlName: "ExposedHeaders", - type: { - name: "String" - } - }, - maxAgeInSeconds: { - constraints: { - InclusiveMinimum: 0 - }, - serializedName: "MaxAgeInSeconds", - required: true, - xmlName: "MaxAgeInSeconds", - type: { - name: "Number" - } - } - } + const azureTracingDisabledValue = (_a = process.env.AZURE_TRACING_DISABLED) === null || _a === void 0 ? void 0 : _a.toLowerCase(); + if (azureTracingDisabledValue === "false" || azureTracingDisabledValue === "0") { + return false; } -}; -const StaticWebsite = { - serializedName: "StaticWebsite", - type: { - name: "Composite", - className: "StaticWebsite", + return Boolean(azureTracingDisabledValue); +} +/** + * Creates a function that can be used to create spans using the global tracer. + * + * Usage: + * + * ```typescript + * // once + * const createSpan = createSpanFunction({ packagePrefix: "Azure.Data.AppConfiguration", namespace: "Microsoft.AppConfiguration" }); + * + * // in each operation + * const span = createSpan("deleteConfigurationSetting", operationOptions); + * // code... + * span.end(); + * ``` + * + * @hidden + * @param args - allows configuration of the prefix for each span as well as the az.namespace field. + */ +function createSpanFunction(args) { + return function (operationName, operationOptions) { + const tracer = getTracer(); + const tracingOptions = (operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions) || {}; + const spanOptions = Object.assign({ kind: exports.SpanKind.INTERNAL }, tracingOptions.spanOptions); + const spanName = args.packagePrefix ? `${args.packagePrefix}.${operationName}` : operationName; + let span; + if (isTracingDisabled()) { + span = api.trace.wrapSpanContext(api.INVALID_SPAN_CONTEXT); + } + else { + span = tracer.startSpan(spanName, spanOptions, tracingOptions.tracingContext); + } + if (args.namespace) { + span.setAttribute("az.namespace", args.namespace); + } + let newSpanOptions = tracingOptions.spanOptions || {}; + if (span.isRecording() && args.namespace) { + newSpanOptions = Object.assign(Object.assign({}, tracingOptions.spanOptions), { attributes: Object.assign(Object.assign({}, spanOptions.attributes), { "az.namespace": args.namespace }) }); + } + const newTracingOptions = Object.assign(Object.assign({}, tracingOptions), { spanOptions: newSpanOptions, tracingContext: setSpan(tracingOptions.tracingContext || context.active(), span) }); + const newOperationOptions = Object.assign(Object.assign({}, operationOptions), { tracingOptions: newTracingOptions }); + return { + span, + updatedOptions: newOperationOptions + }; + }; +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +const VERSION = "00"; +/** + * Generates a `SpanContext` given a `traceparent` header value. + * @param traceParent - Serialized span context data as a `traceparent` header value. + * @returns The `SpanContext` generated from the `traceparent` value. + */ +function extractSpanContextFromTraceParentHeader(traceParentHeader) { + const parts = traceParentHeader.split("-"); + if (parts.length !== 4) { + return; + } + const [version, traceId, spanId, traceOptions] = parts; + if (version !== VERSION) { + return; + } + const traceFlags = parseInt(traceOptions, 16); + const spanContext = { + spanId, + traceId, + traceFlags + }; + return spanContext; +} +/** + * Generates a `traceparent` value given a span context. + * @param spanContext - Contains context for a specific span. + * @returns The `spanContext` represented as a `traceparent` value. + */ +function getTraceParentHeader(spanContext) { + const missingFields = []; + if (!spanContext.traceId) { + missingFields.push("traceId"); + } + if (!spanContext.spanId) { + missingFields.push("spanId"); + } + if (missingFields.length) { + return; + } + const flags = spanContext.traceFlags || 0 /* NONE */; + const hexFlags = flags.toString(16); + const traceFlags = hexFlags.length === 1 ? `0${hexFlags}` : hexFlags; + // https://www.w3.org/TR/trace-context/#traceparent-header-field-values + return `${VERSION}-${spanContext.traceId}-${spanContext.spanId}-${traceFlags}`; +} + +exports.context = context; +exports.createSpanFunction = createSpanFunction; +exports.extractSpanContextFromTraceParentHeader = extractSpanContextFromTraceParentHeader; +exports.getSpan = getSpan; +exports.getSpanContext = getSpanContext; +exports.getTraceParentHeader = getTraceParentHeader; +exports.getTracer = getTracer; +exports.isSpanContextValid = isSpanContextValid; +exports.setSpan = setSpan; +exports.setSpanContext = setSpanContext; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 3233: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var util = _interopDefault(__nccwpck_require__(73837)); +var os = __nccwpck_require__(22037); + +// Copyright (c) Microsoft Corporation. +function log(message, ...args) { + process.stderr.write(`${util.format(message, ...args)}${os.EOL}`); +} + +// Copyright (c) Microsoft Corporation. +const debugEnvVariable = (typeof process !== "undefined" && process.env && process.env.DEBUG) || undefined; +let enabledString; +let enabledNamespaces = []; +let skippedNamespaces = []; +const debuggers = []; +if (debugEnvVariable) { + enable(debugEnvVariable); +} +const debugObj = Object.assign((namespace) => { + return createDebugger(namespace); +}, { + enable, + enabled, + disable, + log +}); +function enable(namespaces) { + enabledString = namespaces; + enabledNamespaces = []; + skippedNamespaces = []; + const wildcard = /\*/g; + const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?")); + for (const ns of namespaceList) { + if (ns.startsWith("-")) { + skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`)); + } + else { + enabledNamespaces.push(new RegExp(`^${ns}$`)); + } + } + for (const instance of debuggers) { + instance.enabled = enabled(instance.namespace); + } +} +function enabled(namespace) { + if (namespace.endsWith("*")) { + return true; + } + for (const skipped of skippedNamespaces) { + if (skipped.test(namespace)) { + return false; + } + } + for (const enabledNamespace of enabledNamespaces) { + if (enabledNamespace.test(namespace)) { + return true; + } + } + return false; +} +function disable() { + const result = enabledString || ""; + enable(""); + return result; +} +function createDebugger(namespace) { + const newDebugger = Object.assign(debug, { + enabled: enabled(namespace), + destroy, + log: debugObj.log, + namespace, + extend + }); + function debug(...args) { + if (!newDebugger.enabled) { + return; + } + if (args.length > 0) { + args[0] = `${namespace} ${args[0]}`; + } + newDebugger.log(...args); + } + debuggers.push(newDebugger); + return newDebugger; +} +function destroy() { + const index = debuggers.indexOf(this); + if (index >= 0) { + debuggers.splice(index, 1); + return true; + } + return false; +} +function extend(namespace) { + const newDebugger = createDebugger(`${this.namespace}:${namespace}`); + newDebugger.log = this.log; + return newDebugger; +} + +// Copyright (c) Microsoft Corporation. +const registeredLoggers = new Set(); +const logLevelFromEnv = (typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL) || undefined; +let azureLogLevel; +/** + * The AzureLogger provides a mechanism for overriding where logs are output to. + * By default, logs are sent to stderr. + * Override the `log` method to redirect logs to another location. + */ +const AzureLogger = debugObj("azure"); +AzureLogger.log = (...args) => { + debugObj.log(...args); +}; +const AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; +if (logLevelFromEnv) { + // avoid calling setLogLevel because we don't want a mis-set environment variable to crash + if (isAzureLogLevel(logLevelFromEnv)) { + setLogLevel(logLevelFromEnv); + } + else { + console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`); + } +} +/** + * Immediately enables logging at the specified log level. + * @param level - The log level to enable for logging. + * Options from most verbose to least verbose are: + * - verbose + * - info + * - warning + * - error + */ +function setLogLevel(level) { + if (level && !isAzureLogLevel(level)) { + throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`); + } + azureLogLevel = level; + const enabledNamespaces = []; + for (const logger of registeredLoggers) { + if (shouldEnable(logger)) { + enabledNamespaces.push(logger.namespace); + } + } + debugObj.enable(enabledNamespaces.join(",")); +} +/** + * Retrieves the currently specified log level. + */ +function getLogLevel() { + return azureLogLevel; +} +const levelMap = { + verbose: 400, + info: 300, + warning: 200, + error: 100 +}; +/** + * Creates a logger for use by the Azure SDKs that inherits from `AzureLogger`. + * @param namespace - The name of the SDK package. + * @hidden + */ +function createClientLogger(namespace) { + const clientRootLogger = AzureLogger.extend(namespace); + patchLogMethod(AzureLogger, clientRootLogger); + return { + error: createLogger(clientRootLogger, "error"), + warning: createLogger(clientRootLogger, "warning"), + info: createLogger(clientRootLogger, "info"), + verbose: createLogger(clientRootLogger, "verbose") + }; +} +function patchLogMethod(parent, child) { + child.log = (...args) => { + parent.log(...args); + }; +} +function createLogger(parent, level) { + const logger = Object.assign(parent.extend(level), { + level + }); + patchLogMethod(parent, logger); + if (shouldEnable(logger)) { + const enabledNamespaces = debugObj.disable(); + debugObj.enable(enabledNamespaces + "," + logger.namespace); + } + registeredLoggers.add(logger); + return logger; +} +function shouldEnable(logger) { + if (azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]) { + return true; + } + else { + return false; + } +} +function isAzureLogLevel(logLevel) { + return AZURE_LOG_LEVELS.includes(logLevel); +} + +exports.AzureLogger = AzureLogger; +exports.createClientLogger = createClientLogger; +exports.getLogLevel = getLogLevel; +exports.setLogLevel = setLogLevel; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 84100: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var coreHttp = __nccwpck_require__(24607); +var tslib = __nccwpck_require__(70679); +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__(74559); +var coreLro = __nccwpck_require__(27094); +var events = __nccwpck_require__(82361); +var fs = __nccwpck_require__(57147); +var util = __nccwpck_require__(73837); + +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n["default"] = e; + return Object.freeze(n); +} + +var coreHttp__namespace = /*#__PURE__*/_interopNamespace(coreHttp); +var os__namespace = /*#__PURE__*/_interopNamespace(os); +var fs__namespace = /*#__PURE__*/_interopNamespace(fs); +var util__namespace = /*#__PURE__*/_interopNamespace(util); + +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ +const BlobServiceProperties = { + serializedName: "BlobServiceProperties", + xmlName: "StorageServiceProperties", + type: { + name: "Composite", + className: "BlobServiceProperties", modelProperties: { - enabled: { - serializedName: "Enabled", - required: true, - xmlName: "Enabled", + blobAnalyticsLogging: { + serializedName: "Logging", + xmlName: "Logging", type: { - name: "Boolean" + name: "Composite", + className: "Logging" } }, - indexDocument: { - serializedName: "IndexDocument", - xmlName: "IndexDocument", + hourMetrics: { + serializedName: "HourMetrics", + xmlName: "HourMetrics", type: { - name: "String" + name: "Composite", + className: "Metrics" } }, - errorDocument404Path: { - serializedName: "ErrorDocument404Path", - xmlName: "ErrorDocument404Path", + minuteMetrics: { + serializedName: "MinuteMetrics", + xmlName: "MinuteMetrics", type: { - name: "String" + name: "Composite", + className: "Metrics" } }, - defaultIndexDocumentPath: { - serializedName: "DefaultIndexDocumentPath", - xmlName: "DefaultIndexDocumentPath", + cors: { + serializedName: "Cors", + xmlName: "Cors", + xmlIsWrapped: true, + xmlElementName: "CorsRule", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "CorsRule" + } + } + } + }, + defaultServiceVersion: { + serializedName: "DefaultServiceVersion", + xmlName: "DefaultServiceVersion", type: { name: "String" } + }, + deleteRetentionPolicy: { + serializedName: "DeleteRetentionPolicy", + xmlName: "DeleteRetentionPolicy", + type: { + name: "Composite", + className: "RetentionPolicy" + } + }, + staticWebsite: { + serializedName: "StaticWebsite", + xmlName: "StaticWebsite", + type: { + name: "Composite", + className: "StaticWebsite" + } } } } }; -const StorageError = { - serializedName: "StorageError", +const Logging = { + serializedName: "Logging", type: { name: "Composite", - className: "StorageError", + className: "Logging", modelProperties: { - message: { - serializedName: "Message", - xmlName: "Message", + version: { + serializedName: "Version", + required: true, + xmlName: "Version", type: { name: "String" } }, - code: { - serializedName: "Code", - xmlName: "Code", + deleteProperty: { + serializedName: "Delete", + required: true, + xmlName: "Delete", type: { - name: "String" + name: "Boolean" } - } - } - } -}; -const BlobServiceStatistics = { - serializedName: "BlobServiceStatistics", - xmlName: "StorageServiceStats", - type: { - name: "Composite", - className: "BlobServiceStatistics", - modelProperties: { - geoReplication: { - serializedName: "GeoReplication", - xmlName: "GeoReplication", + }, + read: { + serializedName: "Read", + required: true, + xmlName: "Read", + type: { + name: "Boolean" + } + }, + write: { + serializedName: "Write", + required: true, + xmlName: "Write", + type: { + name: "Boolean" + } + }, + retentionPolicy: { + serializedName: "RetentionPolicy", + xmlName: "RetentionPolicy", type: { name: "Composite", - className: "GeoReplication" + className: "RetentionPolicy" } } } } }; -const GeoReplication = { - serializedName: "GeoReplication", +const RetentionPolicy = { + serializedName: "RetentionPolicy", type: { name: "Composite", - className: "GeoReplication", + className: "RetentionPolicy", modelProperties: { - status: { - serializedName: "Status", + enabled: { + serializedName: "Enabled", required: true, - xmlName: "Status", + xmlName: "Enabled", type: { - name: "Enum", - allowedValues: ["live", "bootstrap", "unavailable"] + name: "Boolean" } }, - lastSyncOn: { + days: { + constraints: { + InclusiveMinimum: 1 + }, + serializedName: "Days", + xmlName: "Days", + type: { + name: "Number" + } + } + } + } +}; +const Metrics = { + serializedName: "Metrics", + type: { + name: "Composite", + className: "Metrics", + modelProperties: { + version: { + serializedName: "Version", + xmlName: "Version", + type: { + name: "String" + } + }, + enabled: { + serializedName: "Enabled", + required: true, + xmlName: "Enabled", + type: { + name: "Boolean" + } + }, + includeAPIs: { + serializedName: "IncludeAPIs", + xmlName: "IncludeAPIs", + type: { + name: "Boolean" + } + }, + retentionPolicy: { + serializedName: "RetentionPolicy", + xmlName: "RetentionPolicy", + type: { + name: "Composite", + className: "RetentionPolicy" + } + } + } + } +}; +const CorsRule = { + serializedName: "CorsRule", + type: { + name: "Composite", + className: "CorsRule", + modelProperties: { + allowedOrigins: { + serializedName: "AllowedOrigins", + required: true, + xmlName: "AllowedOrigins", + type: { + name: "String" + } + }, + allowedMethods: { + serializedName: "AllowedMethods", + required: true, + xmlName: "AllowedMethods", + type: { + name: "String" + } + }, + allowedHeaders: { + serializedName: "AllowedHeaders", + required: true, + xmlName: "AllowedHeaders", + type: { + name: "String" + } + }, + exposedHeaders: { + serializedName: "ExposedHeaders", + required: true, + xmlName: "ExposedHeaders", + type: { + name: "String" + } + }, + maxAgeInSeconds: { + constraints: { + InclusiveMinimum: 0 + }, + serializedName: "MaxAgeInSeconds", + required: true, + xmlName: "MaxAgeInSeconds", + type: { + name: "Number" + } + } + } + } +}; +const StaticWebsite = { + serializedName: "StaticWebsite", + type: { + name: "Composite", + className: "StaticWebsite", + modelProperties: { + enabled: { + serializedName: "Enabled", + required: true, + xmlName: "Enabled", + type: { + name: "Boolean" + } + }, + indexDocument: { + serializedName: "IndexDocument", + xmlName: "IndexDocument", + type: { + name: "String" + } + }, + errorDocument404Path: { + serializedName: "ErrorDocument404Path", + xmlName: "ErrorDocument404Path", + type: { + name: "String" + } + }, + defaultIndexDocumentPath: { + serializedName: "DefaultIndexDocumentPath", + xmlName: "DefaultIndexDocumentPath", + type: { + name: "String" + } + } + } + } +}; +const StorageError = { + serializedName: "StorageError", + type: { + name: "Composite", + className: "StorageError", + modelProperties: { + message: { + serializedName: "Message", + xmlName: "Message", + type: { + name: "String" + } + }, + code: { + serializedName: "Code", + xmlName: "Code", + type: { + name: "String" + } + } + } + } +}; +const BlobServiceStatistics = { + serializedName: "BlobServiceStatistics", + xmlName: "StorageServiceStats", + type: { + name: "Composite", + className: "BlobServiceStatistics", + modelProperties: { + geoReplication: { + serializedName: "GeoReplication", + xmlName: "GeoReplication", + type: { + name: "Composite", + className: "GeoReplication" + } + } + } + } +}; +const GeoReplication = { + serializedName: "GeoReplication", + type: { + name: "Composite", + className: "GeoReplication", + modelProperties: { + status: { + serializedName: "Status", + required: true, + xmlName: "Status", + type: { + name: "Enum", + allowedValues: ["live", "bootstrap", "unavailable"] + } + }, + lastSyncOn: { serializedName: "LastSyncTime", required: true, xmlName: "LastSyncTime", @@ -22025,6 +22575,7 @@ const BlobName = { content: { serializedName: "content", xmlName: "content", + xmlIsMsText: true, type: { name: "String" } @@ -22253,7 +22804,8 @@ const BlobPropertiesInternal = { "P80", "Hot", "Cool", - "Archive" + "Archive", + "Cold" ] } }, @@ -22271,7 +22823,8 @@ const BlobPropertiesInternal = { name: "Enum", allowedValues: [ "rehydrate-pending-to-hot", - "rehydrate-pending-to-cool" + "rehydrate-pending-to-cool", + "rehydrate-pending-to-cold" ] } }, @@ -24752,6 +25305,13 @@ const BlobDownloadHeaders = { name: "DateTimeRfc1123" } }, + createdOn: { + serializedName: "x-ms-creation-time", + xmlName: "x-ms-creation-time", + type: { + name: "DateTimeRfc1123" + } + }, metadata: { serializedName: "x-ms-meta", xmlName: "x-ms-meta", @@ -29434,7 +29994,7 @@ const timeoutInSeconds = { const version = { parameterPath: "version", mapper: { - defaultValue: "2021-06-08", + defaultValue: "2024-05-04", isConstant: true, serializedName: "x-ms-version", type: { @@ -30299,7 +30859,8 @@ const tier = { "P80", "Hot", "Cool", - "Archive" + "Archive", + "Cold" ] } } @@ -30526,7 +31087,8 @@ const tier1 = { "P80", "Hot", "Cool", - "Archive" + "Archive", + "Cold" ] } } @@ -34035,6 +34597,7 @@ const uploadOperationSpec = { blobTagsString, legalHold1, transactionalContentMD5, + transactionalContentCrc64, contentType1, accept2, blobType2 @@ -34262,14 +34825,15 @@ const logger = logger$1.createClientLogger("storage-blob"); // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -const SDK_VERSION = "12.10.0"; -const SERVICE_VERSION = "2021-06-08"; +const SDK_VERSION = "12.18.0"; +const SERVICE_VERSION = "2024-05-04"; 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; const DEFAULT_BLOCK_BUFFER_SIZE_BYTES = 8 * 1024 * 1024; // 8MB const DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES = 4 * 1024 * 1024; // 4MB const DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS = 5; +const REQUEST_TIMEOUT = 100 * 1000; // In ms /** * The OAuth scope to use with Azure Storage. */ @@ -34457,6 +35021,30 @@ const StorageBlobLoggingAllowedQueryParameters = [ ]; const BlobUsesCustomerSpecifiedEncryptionMsg = "BlobUsesCustomerSpecifiedEncryption"; const BlobDoesNotUseCustomerSpecifiedEncryption = "BlobDoesNotUseCustomerSpecifiedEncryption"; +/// List of ports used for path style addressing. +/// Path style addressing means that storage account is put in URI's Path segment in instead of in host. +const PathStylePorts = [ + "10000", + "10001", + "10002", + "10003", + "10004", + "10100", + "10101", + "10102", + "10103", + "10104", + "11000", + "11001", + "11002", + "11003", + "11004", + "11100", + "11101", + "11102", + "11103", + "11104", +]; // Copyright (c) Microsoft Corporation. /** @@ -34602,7 +35190,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"); } @@ -34637,7 +35229,8 @@ function appendToURLPath(url, name) { let path = urlParsed.getPath(); path = path ? (path.endsWith("/") ? `${path}${name}` : `${path}/${name}`) : name; urlParsed.setPath(path); - return urlParsed.toString(); + const normalizedUrl = new URL(urlParsed.toString()); + return normalizedUrl.toString(); } /** * Set URL parameter name and value. If name exists in URL parameters, old value @@ -34895,10 +35488,11 @@ 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()))); } /** * Convert Tags to encoded string. @@ -35073,9 +35667,7 @@ function ConvertInternalResponseOfListBlobHierarchy(internalResponse) { var _a; return Object.assign(Object.assign({}, internalResponse), { segment: { blobPrefixes: (_a = internalResponse.segment.blobPrefixes) === null || _a === void 0 ? void 0 : _a.map((blobPrefixInternal) => { - const blobPrefix = { - name: BlobNameToString(blobPrefixInternal.name), - }; + const blobPrefix = Object.assign(Object.assign({}, blobPrefixInternal), { name: BlobNameToString(blobPrefixInternal.name) }); return blobPrefix; }), blobItems: internalResponse.segment.blobItems.map((blobItemInteral) => { @@ -35084,296 +35676,6 @@ function ConvertInternalResponseOfListBlobHierarchy(internalResponse) { }), } }); } -function decodeBase64String(value) { - if (coreHttp.isNode) { - return Buffer.from(value, "base64"); - } - else { - const byteString = atob(value); - const arr = new Uint8Array(byteString.length); - for (let i = 0; i < byteString.length; i++) { - arr[i] = byteString.charCodeAt(i); - } - return arr; - } -} -function ParseBoolean(content) { - if (content === undefined) - return undefined; - if (content === "true") - return true; - if (content === "false") - return false; - return undefined; -} -function ParseBlobName(blobNameInXML) { - if (blobNameInXML["$"] !== undefined && blobNameInXML["#"] !== undefined) { - return { - encoded: ParseBoolean(blobNameInXML["$"]["Encoded"]), - content: blobNameInXML["#"], - }; - } - else { - return { - encoded: false, - content: blobNameInXML, - }; - } -} -function ParseBlobProperties(blobPropertiesInXML) { - const blobProperties = blobPropertiesInXML; - if (blobPropertiesInXML["Creation-Time"]) { - blobProperties.createdOn = new Date(blobPropertiesInXML["Creation-Time"]); - delete blobProperties["Creation-Time"]; - } - if (blobPropertiesInXML["Last-Modified"]) { - blobProperties.lastModified = new Date(blobPropertiesInXML["Last-Modified"]); - delete blobProperties["Last-Modified"]; - } - if (blobPropertiesInXML["Etag"]) { - blobProperties.etag = blobPropertiesInXML["Etag"]; - delete blobProperties["Etag"]; - } - if (blobPropertiesInXML["Content-Length"]) { - blobProperties.contentLength = parseFloat(blobPropertiesInXML["Content-Length"]); - delete blobProperties["Content-Length"]; - } - if (blobPropertiesInXML["Content-Type"]) { - blobProperties.contentType = blobPropertiesInXML["Content-Type"]; - delete blobProperties["Content-Type"]; - } - if (blobPropertiesInXML["Content-Encoding"]) { - blobProperties.contentEncoding = blobPropertiesInXML["Content-Encoding"]; - delete blobProperties["Content-Encoding"]; - } - if (blobPropertiesInXML["Content-Language"]) { - blobProperties.contentLanguage = blobPropertiesInXML["Content-Language"]; - delete blobProperties["Content-Language"]; - } - if (blobPropertiesInXML["Content-MD5"]) { - blobProperties.contentMD5 = decodeBase64String(blobPropertiesInXML["Content-MD5"]); - delete blobProperties["Content-MD5"]; - } - if (blobPropertiesInXML["Content-Disposition"]) { - blobProperties.contentDisposition = blobPropertiesInXML["Content-Disposition"]; - delete blobProperties["Content-Disposition"]; - } - if (blobPropertiesInXML["Cache-Control"]) { - blobProperties.cacheControl = blobPropertiesInXML["Cache-Control"]; - delete blobProperties["Cache-Control"]; - } - if (blobPropertiesInXML["x-ms-blob-sequence-number"]) { - blobProperties.blobSequenceNumber = parseFloat(blobPropertiesInXML["x-ms-blob-sequence-number"]); - delete blobProperties["x-ms-blob-sequence-number"]; - } - if (blobPropertiesInXML["BlobType"]) { - blobProperties.blobType = blobPropertiesInXML["BlobType"]; - delete blobProperties["BlobType"]; - } - if (blobPropertiesInXML["LeaseStatus"]) { - blobProperties.leaseStatus = blobPropertiesInXML["LeaseStatus"]; - delete blobProperties["LeaseStatus"]; - } - if (blobPropertiesInXML["LeaseState"]) { - blobProperties.leaseState = blobPropertiesInXML["LeaseState"]; - delete blobProperties["LeaseState"]; - } - if (blobPropertiesInXML["LeaseDuration"]) { - blobProperties.leaseDuration = blobPropertiesInXML["LeaseDuration"]; - delete blobProperties["LeaseDuration"]; - } - if (blobPropertiesInXML["CopyId"]) { - blobProperties.copyId = blobPropertiesInXML["CopyId"]; - delete blobProperties["CopyId"]; - } - if (blobPropertiesInXML["CopyStatus"]) { - blobProperties.copyStatus = blobPropertiesInXML["CopyStatus"]; - delete blobProperties["CopyStatus"]; - } - if (blobPropertiesInXML["CopySource"]) { - blobProperties.copySource = blobPropertiesInXML["CopySource"]; - delete blobProperties["CopySource"]; - } - if (blobPropertiesInXML["CopyProgress"]) { - blobProperties.copyProgress = blobPropertiesInXML["CopyProgress"]; - delete blobProperties["CopyProgress"]; - } - if (blobPropertiesInXML["CopyCompletionTime"]) { - blobProperties.copyCompletedOn = new Date(blobPropertiesInXML["CopyCompletionTime"]); - delete blobProperties["CopyCompletionTime"]; - } - if (blobPropertiesInXML["CopyStatusDescription"]) { - blobProperties.copyStatusDescription = blobPropertiesInXML["CopyStatusDescription"]; - delete blobProperties["CopyStatusDescription"]; - } - if (blobPropertiesInXML["ServerEncrypted"]) { - blobProperties.serverEncrypted = ParseBoolean(blobPropertiesInXML["ServerEncrypted"]); - delete blobProperties["ServerEncrypted"]; - } - if (blobPropertiesInXML["IncrementalCopy"]) { - blobProperties.incrementalCopy = ParseBoolean(blobPropertiesInXML["IncrementalCopy"]); - delete blobProperties["IncrementalCopy"]; - } - if (blobPropertiesInXML["DestinationSnapshot"]) { - blobProperties.destinationSnapshot = blobPropertiesInXML["DestinationSnapshot"]; - delete blobProperties["DestinationSnapshot"]; - } - if (blobPropertiesInXML["DeletedTime"]) { - blobProperties.deletedOn = new Date(blobPropertiesInXML["DeletedTime"]); - delete blobProperties["DeletedTime"]; - } - if (blobPropertiesInXML["RemainingRetentionDays"]) { - blobProperties.remainingRetentionDays = parseFloat(blobPropertiesInXML["RemainingRetentionDays"]); - delete blobProperties["RemainingRetentionDays"]; - } - if (blobPropertiesInXML["AccessTier"]) { - blobProperties.accessTier = blobPropertiesInXML["AccessTier"]; - delete blobProperties["AccessTier"]; - } - if (blobPropertiesInXML["AccessTierInferred"]) { - blobProperties.accessTierInferred = ParseBoolean(blobPropertiesInXML["AccessTierInferred"]); - delete blobProperties["AccessTierInferred"]; - } - if (blobPropertiesInXML["ArchiveStatus"]) { - blobProperties.archiveStatus = blobPropertiesInXML["ArchiveStatus"]; - delete blobProperties["ArchiveStatus"]; - } - if (blobPropertiesInXML["CustomerProvidedKeySha256"]) { - blobProperties.customerProvidedKeySha256 = blobPropertiesInXML["CustomerProvidedKeySha256"]; - delete blobProperties["CustomerProvidedKeySha256"]; - } - if (blobPropertiesInXML["EncryptionScope"]) { - blobProperties.encryptionScope = blobPropertiesInXML["EncryptionScope"]; - delete blobProperties["EncryptionScope"]; - } - if (blobPropertiesInXML["AccessTierChangeTime"]) { - blobProperties.accessTierChangedOn = new Date(blobPropertiesInXML["AccessTierChangeTime"]); - delete blobProperties["AccessTierChangeTime"]; - } - if (blobPropertiesInXML["TagCount"]) { - blobProperties.tagCount = parseFloat(blobPropertiesInXML["TagCount"]); - delete blobProperties["TagCount"]; - } - if (blobPropertiesInXML["Expiry-Time"]) { - blobProperties.expiresOn = new Date(blobPropertiesInXML["Expiry-Time"]); - delete blobProperties["Expiry-Time"]; - } - if (blobPropertiesInXML["Sealed"]) { - blobProperties.isSealed = ParseBoolean(blobPropertiesInXML["Sealed"]); - delete blobProperties["Sealed"]; - } - if (blobPropertiesInXML["RehydratePriority"]) { - blobProperties.rehydratePriority = blobPropertiesInXML["RehydratePriority"]; - delete blobProperties["RehydratePriority"]; - } - if (blobPropertiesInXML["LastAccessTime"]) { - blobProperties.lastAccessedOn = new Date(blobPropertiesInXML["LastAccessTime"]); - delete blobProperties["LastAccessTime"]; - } - if (blobPropertiesInXML["ImmutabilityPolicyUntilDate"]) { - blobProperties.immutabilityPolicyExpiresOn = new Date(blobPropertiesInXML["ImmutabilityPolicyUntilDate"]); - delete blobProperties["ImmutabilityPolicyUntilDate"]; - } - if (blobPropertiesInXML["ImmutabilityPolicyMode"]) { - blobProperties.immutabilityPolicyMode = blobPropertiesInXML["ImmutabilityPolicyMode"]; - delete blobProperties["ImmutabilityPolicyMode"]; - } - if (blobPropertiesInXML["LegalHold"]) { - blobProperties.legalHold = ParseBoolean(blobPropertiesInXML["LegalHold"]); - delete blobProperties["LegalHold"]; - } - return blobProperties; -} -function ParseBlobItem(blobInXML) { - const blobItem = blobInXML; - blobItem.properties = ParseBlobProperties(blobInXML["Properties"]); - delete blobItem["Properties"]; - blobItem.name = ParseBlobName(blobInXML["Name"]); - delete blobItem["Name"]; - blobItem.deleted = ParseBoolean(blobInXML["Deleted"]); - delete blobItem["Deleted"]; - if (blobInXML["Snapshot"]) { - blobItem.snapshot = blobInXML["Snapshot"]; - delete blobItem["Snapshot"]; - } - if (blobInXML["VersionId"]) { - blobItem.versionId = blobInXML["VersionId"]; - delete blobItem["VersionId"]; - } - if (blobInXML["IsCurrentVersion"]) { - blobItem.isCurrentVersion = ParseBoolean(blobInXML["IsCurrentVersion"]); - delete blobItem["IsCurrentVersion"]; - } - if (blobInXML["Metadata"]) { - blobItem.metadata = blobInXML["Metadata"]; - delete blobItem["Metadata"]; - } - if (blobInXML["Tags"]) { - blobItem.blobTags = ParseBlobTags(blobInXML["Tags"]); - delete blobItem["Tags"]; - } - if (blobInXML["OrMetadata"]) { - blobItem.objectReplicationMetadata = blobInXML["OrMetadata"]; - delete blobItem["OrMetadata"]; - } - if (blobInXML["HasVersionsOnly"]) { - blobItem.hasVersionsOnly = ParseBoolean(blobInXML["HasVersionsOnly"]); - delete blobItem["HasVersionsOnly"]; - } - return blobItem; -} -function ParseBlobPrefix(blobPrefixInXML) { - return { - name: ParseBlobName(blobPrefixInXML["Name"]), - }; -} -function ParseBlobTag(blobTagInXML) { - return { - key: blobTagInXML["Key"], - value: blobTagInXML["Value"], - }; -} -function ParseBlobTags(blobTagsInXML) { - if (blobTagsInXML === undefined || - blobTagsInXML["TagSet"] === undefined || - blobTagsInXML["TagSet"]["Tag"] === undefined) { - return undefined; - } - const blobTagSet = []; - if (blobTagsInXML["TagSet"]["Tag"] instanceof Array) { - blobTagsInXML["TagSet"]["Tag"].forEach((blobTagInXML) => { - blobTagSet.push(ParseBlobTag(blobTagInXML)); - }); - } - else { - blobTagSet.push(ParseBlobTag(blobTagsInXML["TagSet"]["Tag"])); - } - return { blobTagSet: blobTagSet }; -} -function ProcessBlobItems(blobArrayInXML) { - const blobItems = []; - if (blobArrayInXML instanceof Array) { - blobArrayInXML.forEach((blobInXML) => { - blobItems.push(ParseBlobItem(blobInXML)); - }); - } - else { - blobItems.push(ParseBlobItem(blobArrayInXML)); - } - return blobItems; -} -function ProcessBlobPrefixes(blobPrefixesInXML) { - const blobPrefixes = []; - if (blobPrefixesInXML instanceof Array) { - blobPrefixesInXML.forEach((blobPrefixInXML) => { - blobPrefixes.push(ParseBlobPrefix(blobPrefixInXML)); - }); - } - else { - blobPrefixes.push(ParseBlobPrefix(blobPrefixesInXML)); - } - return blobPrefixes; -} function* ExtractPageRangeInfoItems(getPageRangesSegment) { let pageRange = []; let clearRange = []; @@ -35416,6 +35718,16 @@ function* ExtractPageRangeInfoItems(getPageRangesSegment) { }; } } +/** + * Escape the blobName but keep path separator ('/'). + */ +function EscapePath(blobName) { + const split = blobName.split("/"); + for (let i = 0; i < split.length; i++) { + split[i] = encodeURIComponent(split[i]); + } + return split.join("/"); +} // Copyright (c) Microsoft Corporation. /** @@ -36374,7 +36686,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.10.0"; +const packageVersion = "12.18.0"; class StorageClientContext extends coreHttp__namespace.ServiceClient { /** * Initializes a new instance of the StorageClientContext class. @@ -36400,7 +36712,7 @@ class StorageClientContext extends coreHttp__namespace.ServiceClient { // Parameter assignments this.url = url; // Assigning values to Constant parameters - this.version = options.version || "2021-06-08"; + this.version = options.version || "2024-05-04"; } } @@ -38329,6 +38641,14 @@ class BlobDownloadResponse { get lastAccessed() { return this.originalResponse.lastAccessed; } + /** + * Returns the date and time the blob was created. + * + * @readonly + */ + get createdOn() { + return this.originalResponse.createdOn; + } /** * A name-value pair * to associate with a file storage object. @@ -38759,6 +39079,7 @@ class AvroUnionType extends AvroType { this._types = types; } async read(stream, options = {}) { + // eslint-disable-line @typescript-eslint/ban-types const typeIndex = await AvroParser.readInt(stream, options); return this._types[typeIndex].read(stream, options); } @@ -39482,6 +39803,10 @@ exports.BlockBlobTier = void 0; * Optimized for storing data that is infrequently accessed and stored for at least 30 days. */ BlockBlobTier["Cool"] = "Cool"; + /** + * Optimized for storing data that is rarely accessed. + */ + BlockBlobTier["Cold"] = "Cold"; /** * Optimized for storing data that is rarely accessed and stored for at least 180 days * with flexible latency requirements (on the order of hours). @@ -39568,6 +39893,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. @@ -39945,7 +40273,7 @@ class BuffersStream extends stream.Readable { * maxBufferLength is max size of each buffer in the pooled buffers. */ // Can't use import as Typescript doesn't recognize "buffer". -const maxBufferLength = (__nccwpck_require__(4300).constants.MAX_LENGTH); +const maxBufferLength = (__nccwpck_require__(14300).constants.MAX_LENGTH); /** * This class provides a buffer container which conceptually has no hard size limit. * It accepts a capacity, an array of input buffers and the total length of input data. @@ -40288,8 +40616,10 @@ async function streamToBuffer(stream, buffer, offset, end, encoding) { let pos = 0; // Position in stream const count = end - offset; // Total amount of data needed in stream return new Promise((resolve, reject) => { + const timeout = setTimeout(() => reject(new Error(`The operation cannot be completed in timeout.`)), REQUEST_TIMEOUT); stream.on("readable", () => { if (pos >= count) { + clearTimeout(timeout); resolve(); return; } @@ -40306,12 +40636,16 @@ async function streamToBuffer(stream, buffer, offset, end, encoding) { pos += chunkLength; }); stream.on("end", () => { + clearTimeout(timeout); if (pos < count) { reject(new Error(`Stream drains before getting enough data needed. Data read: ${pos}, data need: ${count}`)); } resolve(); }); - stream.on("error", reject); + stream.on("error", (msg) => { + clearTimeout(timeout); + reject(msg); + }); }); } /** @@ -40407,6 +40741,9 @@ class BlobClient extends StorageClient { // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) // The second parameter is undefined. Use anonymous credential. url = urlOrConnectionString; + if (blobNameOrOptions && typeof blobNameOrOptions !== "string") { + options = blobNameOrOptions; + } pipeline = newPipeline(new AnonymousCredential(), options); } else if (credentialOrPipelineOrContainerName && @@ -41077,7 +41414,7 @@ class BlobClient extends StorageClient { sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince, - }, sourceContentMD5: options.sourceContentMD5, copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization), blobTagsString: toBlobTagsString(options.tags), immutabilityPolicyExpiry: (_b = options.immutabilityPolicy) === null || _b === void 0 ? void 0 : _b.expiriesOn, immutabilityPolicyMode: (_c = options.immutabilityPolicy) === null || _c === void 0 ? void 0 : _c.policyMode, legalHold: options.legalHold, encryptionScope: options.encryptionScope, copySourceTags: options.copySourceTags }, convertTracingToRequestOptionsBase(updatedOptions))); + }, sourceContentMD5: options.sourceContentMD5, copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization), tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags), immutabilityPolicyExpiry: (_b = options.immutabilityPolicy) === null || _b === void 0 ? void 0 : _b.expiriesOn, immutabilityPolicyMode: (_c = options.immutabilityPolicy) === null || _c === void 0 ? void 0 : _c.policyMode, legalHold: options.legalHold, encryptionScope: options.encryptionScope, copySourceTags: options.copySourceTags }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ @@ -41710,6 +42047,9 @@ class BlockBlobClient extends BlobClient { // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) // The second parameter is undefined. Use anonymous credential. url = urlOrConnectionString; + if (blobNameOrOptions && typeof blobNameOrOptions !== "string") { + options = blobNameOrOptions; + } pipeline = newPipeline(new AnonymousCredential(), options); } else if (credentialOrPipelineOrContainerName && @@ -43803,6 +44143,7 @@ class ContainerClient extends StorageClient { * Creates a new container under the specified account. If the container with * the same name already exists, the operation fails. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container + * Naming rules: @see https://learn.microsoft.com/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata * * @param options - Options to Container Create operation. * @@ -43837,6 +44178,7 @@ class ContainerClient extends StorageClient { * Creates a new container under the specified account. If the container with * the same name already exists, it is not changed. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container + * Naming rules: @see https://learn.microsoft.com/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata * * @param options - */ @@ -43908,7 +44250,7 @@ class ContainerClient extends StorageClient { * @returns A new BlobClient object for the given blob name. */ getBlobClient(blobName) { - return new BlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); + return new BlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); } /** * Creates an {@link AppendBlobClient} @@ -43916,7 +44258,7 @@ class ContainerClient extends StorageClient { * @param blobName - An append blob name */ getAppendBlobClient(blobName) { - return new AppendBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); + return new AppendBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); } /** * Creates a {@link BlockBlobClient} @@ -43934,7 +44276,7 @@ class ContainerClient extends StorageClient { * ``` */ getBlockBlobClient(blobName) { - return new BlockBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); + return new BlockBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); } /** * Creates a {@link PageBlobClient} @@ -43942,7 +44284,7 @@ class ContainerClient extends StorageClient { * @param blobName - A page blob name */ getPageBlobClient(blobName) { - return new PageBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); + return new PageBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); } /** * Returns all user-defined metadata and system properties for the specified @@ -44274,10 +44616,6 @@ class ContainerClient extends StorageClient { const { span, updatedOptions } = createSpan("ContainerClient-listBlobFlatSegment", options); try { const response = await this.containerContext.listBlobFlatSegment(Object.assign(Object.assign({ marker }, options), convertTracingToRequestOptionsBase(updatedOptions))); - response.segment.blobItems = []; - if (response.segment["Blob"] !== undefined) { - response.segment.blobItems = ProcessBlobItems(response.segment["Blob"]); - } const wrappedResponse = Object.assign(Object.assign({}, response), { _response: Object.assign(Object.assign({}, response._response), { parsedBody: ConvertInternalResponseOfListBlobFlat(response._response.parsedBody) }), segment: Object.assign(Object.assign({}, response.segment), { blobItems: response.segment.blobItems.map((blobItemInteral) => { const blobItem = Object.assign(Object.assign({}, blobItemInteral), { name: BlobNameToString(blobItemInteral.name), tags: toTags(blobItemInteral.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInteral.objectReplicationMetadata) }); return blobItem; @@ -44311,21 +44649,11 @@ class ContainerClient extends StorageClient { const { span, updatedOptions } = createSpan("ContainerClient-listBlobHierarchySegment", options); try { const response = await this.containerContext.listBlobHierarchySegment(delimiter, Object.assign(Object.assign({ marker }, options), convertTracingToRequestOptionsBase(updatedOptions))); - response.segment.blobItems = []; - if (response.segment["Blob"] !== undefined) { - response.segment.blobItems = ProcessBlobItems(response.segment["Blob"]); - } - response.segment.blobPrefixes = []; - if (response.segment["BlobPrefix"] !== undefined) { - response.segment.blobPrefixes = ProcessBlobPrefixes(response.segment["BlobPrefix"]); - } const wrappedResponse = Object.assign(Object.assign({}, response), { _response: Object.assign(Object.assign({}, response._response), { parsedBody: ConvertInternalResponseOfListBlobHierarchy(response._response.parsedBody) }), segment: Object.assign(Object.assign({}, response.segment), { blobItems: response.segment.blobItems.map((blobItemInteral) => { const blobItem = Object.assign(Object.assign({}, blobItemInteral), { name: BlobNameToString(blobItemInteral.name), tags: toTags(blobItemInteral.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInteral.objectReplicationMetadata) }); return blobItem; }), blobPrefixes: (_a = response.segment.blobPrefixes) === null || _a === void 0 ? void 0 : _a.map((blobPrefixInternal) => { - const blobPrefix = { - name: BlobNameToString(blobPrefixInternal.name), - }; + const blobPrefix = Object.assign(Object.assign({}, blobPrefixInternal), { name: BlobNameToString(blobPrefixInternal.name) }); return blobPrefix; }) }) }); return wrappedResponse; @@ -45530,7 +45858,7 @@ class BlobServiceClient extends StorageClient { return new ContainerClient(appendToURLPath(this.url, encodeURIComponent(containerName)), this.pipeline); } /** - * Create a Blob container. + * Create a Blob container. @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container * * @param containerName - Name of the container to create. * @param options - Options to configure Container Create operation. @@ -46217,6 +46545,14 @@ class BlobServiceClient extends StorageClient { } } +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** Known values of {@link EncryptionAlgorithmType} that the service accepts. */ +exports.KnownEncryptionAlgorithmType = void 0; +(function (KnownEncryptionAlgorithmType) { + KnownEncryptionAlgorithmType["AES256"] = "AES256"; +})(exports.KnownEncryptionAlgorithmType || (exports.KnownEncryptionAlgorithmType = {})); + Object.defineProperty(exports, "BaseRequestPolicy", ({ enumerable: true, get: function () { return coreHttp.BaseRequestPolicy; } @@ -46270,6 +46606,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; @@ -46278,7 +46615,7 @@ exports.newPipeline = newPipeline; /***/ }), -/***/ 4882: +/***/ 70679: /***/ ((module) => { /****************************************************************************** @@ -46602,7 +46939,7 @@ var __createBinding; /***/ }), -/***/ 8649: +/***/ 40334: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -46665,7 +47002,7 @@ exports.createTokenAuth = createTokenAuth; /***/ }), -/***/ 7462: +/***/ 76762: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -46673,11 +47010,11 @@ exports.createTokenAuth = createTokenAuth; Object.defineProperty(exports, "__esModule", ({ value: true })); -var universalUserAgent = __nccwpck_require__(3877); -var beforeAfterHook = __nccwpck_require__(3573); -var request = __nccwpck_require__(5023); -var graphql = __nccwpck_require__(4325); -var authToken = __nccwpck_require__(8649); +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 {}; @@ -46849,7 +47186,7 @@ exports.Octokit = Octokit; /***/ }), -/***/ 9047: +/***/ 59440: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -46857,8 +47194,8 @@ exports.Octokit = Octokit; Object.defineProperty(exports, "__esModule", ({ value: true })); -var isPlainObject = __nccwpck_require__(646); -var universalUserAgent = __nccwpck_require__(3877); +var isPlainObject = __nccwpck_require__(63287); +var universalUserAgent = __nccwpck_require__(45030); function lowercaseKeys(object) { if (!object) { @@ -47247,7 +47584,7 @@ exports.endpoint = endpoint; /***/ }), -/***/ 4325: +/***/ 88467: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -47255,8 +47592,8 @@ exports.endpoint = endpoint; Object.defineProperty(exports, "__esModule", ({ value: true })); -var request = __nccwpck_require__(5023); -var universalUserAgent = __nccwpck_require__(3877); +var request = __nccwpck_require__(36234); +var universalUserAgent = __nccwpck_require__(45030); const VERSION = "4.8.0"; @@ -47373,7 +47710,7 @@ exports.withCustomRequest = withCustomRequest; /***/ }), -/***/ 2182: +/***/ 64193: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -47598,7 +47935,7 @@ exports.paginatingEndpoints = paginatingEndpoints; /***/ }), -/***/ 85: +/***/ 68883: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -47636,7 +47973,7 @@ exports.requestLog = requestLog; /***/ }), -/***/ 7591: +/***/ 83044: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -48669,7 +49006,91 @@ exports.restEndpointMethods = restEndpointMethods; /***/ }), -/***/ 1643: +/***/ 86298: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +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__(11174)); + +// @ts-ignore +async function errorRequest(octokit, state, error, options) { + if (!error.request || !error.request.request) { + // address https://github.com/octokit/plugin-retry.js/issues/8 + throw error; + } // retry all >= 400 && not doNotRetry + + + if (error.status >= 400 && !state.doNotRetry.includes(error.status)) { + const retries = options.request.retries != null ? options.request.retries : state.retries; + const retryAfter = Math.pow((options.request.retryCount || 0) + 1, 2); + throw octokit.retry.retryRequest(error, retries, retryAfter); + } // Maybe eventually there will be more cases here + + + throw error; +} + +// @ts-ignore + +async function wrapRequest(state, request, options) { + const limiter = new Bottleneck(); // @ts-ignore + + limiter.on("failed", function (error, info) { + const maxRetries = ~~error.request.request.retries; + const after = ~~error.request.request.retryAfter; + options.request.retryCount = info.retryCount + 1; + + if (maxRetries > info.retryCount) { + // Returning a number instructs the limiter to retry + // the request after that number of milliseconds have passed + return after * state.retryAfterBaseValue; + } + }); + return limiter.schedule(request, options); +} + +const VERSION = "3.0.9"; +function retry(octokit, octokitOptions) { + const state = Object.assign({ + enabled: true, + retryAfterBaseValue: 1000, + doNotRetry: [400, 401, 403, 404, 422], + retries: 3 + }, octokitOptions.retry); + + if (state.enabled) { + octokit.hook.error("request", errorRequest.bind(null, octokit, state)); + octokit.hook.wrap("request", wrapRequest.bind(null, state)); + } + + return { + retry: { + retryRequest: (error, retries, retryAfter) => { + error.request.request = Object.assign({}, error.request.request, { + retries: retries, + retryAfter: retryAfter + }); + return error; + } + } + }; +} +retry.VERSION = VERSION; + +exports.VERSION = VERSION; +exports.retry = retry; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 10537: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -48679,8 +49100,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__(6036); -var once = _interopDefault(__nccwpck_require__(4410)); +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)); @@ -48751,7 +49172,7 @@ exports.RequestError = RequestError; /***/ }), -/***/ 5023: +/***/ 36234: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -48761,11 +49182,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__(9047); -var universalUserAgent = __nccwpck_require__(3877); -var isPlainObject = __nccwpck_require__(646); -var nodeFetch = _interopDefault(__nccwpck_require__(4956)); -var requestError = __nccwpck_require__(1643); +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__(10537); const VERSION = "5.6.3"; @@ -48936,7 +49357,7 @@ exports.request = request; /***/ }), -/***/ 5458: +/***/ 55375: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -48944,10 +49365,10 @@ exports.request = request; Object.defineProperty(exports, "__esModule", ({ value: true })); -var core = __nccwpck_require__(7462); -var pluginRequestLog = __nccwpck_require__(85); -var pluginPaginateRest = __nccwpck_require__(2182); -var pluginRestEndpointMethods = __nccwpck_require__(7591); +var core = __nccwpck_require__(76762); +var pluginRequestLog = __nccwpck_require__(68883); +var pluginPaginateRest = __nccwpck_require__(64193); +var pluginRestEndpointMethods = __nccwpck_require__(83044); const VERSION = "18.12.0"; @@ -48961,7 +49382,7 @@ exports.Octokit = Octokit; /***/ }), -/***/ 8222: +/***/ 57171: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -48988,9 +49409,9 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ContextAPI = void 0; -var NoopContextManager_1 = __nccwpck_require__(851); -var global_utils_1 = __nccwpck_require__(954); -var diag_1 = __nccwpck_require__(6081); +var NoopContextManager_1 = __nccwpck_require__(54118); +var global_utils_1 = __nccwpck_require__(85135); +var diag_1 = __nccwpck_require__(11877); var API_NAME = 'context'; var NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager(); /** @@ -49061,7 +49482,7 @@ exports.ContextAPI = ContextAPI; /***/ }), -/***/ 6081: +/***/ 11877: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -49083,10 +49504,10 @@ exports.ContextAPI = ContextAPI; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DiagAPI = void 0; -var ComponentLogger_1 = __nccwpck_require__(8240); -var logLevelLogger_1 = __nccwpck_require__(2609); -var types_1 = __nccwpck_require__(5581); -var global_utils_1 = __nccwpck_require__(954); +var ComponentLogger_1 = __nccwpck_require__(17978); +var logLevelLogger_1 = __nccwpck_require__(99639); +var types_1 = __nccwpck_require__(78077); +var global_utils_1 = __nccwpck_require__(85135); var API_NAME = 'diag'; /** * Singleton object which represents the entry point to the OpenTelemetry internal @@ -49161,7 +49582,7 @@ exports.DiagAPI = DiagAPI; /***/ }), -/***/ 7218: +/***/ 89909: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -49183,12 +49604,12 @@ exports.DiagAPI = DiagAPI; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PropagationAPI = void 0; -var global_utils_1 = __nccwpck_require__(954); -var NoopTextMapPropagator_1 = __nccwpck_require__(4002); -var TextMapPropagator_1 = __nccwpck_require__(3600); -var context_helpers_1 = __nccwpck_require__(2650); -var utils_1 = __nccwpck_require__(6266); -var diag_1 = __nccwpck_require__(6081); +var global_utils_1 = __nccwpck_require__(85135); +var NoopTextMapPropagator_1 = __nccwpck_require__(72368); +var TextMapPropagator_1 = __nccwpck_require__(80865); +var context_helpers_1 = __nccwpck_require__(37682); +var utils_1 = __nccwpck_require__(28136); +var diag_1 = __nccwpck_require__(11877); var API_NAME = 'propagation'; var NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator(); /** @@ -49259,7 +49680,7 @@ exports.PropagationAPI = PropagationAPI; /***/ }), -/***/ 4153: +/***/ 81539: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -49281,11 +49702,11 @@ exports.PropagationAPI = PropagationAPI; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TraceAPI = void 0; -var global_utils_1 = __nccwpck_require__(954); -var ProxyTracerProvider_1 = __nccwpck_require__(1595); -var spancontext_utils_1 = __nccwpck_require__(9741); -var context_utils_1 = __nccwpck_require__(3074); -var diag_1 = __nccwpck_require__(6081); +var global_utils_1 = __nccwpck_require__(85135); +var ProxyTracerProvider_1 = __nccwpck_require__(2285); +var spancontext_utils_1 = __nccwpck_require__(49745); +var context_utils_1 = __nccwpck_require__(23326); +var diag_1 = __nccwpck_require__(11877); var API_NAME = 'trace'; /** * Singleton object which represents the entry point to the OpenTelemetry Tracing API @@ -49345,7 +49766,7 @@ exports.TraceAPI = TraceAPI; /***/ }), -/***/ 2650: +/***/ 37682: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -49367,7 +49788,7 @@ exports.TraceAPI = TraceAPI; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.deleteBaggage = exports.setBaggage = exports.getBaggage = void 0; -var context_1 = __nccwpck_require__(4456); +var context_1 = __nccwpck_require__(78242); /** * Baggage key */ @@ -49405,7 +49826,7 @@ exports.deleteBaggage = deleteBaggage; /***/ }), -/***/ 6891: +/***/ 84811: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -49476,7 +49897,7 @@ exports.BaggageImpl = BaggageImpl; /***/ }), -/***/ 1321: +/***/ 23542: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -49506,7 +49927,7 @@ exports.baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata'); /***/ }), -/***/ 4761: +/***/ 91508: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -49531,7 +49952,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 6266: +/***/ 28136: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -49553,9 +49974,9 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.baggageEntryMetadataFromString = exports.createBaggage = void 0; -var diag_1 = __nccwpck_require__(6081); -var baggage_impl_1 = __nccwpck_require__(6891); -var symbol_1 = __nccwpck_require__(1321); +var diag_1 = __nccwpck_require__(11877); +var baggage_impl_1 = __nccwpck_require__(84811); +var symbol_1 = __nccwpck_require__(23542); var diag = diag_1.DiagAPI.instance(); /** * Create a new Baggage with optional entries @@ -49590,7 +50011,7 @@ exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString; /***/ }), -/***/ 884: +/***/ 1109: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -49615,7 +50036,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 1444: +/***/ 14447: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -49640,7 +50061,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 8471: +/***/ 92358: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -49650,7 +50071,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 851: +/***/ 54118: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -49677,7 +50098,7 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopContextManager = void 0; -var context_1 = __nccwpck_require__(4456); +var context_1 = __nccwpck_require__(78242); var NoopContextManager = /** @class */ (function () { function NoopContextManager() { } @@ -49707,7 +50128,7 @@ exports.NoopContextManager = NoopContextManager; /***/ }), -/***/ 4456: +/***/ 78242: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -49770,7 +50191,7 @@ exports.ROOT_CONTEXT = new BaseContext(); /***/ }), -/***/ 147: +/***/ 36504: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -49795,7 +50216,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 8240: +/***/ 17978: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -49817,7 +50238,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DiagComponentLogger = void 0; -var global_utils_1 = __nccwpck_require__(954); +var 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. @@ -49882,7 +50303,7 @@ function logProxy(funcName, namespace, args) { /***/ }), -/***/ 4172: +/***/ 3041: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -49951,7 +50372,7 @@ exports.DiagConsoleLogger = DiagConsoleLogger; /***/ }), -/***/ 6836: +/***/ 31634: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -49982,13 +50403,13 @@ 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__(4172), exports); -__exportStar(__nccwpck_require__(5581), exports); +__exportStar(__nccwpck_require__(3041), exports); +__exportStar(__nccwpck_require__(78077), exports); //# sourceMappingURL=index.js.map /***/ }), -/***/ 2609: +/***/ 99639: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -50010,7 +50431,7 @@ __exportStar(__nccwpck_require__(5581), exports); */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createLogLevelDiagLogger = void 0; -var types_1 = __nccwpck_require__(5581); +var types_1 = __nccwpck_require__(78077); function createLogLevelDiagLogger(maxLevel, logger) { if (maxLevel < types_1.DiagLogLevel.NONE) { maxLevel = types_1.DiagLogLevel.NONE; @@ -50040,7 +50461,7 @@ exports.createLogLevelDiagLogger = createLogLevelDiagLogger; /***/ }), -/***/ 5581: +/***/ 78077: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -50091,7 +50512,7 @@ var DiagLogLevel; /***/ }), -/***/ 5653: +/***/ 65163: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -50123,52 +50544,52 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.diag = exports.propagation = exports.trace = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.createTraceState = exports.baggageEntryMetadataFromString = void 0; -__exportStar(__nccwpck_require__(4761), exports); -var utils_1 = __nccwpck_require__(6266); +__exportStar(__nccwpck_require__(91508), exports); +var utils_1 = __nccwpck_require__(28136); Object.defineProperty(exports, "baggageEntryMetadataFromString", ({ enumerable: true, get: function () { return utils_1.baggageEntryMetadataFromString; } })); -__exportStar(__nccwpck_require__(1444), exports); -__exportStar(__nccwpck_require__(8471), exports); -__exportStar(__nccwpck_require__(884), exports); -__exportStar(__nccwpck_require__(6836), exports); -__exportStar(__nccwpck_require__(3600), exports); -__exportStar(__nccwpck_require__(2733), exports); -__exportStar(__nccwpck_require__(122), exports); -__exportStar(__nccwpck_require__(8668), exports); -__exportStar(__nccwpck_require__(1595), exports); -__exportStar(__nccwpck_require__(3218), exports); -__exportStar(__nccwpck_require__(9311), exports); -__exportStar(__nccwpck_require__(9549), exports); -__exportStar(__nccwpck_require__(341), exports); -__exportStar(__nccwpck_require__(7841), exports); -__exportStar(__nccwpck_require__(74), exports); -__exportStar(__nccwpck_require__(1998), exports); -__exportStar(__nccwpck_require__(9327), exports); -__exportStar(__nccwpck_require__(7990), exports); -var utils_2 = __nccwpck_require__(5434); +__exportStar(__nccwpck_require__(14447), exports); +__exportStar(__nccwpck_require__(92358), exports); +__exportStar(__nccwpck_require__(1109), exports); +__exportStar(__nccwpck_require__(31634), exports); +__exportStar(__nccwpck_require__(80865), exports); +__exportStar(__nccwpck_require__(57492), exports); +__exportStar(__nccwpck_require__(44023), exports); +__exportStar(__nccwpck_require__(43503), exports); +__exportStar(__nccwpck_require__(2285), exports); +__exportStar(__nccwpck_require__(19671), exports); +__exportStar(__nccwpck_require__(33209), exports); +__exportStar(__nccwpck_require__(15769), exports); +__exportStar(__nccwpck_require__(31424), exports); +__exportStar(__nccwpck_require__(4416), exports); +__exportStar(__nccwpck_require__(25094), exports); +__exportStar(__nccwpck_require__(48845), exports); +__exportStar(__nccwpck_require__(26905), exports); +__exportStar(__nccwpck_require__(88384), exports); +var utils_2 = __nccwpck_require__(32615); Object.defineProperty(exports, "createTraceState", ({ enumerable: true, get: function () { return utils_2.createTraceState; } })); -__exportStar(__nccwpck_require__(524), exports); -__exportStar(__nccwpck_require__(1339), exports); -__exportStar(__nccwpck_require__(5904), exports); -var spancontext_utils_1 = __nccwpck_require__(9741); +__exportStar(__nccwpck_require__(30891), exports); +__exportStar(__nccwpck_require__(33168), exports); +__exportStar(__nccwpck_require__(91823), exports); +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__(4881); +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; } })); -__exportStar(__nccwpck_require__(4456), exports); -__exportStar(__nccwpck_require__(147), exports); -var context_1 = __nccwpck_require__(8222); +__exportStar(__nccwpck_require__(78242), exports); +__exportStar(__nccwpck_require__(36504), exports); +var context_1 = __nccwpck_require__(57171); /** Entrypoint for context API */ exports.context = context_1.ContextAPI.getInstance(); -var trace_1 = __nccwpck_require__(4153); +var trace_1 = __nccwpck_require__(81539); /** Entrypoint for trace API */ exports.trace = trace_1.TraceAPI.getInstance(); -var propagation_1 = __nccwpck_require__(7218); +var propagation_1 = __nccwpck_require__(89909); /** Entrypoint for propagation API */ exports.propagation = propagation_1.PropagationAPI.getInstance(); -var diag_1 = __nccwpck_require__(6081); +var diag_1 = __nccwpck_require__(11877); /** * Entrypoint for Diag API. * Defines Diagnostic handler used for internal diagnostic logging operations. @@ -50186,7 +50607,7 @@ exports["default"] = { /***/ }), -/***/ 954: +/***/ 85135: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -50208,9 +50629,9 @@ exports["default"] = { */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.unregisterGlobal = exports.getGlobal = exports.registerGlobal = void 0; -var platform_1 = __nccwpck_require__(9888); -var version_1 = __nccwpck_require__(5047); -var semver_1 = __nccwpck_require__(6629); +var platform_1 = __nccwpck_require__(99957); +var version_1 = __nccwpck_require__(98996); +var semver_1 = __nccwpck_require__(81522); var major = version_1.VERSION.split('.')[0]; var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("opentelemetry.js.api." + major); var _global = platform_1._globalThis; @@ -50258,7 +50679,7 @@ exports.unregisterGlobal = unregisterGlobal; /***/ }), -/***/ 6629: +/***/ 81522: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -50280,7 +50701,7 @@ exports.unregisterGlobal = unregisterGlobal; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isCompatible = exports._makeCompatibilityCheck = void 0; -var version_1 = __nccwpck_require__(5047); +var version_1 = __nccwpck_require__(98996); var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; /** * Create a function to test an API version to see if it is compatible with the provided ownVersion. @@ -50387,7 +50808,7 @@ exports.isCompatible = _makeCompatibilityCheck(version_1.VERSION); /***/ }), -/***/ 9888: +/***/ 99957: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -50418,12 +50839,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__(5478), exports); +__exportStar(__nccwpck_require__(87200), exports); //# sourceMappingURL=index.js.map /***/ }), -/***/ 2730: +/***/ 89406: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -50452,7 +50873,7 @@ exports._globalThis = typeof globalThis === 'object' ? globalThis : global; /***/ }), -/***/ 5478: +/***/ 87200: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -50483,12 +50904,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__(2730), exports); +__exportStar(__nccwpck_require__(89406), exports); //# sourceMappingURL=index.js.map /***/ }), -/***/ 4002: +/***/ 72368: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -50532,7 +50953,7 @@ exports.NoopTextMapPropagator = NoopTextMapPropagator; /***/ }), -/***/ 3600: +/***/ 80865: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -50580,7 +51001,7 @@ exports.defaultTextMapSetter = { /***/ }), -/***/ 9807: +/***/ 81462: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -50602,7 +51023,7 @@ exports.defaultTextMapSetter = { */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NonRecordingSpan = void 0; -var invalid_span_constants_1 = __nccwpck_require__(4881); +var 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 @@ -50652,7 +51073,7 @@ exports.NonRecordingSpan = NonRecordingSpan; /***/ }), -/***/ 3722: +/***/ 17606: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -50674,10 +51095,10 @@ exports.NonRecordingSpan = NonRecordingSpan; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopTracer = void 0; -var context_1 = __nccwpck_require__(8222); -var context_utils_1 = __nccwpck_require__(3074); -var NonRecordingSpan_1 = __nccwpck_require__(9807); -var spancontext_utils_1 = __nccwpck_require__(9741); +var context_1 = __nccwpck_require__(57171); +var context_utils_1 = __nccwpck_require__(23326); +var NonRecordingSpan_1 = __nccwpck_require__(81462); +var spancontext_utils_1 = __nccwpck_require__(49745); var context = context_1.ContextAPI.getInstance(); /** * No-op implementations of {@link Tracer}. @@ -50737,7 +51158,7 @@ function isSpanContext(spanContext) { /***/ }), -/***/ 2282: +/***/ 23259: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -50759,7 +51180,7 @@ function isSpanContext(spanContext) { */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopTracerProvider = void 0; -var NoopTracer_1 = __nccwpck_require__(3722); +var NoopTracer_1 = __nccwpck_require__(17606); /** * An implementation of the {@link TracerProvider} which returns an impotent * Tracer for all calls to `getTracer`. @@ -50779,7 +51200,7 @@ exports.NoopTracerProvider = NoopTracerProvider; /***/ }), -/***/ 8668: +/***/ 43503: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -50801,7 +51222,7 @@ exports.NoopTracerProvider = NoopTracerProvider; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProxyTracer = void 0; -var NoopTracer_1 = __nccwpck_require__(3722); +var NoopTracer_1 = __nccwpck_require__(17606); var NOOP_TRACER = new NoopTracer_1.NoopTracer(); /** * Proxy tracer provided by the proxy tracer provider @@ -50842,7 +51263,7 @@ exports.ProxyTracer = ProxyTracer; /***/ }), -/***/ 1595: +/***/ 2285: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -50864,8 +51285,8 @@ exports.ProxyTracer = ProxyTracer; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProxyTracerProvider = void 0; -var ProxyTracer_1 = __nccwpck_require__(8668); -var NoopTracerProvider_1 = __nccwpck_require__(2282); +var ProxyTracer_1 = __nccwpck_require__(43503); +var NoopTracerProvider_1 = __nccwpck_require__(23259); var NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider(); /** * Tracer provider which provides {@link ProxyTracer}s. @@ -50906,7 +51327,7 @@ exports.ProxyTracerProvider = ProxyTracerProvider; /***/ }), -/***/ 3218: +/***/ 19671: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -50931,7 +51352,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 9311: +/***/ 33209: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -50979,7 +51400,7 @@ var SamplingDecision; /***/ }), -/***/ 74: +/***/ 25094: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51004,7 +51425,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 2733: +/***/ 57492: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51029,7 +51450,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 3074: +/***/ 23326: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -51051,8 +51472,8 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getSpan = void 0; -var context_1 = __nccwpck_require__(4456); -var NonRecordingSpan_1 = __nccwpck_require__(9807); +var context_1 = __nccwpck_require__(78242); +var NonRecordingSpan_1 = __nccwpck_require__(81462); /** * span key */ @@ -51110,7 +51531,7 @@ exports.getSpanContext = getSpanContext; /***/ }), -/***/ 9812: +/***/ 62110: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -51132,7 +51553,7 @@ exports.getSpanContext = getSpanContext; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TraceStateImpl = void 0; -var tracestate_validators_1 = __nccwpck_require__(5600); +var tracestate_validators_1 = __nccwpck_require__(54864); var MAX_TRACE_STATE_ITEMS = 32; var MAX_TRACE_STATE_LEN = 512; var LIST_MEMBERS_SEPARATOR = ','; @@ -51222,7 +51643,7 @@ exports.TraceStateImpl = TraceStateImpl; /***/ }), -/***/ 5600: +/***/ 54864: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51275,7 +51696,7 @@ exports.validateValue = validateValue; /***/ }), -/***/ 5434: +/***/ 32615: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -51297,7 +51718,7 @@ exports.validateValue = validateValue; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createTraceState = void 0; -var tracestate_impl_1 = __nccwpck_require__(9812); +var tracestate_impl_1 = __nccwpck_require__(62110); function createTraceState(rawTraceState) { return new tracestate_impl_1.TraceStateImpl(rawTraceState); } @@ -51306,7 +51727,7 @@ exports.createTraceState = createTraceState; /***/ }), -/***/ 4881: +/***/ 91760: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -51328,7 +51749,7 @@ exports.createTraceState = createTraceState; */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0; -var trace_flags_1 = __nccwpck_require__(9327); +var trace_flags_1 = __nccwpck_require__(26905); exports.INVALID_SPANID = '0000000000000000'; exports.INVALID_TRACEID = '00000000000000000000000000000000'; exports.INVALID_SPAN_CONTEXT = { @@ -51340,7 +51761,7 @@ exports.INVALID_SPAN_CONTEXT = { /***/ }), -/***/ 122: +/***/ 44023: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51365,7 +51786,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 7841: +/***/ 4416: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51390,7 +51811,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 9549: +/***/ 15769: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51415,7 +51836,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 341: +/***/ 31424: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51468,7 +51889,7 @@ var SpanKind; /***/ }), -/***/ 9741: +/***/ 49745: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -51490,8 +51911,8 @@ exports.wrapSpanContext = exports.isSpanContextValid = exports.isValidSpanId = e * See the License for the specific language governing permissions and * limitations under the License. */ -var invalid_span_constants_1 = __nccwpck_require__(4881); -var NonRecordingSpan_1 = __nccwpck_require__(9807); +var invalid_span_constants_1 = __nccwpck_require__(91760); +var NonRecordingSpan_1 = __nccwpck_require__(81462); var VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; var VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; function isValidTraceId(traceId) { @@ -51524,7 +51945,7 @@ exports.wrapSpanContext = wrapSpanContext; /***/ }), -/***/ 1998: +/***/ 48845: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51554,7 +51975,7 @@ var SpanStatusCode; /***/ }), -/***/ 9327: +/***/ 26905: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51587,7 +52008,7 @@ var TraceFlags; /***/ }), -/***/ 7990: +/***/ 88384: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51612,7 +52033,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 1339: +/***/ 33168: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51637,7 +52058,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 5904: +/***/ 91823: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51662,7 +52083,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 524: +/***/ 30891: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51687,7 +52108,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 5047: +/***/ 98996: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -51715,12860 +52136,70779 @@ exports.VERSION = '1.1.0'; /***/ }), -/***/ 1113: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 29912: +/***/ (function(__unused_webpack_module, exports) { -module.exports = -{ - parallel : __nccwpck_require__(1979), - serial : __nccwpck_require__(2457), - serialOrdered : __nccwpck_require__(8775) +"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.ClientStreamingCall = void 0; +/** + * A client streaming RPC call. This means that the clients sends 0, 1, or + * more messages to the server, and the server replies with exactly one + * message. + */ +class ClientStreamingCall { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.requests = request; + this.headers = headers; + this.response = response; + this.status = status; + this.trailers = trailers; + } + /** + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * Note that it may still be valid to send more request messages. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter(this, void 0, void 0, function* () { + let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + headers, + response, + status, + trailers + }; + }); + } +} +exports.ClientStreamingCall = ClientStreamingCall; /***/ }), -/***/ 7553: -/***/ ((module) => { - -// API -module.exports = abort; - -/** - * Aborts leftover active jobs - * - * @param {object} state - current state object - */ -function abort(state) -{ - Object.keys(state.jobs).forEach(clean.bind(state)); +/***/ 85702: +/***/ ((__unused_webpack_module, exports) => { - // reset leftover jobs - state.jobs = {}; -} +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Deferred = exports.DeferredState = void 0; +var DeferredState; +(function (DeferredState) { + DeferredState[DeferredState["PENDING"] = 0] = "PENDING"; + DeferredState[DeferredState["REJECTED"] = 1] = "REJECTED"; + DeferredState[DeferredState["RESOLVED"] = 2] = "RESOLVED"; +})(DeferredState = exports.DeferredState || (exports.DeferredState = {})); /** - * 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](); - } + * A deferred promise. This is a "controller" for a promise, which lets you + * pass a promise around and reject or resolve it from the outside. + * + * Warning: This class is to be used with care. Using it can make code very + * difficult to read. It is intended for use in library code that exposes + * promises, not for regular business logic. + */ +class Deferred { + /** + * @param preventUnhandledRejectionWarning - prevents the warning + * "Unhandled Promise rejection" by adding a noop rejection handler. + * Working with calls returned from the runtime-rpc package in an + * async function usually means awaiting one call property after + * the other. This means that the "status" is not being awaited when + * an earlier await for the "headers" is rejected. This causes the + * "unhandled promise reject" warning. A more correct behaviour for + * calls might be to become aware whether at least one of the + * promises is handled and swallow the rejection warning for the + * others. + */ + constructor(preventUnhandledRejectionWarning = true) { + this._state = DeferredState.PENDING; + this._promise = new Promise((resolve, reject) => { + this._resolve = resolve; + this._reject = reject; + }); + if (preventUnhandledRejectionWarning) { + this._promise.catch(_ => { }); + } + } + /** + * Get the current state of the promise. + */ + get state() { + return this._state; + } + /** + * Get the deferred promise. + */ + get promise() { + return this._promise; + } + /** + * Resolve the promise. Throws if the promise is already resolved or rejected. + */ + resolve(value) { + if (this.state !== DeferredState.PENDING) + throw new Error(`cannot resolve ${DeferredState[this.state].toLowerCase()}`); + this._resolve(value); + this._state = DeferredState.RESOLVED; + } + /** + * Reject the promise. Throws if the promise is already resolved or rejected. + */ + reject(reason) { + if (this.state !== DeferredState.PENDING) + throw new Error(`cannot reject ${DeferredState[this.state].toLowerCase()}`); + this._reject(reason); + this._state = DeferredState.REJECTED; + } + /** + * Resolve the promise. Ignore if not pending. + */ + resolvePending(val) { + if (this._state === DeferredState.PENDING) + this.resolve(val); + } + /** + * Reject the promise. Ignore if not pending. + */ + rejectPending(reason) { + if (this._state === DeferredState.PENDING) + this.reject(reason); + } } +exports.Deferred = Deferred; /***/ }), -/***/ 3862: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var defer = __nccwpck_require__(1418); +/***/ 17042: +/***/ (function(__unused_webpack_module, exports) { -// API -module.exports = async; +"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.DuplexStreamingCall = void 0; /** - * Runs provided callback asynchronously - * even if callback itself is not - * - * @param {function} callback - callback to invoke - * @returns {function} - augmented callback + * A duplex streaming RPC call. This means that the clients sends an + * arbitrary amount of messages to the server, while at the same time, + * the server sends an arbitrary amount of messages to the client. */ -function async(callback) -{ - var isAsync = false; - - // check if async happened - defer(function() { isAsync = true; }); - - return function async_callback(err, result) - { - if (isAsync) - { - callback(err, result); +class DuplexStreamingCall { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.requests = request; + this.headers = headers; + this.responses = response; + this.status = status; + this.trailers = trailers; } - else - { - defer(function nextTick_callback() - { - callback(err, result); - }); + /** + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * Note that it may still be valid to send more request messages. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter(this, void 0, void 0, function* () { + let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + headers, + status, + trailers, + }; + }); } - }; } +exports.DuplexStreamingCall = DuplexStreamingCall; /***/ }), -/***/ 1418: -/***/ ((module) => { - -module.exports = defer; +/***/ 60012: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * 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 - ); +"use strict"; - if (nextTick) - { - nextTick(fn); - } - else - { - setTimeout(fn, 0); - } -} +// Public API of the rpc runtime. +// 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__(14107); +Object.defineProperty(exports, "ServiceType", ({ enumerable: true, get: function () { return service_type_1.ServiceType; } })); +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__(63159); +Object.defineProperty(exports, "RpcError", ({ enumerable: true, get: function () { return rpc_error_1.RpcError; } })); +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__(76637); +Object.defineProperty(exports, "RpcOutputStreamController", ({ enumerable: true, get: function () { return rpc_output_stream_1.RpcOutputStreamController; } })); +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__(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__(17042); +Object.defineProperty(exports, "DuplexStreamingCall", ({ enumerable: true, get: function () { return duplex_streaming_call_1.DuplexStreamingCall; } })); +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__(30066); +Object.defineProperty(exports, "ServerStreamingCall", ({ enumerable: true, get: function () { return server_streaming_call_1.ServerStreamingCall; } })); +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__(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__(25320); +Object.defineProperty(exports, "ServerCallContextController", ({ enumerable: true, get: function () { return server_call_context_1.ServerCallContextController; } })); /***/ }), -/***/ 9851: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var async = __nccwpck_require__(3862) - , abort = __nccwpck_require__(7553) - ; +/***/ 44331: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// API -module.exports = iterate; +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.readServiceOption = exports.readMethodOption = exports.readMethodOptions = exports.normalizeMethodInfo = void 0; +const runtime_1 = __nccwpck_require__(4061); /** - * Iterates over each job object + * Turns PartialMethodInfo into MethodInfo. + */ +function normalizeMethodInfo(method, service) { + var _a, _b, _c; + let m = method; + m.service = service; + m.localName = (_a = m.localName) !== null && _a !== void 0 ? _a : runtime_1.lowerCamelCase(m.name); + // noinspection PointlessBooleanExpressionJS + m.serverStreaming = !!m.serverStreaming; + // noinspection PointlessBooleanExpressionJS + m.clientStreaming = !!m.clientStreaming; + m.options = (_b = m.options) !== null && _b !== void 0 ? _b : {}; + m.idempotency = (_c = m.idempotency) !== null && _c !== void 0 ? _c : undefined; + return m; +} +exports.normalizeMethodInfo = normalizeMethodInfo; +/** + * Read custom method options from a generated service client. * - * @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 + * @deprecated use readMethodOption() */ -function iterate(list, iterator, state, callback) -{ - // store current index - var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; - - 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 (error) - { - // don't process rest of the results - // stop still active jobs - // and reset the list - abort(state); +function readMethodOptions(service, methodName, extensionName, extensionType) { + var _a; + const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; + return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : undefined; +} +exports.readMethodOptions = readMethodOptions; +function readMethodOption(service, methodName, extensionName, extensionType) { + var _a; + const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; + if (!options) { + return undefined; } - else - { - state.results[key] = output; + const optionVal = options[extensionName]; + if (optionVal === undefined) { + return optionVal; } - - // return salvaged results - callback(error, state.results); - }); + return extensionType ? extensionType.fromJson(optionVal) : optionVal; } - -/** - * 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; - - // 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; +exports.readMethodOption = readMethodOption; +function readServiceOption(service, extensionName, extensionType) { + const options = service.options; + if (!options) { + return undefined; + } + const optionVal = options[extensionName]; + if (optionVal === undefined) { + return optionVal; + } + return extensionType ? extensionType.fromJson(optionVal) : optionVal; } +exports.readServiceOption = readServiceOption; /***/ }), -/***/ 6474: -/***/ ((module) => { +/***/ 63159: +/***/ ((__unused_webpack_module, exports) => { -// API -module.exports = state; +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RpcError = void 0; /** - * 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 + * An error that occurred while calling a RPC method. */ -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 +class RpcError extends Error { + constructor(message, code = 'UNKNOWN', meta) { + super(message); + this.name = 'RpcError'; + // see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#example + Object.setPrototypeOf(this, new.target.prototype); + this.code = code; + this.meta = meta !== null && meta !== void 0 ? meta : {}; + } + toString() { + const l = [this.name + ': ' + this.message]; + if (this.code) { + l.push(''); + l.push('Code: ' + this.code); + } + if (this.serviceName && this.methodName) { + l.push('Method: ' + this.serviceName + '/' + this.methodName); + } + let m = Object.entries(this.meta); + if (m.length) { + l.push(''); + l.push('Meta:'); + for (let [k, v] of m) { + l.push(` ${k}: ${v}`); + } + } + return l.join('\n'); } - ; - - 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]); - }); - } - - return initState; } +exports.RpcError = RpcError; /***/ }), -/***/ 3701: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var abort = __nccwpck_require__(7553) - , async = __nccwpck_require__(3862) - ; +/***/ 51680: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// API -module.exports = terminator; +"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__(4061); /** - * Terminates jobs in the attached state context - * - * @this AsyncKitState# - * @param {function} callback - final callback to invoke after termination + * Creates a "stack" of of all interceptors specified in the given `RpcOptions`. + * Used by generated client implementations. + * @internal */ -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); +function stackIntercept(kind, transport, method, options, input) { + var _a, _b, _c, _d; + if (kind == "unary") { + let tail = (mtd, inp, opt) => transport.unary(mtd, inp, opt); + for (const curr of ((_a = options.interceptors) !== null && _a !== void 0 ? _a : []).filter(i => i.interceptUnary).reverse()) { + const next = tail; + tail = (mtd, inp, opt) => curr.interceptUnary(next, mtd, inp, opt); + } + return tail(method, input, options); + } + if (kind == "serverStreaming") { + let tail = (mtd, inp, opt) => transport.serverStreaming(mtd, inp, opt); + for (const curr of ((_b = options.interceptors) !== null && _b !== void 0 ? _b : []).filter(i => i.interceptServerStreaming).reverse()) { + const next = tail; + tail = (mtd, inp, opt) => curr.interceptServerStreaming(next, mtd, inp, opt); + } + return tail(method, input, options); + } + if (kind == "clientStreaming") { + let tail = (mtd, opt) => transport.clientStreaming(mtd, opt); + for (const curr of ((_c = options.interceptors) !== null && _c !== void 0 ? _c : []).filter(i => i.interceptClientStreaming).reverse()) { + const next = tail; + tail = (mtd, opt) => curr.interceptClientStreaming(next, mtd, opt); + } + return tail(method, options); + } + if (kind == "duplex") { + let tail = (mtd, opt) => transport.duplex(mtd, opt); + for (const curr of ((_d = options.interceptors) !== null && _d !== void 0 ? _d : []).filter(i => i.interceptDuplex).reverse()) { + const next = tail; + tail = (mtd, opt) => curr.interceptDuplex(next, mtd, opt); + } + return tail(method, options); + } + runtime_1.assertNever(kind); +} +exports.stackIntercept = stackIntercept; +/** + * @deprecated replaced by `stackIntercept()`, still here to support older generated code + */ +function stackUnaryInterceptors(transport, method, input, options) { + return stackIntercept("unary", transport, method, options, input); +} +exports.stackUnaryInterceptors = stackUnaryInterceptors; +/** + * @deprecated replaced by `stackIntercept()`, still here to support older generated code + */ +function stackServerStreamingInterceptors(transport, method, input, options) { + return stackIntercept("serverStreaming", transport, method, options, input); +} +exports.stackServerStreamingInterceptors = stackServerStreamingInterceptors; +/** + * @deprecated replaced by `stackIntercept()`, still here to support older generated code + */ +function stackClientStreamingInterceptors(transport, method, options) { + return stackIntercept("clientStreaming", transport, method, options); +} +exports.stackClientStreamingInterceptors = stackClientStreamingInterceptors; +/** + * @deprecated replaced by `stackIntercept()`, still here to support older generated code + */ +function stackDuplexStreamingInterceptors(transport, method, options) { + return stackIntercept("duplex", transport, method, options); } +exports.stackDuplexStreamingInterceptors = stackDuplexStreamingInterceptors; /***/ }), -/***/ 1979: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var iterate = __nccwpck_require__(9851) - , initState = __nccwpck_require__(6474) - , terminator = __nccwpck_require__(3701) - ; +/***/ 67386: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// Public API -module.exports = parallel; +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.mergeRpcOptions = void 0; +const runtime_1 = __nccwpck_require__(4061); /** - * 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); + * Merges custom RPC options with defaults. Returns a new instance and keeps + * the "defaults" and the "options" unmodified. + * + * Merges `RpcMetadata` "meta", overwriting values from "defaults" with + * values from "options". Does not append values to existing entries. + * + * Merges "jsonOptions", including "jsonOptions.typeRegistry", by creating + * a new array that contains types from "options.jsonOptions.typeRegistry" + * first, then types from "defaults.jsonOptions.typeRegistry". + * + * Merges "binaryOptions". + * + * Merges "interceptors" by creating a new array that contains interceptors + * from "defaults" first, then interceptors from "options". + * + * Works with objects that extend `RpcOptions`, but only if the added + * properties are of type Date, primitive like string, boolean, or Array + * of primitives. If you have other property types, you have to merge them + * yourself. + */ +function mergeRpcOptions(defaults, options) { + if (!options) + return defaults; + let o = {}; + copy(defaults, o); + copy(options, o); + for (let key of Object.keys(options)) { + let val = options[key]; + switch (key) { + case "jsonOptions": + o.jsonOptions = runtime_1.mergeJsonOptions(defaults.jsonOptions, o.jsonOptions); + break; + case "binaryOptions": + o.binaryOptions = runtime_1.mergeBinaryOptions(defaults.binaryOptions, o.binaryOptions); + break; + case "meta": + o.meta = {}; + copy(defaults.meta, o.meta); + copy(options.meta, o.meta); + break; + case "interceptors": + o.interceptors = defaults.interceptors ? defaults.interceptors.concat(val) : val.concat(); + break; + } + } + return o; +} +exports.mergeRpcOptions = mergeRpcOptions; +function copy(a, into) { + if (!a) return; - } - }); - - state.index++; - } - - return terminator.bind(state, callback); + let c = into; + for (let [k, v] of Object.entries(a)) { + if (v instanceof Date) + c[k] = new Date(v.getTime()); + else if (Array.isArray(v)) + c[k] = v.concat(); + else + c[k] = v; + } } /***/ }), -/***/ 2457: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var serialOrdered = __nccwpck_require__(8775); +/***/ 76637: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// Public API -module.exports = serial; +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RpcOutputStreamController = void 0; +const deferred_1 = __nccwpck_require__(85702); +const runtime_1 = __nccwpck_require__(4061); /** - * 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 + * A `RpcOutputStream` that you control. */ -function serial(list, iterator, callback) -{ - return serialOrdered(list, iterator, null, callback); +class RpcOutputStreamController { + constructor() { + this._lis = { + nxt: [], + msg: [], + err: [], + cmp: [], + }; + this._closed = false; + } + // --- RpcOutputStream callback API + onNext(callback) { + return this.addLis(callback, this._lis.nxt); + } + onMessage(callback) { + return this.addLis(callback, this._lis.msg); + } + onError(callback) { + return this.addLis(callback, this._lis.err); + } + onComplete(callback) { + return this.addLis(callback, this._lis.cmp); + } + addLis(callback, list) { + list.push(callback); + return () => { + let i = list.indexOf(callback); + if (i >= 0) + list.splice(i, 1); + }; + } + // remove all listeners + clearLis() { + for (let l of Object.values(this._lis)) + l.splice(0, l.length); + } + // --- Controller API + /** + * Is this stream already closed by a completion or error? + */ + get closed() { + return this._closed !== false; + } + /** + * Emit message, close with error, or close successfully, but only one + * at a time. + * Can be used to wrap a stream by using the other stream's `onNext`. + */ + notifyNext(message, error, complete) { + runtime_1.assert((message ? 1 : 0) + (error ? 1 : 0) + (complete ? 1 : 0) <= 1, 'only one emission at a time'); + if (message) + this.notifyMessage(message); + if (error) + this.notifyError(error); + if (complete) + this.notifyComplete(); + } + /** + * Emits a new message. Throws if stream is closed. + * + * Triggers onNext and onMessage callbacks. + */ + notifyMessage(message) { + runtime_1.assert(!this.closed, 'stream is closed'); + this.pushIt({ value: message, done: false }); + this._lis.msg.forEach(l => l(message)); + this._lis.nxt.forEach(l => l(message, undefined, false)); + } + /** + * Closes the stream with an error. Throws if stream is closed. + * + * Triggers onNext and onError callbacks. + */ + notifyError(error) { + runtime_1.assert(!this.closed, 'stream is closed'); + this._closed = error; + this.pushIt(error); + this._lis.err.forEach(l => l(error)); + this._lis.nxt.forEach(l => l(undefined, error, false)); + this.clearLis(); + } + /** + * Closes the stream successfully. Throws if stream is closed. + * + * Triggers onNext and onComplete callbacks. + */ + notifyComplete() { + runtime_1.assert(!this.closed, 'stream is closed'); + this._closed = true; + this.pushIt({ value: null, done: true }); + this._lis.cmp.forEach(l => l()); + this._lis.nxt.forEach(l => l(undefined, undefined, true)); + this.clearLis(); + } + /** + * Creates an async iterator (that can be used with `for await {...}`) + * to consume the stream. + * + * Some things to note: + * - If an error occurs, the `for await` will throw it. + * - If an error occurred before the `for await` was started, `for await` + * will re-throw it. + * - If the stream is already complete, the `for await` will be empty. + * - If your `for await` consumes slower than the stream produces, + * for example because you are relaying messages in a slow operation, + * messages are queued. + */ + [Symbol.asyncIterator]() { + // init the iterator state, enabling pushIt() + if (!this._itState) { + this._itState = { q: [] }; + } + // if we are closed, we are definitely not receiving any more messages. + // but we can't let the iterator get stuck. we want to either: + // a) finish the new iterator immediately, because we are completed + // b) reject the new iterator, because we errored + if (this._closed === true) + this.pushIt({ value: null, done: true }); + else if (this._closed !== false) + this.pushIt(this._closed); + // the async iterator + return { + next: () => { + let state = this._itState; + runtime_1.assert(state, "bad state"); // if we don't have a state here, code is broken + // there should be no pending result. + // did the consumer call next() before we resolved our previous result promise? + runtime_1.assert(!state.p, "iterator contract broken"); + // did we produce faster than the iterator consumed? + // return the oldest result from the queue. + let first = state.q.shift(); + if (first) + return ("value" in first) ? Promise.resolve(first) : Promise.reject(first); + // we have no result ATM, but we promise one. + // as soon as we have a result, we must resolve promise. + state.p = new deferred_1.Deferred(); + return state.p.promise; + }, + }; + } + // "push" a new iterator result. + // this either resolves a pending promise, or enqueues the result. + pushIt(result) { + let state = this._itState; + if (!state) + return; + // is the consumer waiting for us? + if (state.p) { + // yes, consumer is waiting for this promise. + const p = state.p; + runtime_1.assert(p.state == deferred_1.DeferredState.PENDING, "iterator contract broken"); + // resolve the promise + ("value" in result) ? p.resolve(result) : p.reject(result); + // must cleanup, otherwise iterator.next() would pick it up again. + delete state.p; + } + else { + // we are producing faster than the iterator consumes. + // push result onto queue. + state.q.push(result); + } + } } +exports.RpcOutputStreamController = RpcOutputStreamController; /***/ }), -/***/ 8775: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var iterate = __nccwpck_require__(9851) - , initState = __nccwpck_require__(6474) - , terminator = __nccwpck_require__(3701) - ; +/***/ 25320: +/***/ ((__unused_webpack_module, exports) => { -// Public API -module.exports = serialOrdered; -// sorting helpers -module.exports.ascending = ascending; -module.exports.descending = descending; +"use strict"; -/** - * 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); - - iterate(list, iterator, state, function iteratorHandler(error, result) - { - if (error) - { - callback(error, result); - return; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ServerCallContextController = void 0; +class ServerCallContextController { + constructor(method, headers, deadline, sendResponseHeadersFn, defaultStatus = { code: 'OK', detail: '' }) { + this._cancelled = false; + this._listeners = []; + this.method = method; + this.headers = headers; + this.deadline = deadline; + this.trailers = {}; + this._sendRH = sendResponseHeadersFn; + this.status = defaultStatus; } - - state.index++; - - // are we there yet? - if (state.index < (state['keyedList'] || list).length) - { - iterate(list, iterator, state, iteratorHandler); - return; + /** + * Set the call cancelled. + * + * Invokes all callbacks registered with onCancel() and + * sets `cancelled = true`. + */ + notifyCancelled() { + if (!this._cancelled) { + this._cancelled = true; + for (let l of this._listeners) { + l(); + } + } + } + /** + * Send response headers. + */ + sendResponseHeaders(data) { + this._sendRH(data); + } + /** + * Is the call cancelled? + * + * When the client closes the connection before the server + * is done, the call is cancelled. + * + * If you want to cancel a request on the server, throw a + * RpcError with the CANCELLED status code. + */ + get cancelled() { + return this._cancelled; + } + /** + * Add a callback for cancellation. + */ + onCancel(callback) { + const l = this._listeners; + l.push(callback); + return () => { + let i = l.indexOf(callback); + if (i >= 0) + l.splice(i, 1); + }; } +} +exports.ServerCallContextController = ServerCallContextController; - // done here - callback(null, state.results); - }); - return terminator.bind(state, callback); -} +/***/ }), -/* - * -- Sort methods - */ +/***/ 30066: +/***/ (function(__unused_webpack_module, exports) { -/** - * 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; -} +"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.ServerStreamingCall = void 0; /** - * 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 + * A server streaming RPC call. The client provides exactly one input message + * but the server may respond with 0, 1, or more messages. */ -function descending(a, b) -{ - return -1 * ascending(a, b); +class ServerStreamingCall { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.request = request; + this.headers = headers; + this.responses = response; + this.status = status; + this.trailers = trailers; + } + /** + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * You should first setup some listeners to the `request` to + * see the actual messages the server replied with. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter(this, void 0, void 0, function* () { + let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + request: this.request, + headers, + status, + trailers, + }; + }); + } } +exports.ServerStreamingCall = ServerStreamingCall; /***/ }), -/***/ 4357: -/***/ ((module) => { +/***/ 14107: +/***/ ((__unused_webpack_module, 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); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ServiceType = void 0; +const reflection_info_1 = __nccwpck_require__(44331); +class ServiceType { + constructor(typeName, methods, options) { + this.typeName = typeName; + this.methods = methods.map(i => reflection_info_1.normalizeMethodInfo(i, this)); + this.options = options !== null && options !== void 0 ? options : {}; + } +} +exports.ServiceType = ServiceType; - var r = range(a, b, str); - return r && { - start: r[0], - end: r[1], - pre: str.slice(0, r[0]), - body: str.slice(r[0] + a.length, r[1]), - post: str.slice(r[1] + b.length) - }; -} +/***/ }), -function maybeMatch(reg, str) { - var m = str.match(reg); - return m ? m[0] : null; -} +/***/ 87008: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -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; +"use strict"; - if (ai >= 0 && bi > 0) { - if(a===b) { - return [ai, bi]; +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.TestTransport = void 0; +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. + */ +class TestTransport { + /** + * Initialize with mock data. Omitted fields have default value. + */ + constructor(data) { + /** + * Suppress warning / error about uncaught rejections of + * "status" and "trailers". + */ + this.suppressUncaughtRejections = true; + this.headerDelay = 10; + this.responseDelay = 50; + this.betweenResponseDelay = 10; + this.afterResponseDelay = 10; + this.data = data !== null && data !== void 0 ? data : {}; } - begs = []; - left = str.length; - - while (i >= 0 && !result) { - if (i == ai) { - begs.push(i); - ai = str.indexOf(a, i + 1); - } else if (begs.length == 1) { - result = [ begs.pop(), bi ]; - } else { - beg = begs.pop(); - if (beg < left) { - left = beg; - right = bi; + /** + * Sent message(s) during the last operation. + */ + get sentMessages() { + if (this.lastInput instanceof TestInputStream) { + return this.lastInput.sent; } - - bi = str.indexOf(b, i + 1); - } - - i = ai < bi && ai >= 0 ? ai : bi; + else if (typeof this.lastInput == "object") { + return [this.lastInput.single]; + } + return []; } - - if (begs.length) { - result = [ left, right ]; + /** + * Sending message(s) completed? + */ + get sendComplete() { + if (this.lastInput instanceof TestInputStream) { + return this.lastInput.completed; + } + else if (typeof this.lastInput == "object") { + return true; + } + return false; + } + // Creates a promise for response headers from the mock data. + promiseHeaders() { + var _a; + const headers = (_a = this.data.headers) !== null && _a !== void 0 ? _a : TestTransport.defaultHeaders; + return headers instanceof rpc_error_1.RpcError + ? Promise.reject(headers) + : Promise.resolve(headers); + } + // Creates a promise for a single, valid, message from the mock data. + promiseSingleResponse(method) { + if (this.data.response instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.response); + } + let r; + if (Array.isArray(this.data.response)) { + runtime_1.assert(this.data.response.length > 0); + r = this.data.response[0]; + } + else if (this.data.response !== undefined) { + r = this.data.response; + } + else { + r = method.O.create(); + } + runtime_1.assert(method.O.is(r)); + return Promise.resolve(r); + } + /** + * Pushes response messages from the mock data to the output stream. + * If an error response, status or trailers are mocked, the stream is + * closed with the respective error. + * Otherwise, stream is completed successfully. + * + * The returned promise resolves when the stream is closed. It should + * not reject. If it does, code is broken. + */ + streamResponses(method, stream, abort) { + return __awaiter(this, void 0, void 0, function* () { + // normalize "data.response" into an array of valid output messages + const messages = []; + if (this.data.response === undefined) { + messages.push(method.O.create()); + } + else if (Array.isArray(this.data.response)) { + for (let msg of this.data.response) { + runtime_1.assert(method.O.is(msg)); + messages.push(msg); + } + } + else if (!(this.data.response instanceof rpc_error_1.RpcError)) { + runtime_1.assert(method.O.is(this.data.response)); + messages.push(this.data.response); + } + // start the stream with an initial delay. + // if the request is cancelled, notify() error and exit. + try { + yield delay(this.responseDelay, abort)(undefined); + } + catch (error) { + stream.notifyError(error); + return; + } + // if error response was mocked, notify() error (stream is now closed with error) and exit. + if (this.data.response instanceof rpc_error_1.RpcError) { + stream.notifyError(this.data.response); + return; + } + // regular response messages were mocked. notify() them. + for (let msg of messages) { + stream.notifyMessage(msg); + // add a short delay between responses + // if the request is cancelled, notify() error and exit. + try { + yield delay(this.betweenResponseDelay, abort)(undefined); + } + catch (error) { + stream.notifyError(error); + return; + } + } + // error status was mocked, notify() error (stream is now closed with error) and exit. + if (this.data.status instanceof rpc_error_1.RpcError) { + stream.notifyError(this.data.status); + return; + } + // error trailers were mocked, notify() error (stream is now closed with error) and exit. + if (this.data.trailers instanceof rpc_error_1.RpcError) { + stream.notifyError(this.data.trailers); + return; + } + // stream completed successfully + stream.notifyComplete(); + }); + } + // Creates a promise for response status from the mock data. + promiseStatus() { + var _a; + const status = (_a = this.data.status) !== null && _a !== void 0 ? _a : TestTransport.defaultStatus; + return status instanceof rpc_error_1.RpcError + ? Promise.reject(status) + : Promise.resolve(status); + } + // Creates a promise for response trailers from the mock data. + promiseTrailers() { + var _a; + const trailers = (_a = this.data.trailers) !== null && _a !== void 0 ? _a : TestTransport.defaultTrailers; + return trailers instanceof rpc_error_1.RpcError + ? Promise.reject(trailers) + : Promise.resolve(trailers); + } + maybeSuppressUncaught(...promise) { + if (this.suppressUncaughtRejections) { + for (let p of promise) { + p.catch(() => { + }); + } + } + } + mergeOptions(options) { + return rpc_options_1.mergeRpcOptions({}, options); + } + unary(method, input, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders() + .then(delay(this.headerDelay, options.abort)), responsePromise = headersPromise + .catch(_ => { + }) + .then(delay(this.responseDelay, options.abort)) + .then(_ => this.promiseSingleResponse(method)), statusPromise = responsePromise + .catch(_ => { + }) + .then(delay(this.afterResponseDelay, options.abort)) + .then(_ => this.promiseStatus()), trailersPromise = responsePromise + .catch(_ => { + }) + .then(delay(this.afterResponseDelay, options.abort)) + .then(_ => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = { single: input }; + return new unary_call_1.UnaryCall(method, requestHeaders, input, headersPromise, responsePromise, statusPromise, trailersPromise); + } + serverStreaming(method, input, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders() + .then(delay(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise + .then(delay(this.responseDelay, options.abort)) + .catch(() => { + }) + .then(() => this.streamResponses(method, outputStream, options.abort)) + .then(delay(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise + .then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise + .then(() => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = { single: input }; + return new server_streaming_call_1.ServerStreamingCall(method, requestHeaders, input, headersPromise, outputStream, statusPromise, trailersPromise); + } + clientStreaming(method, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders() + .then(delay(this.headerDelay, options.abort)), responsePromise = headersPromise + .catch(_ => { + }) + .then(delay(this.responseDelay, options.abort)) + .then(_ => this.promiseSingleResponse(method)), statusPromise = responsePromise + .catch(_ => { + }) + .then(delay(this.afterResponseDelay, options.abort)) + .then(_ => this.promiseStatus()), trailersPromise = responsePromise + .catch(_ => { + }) + .then(delay(this.afterResponseDelay, options.abort)) + .then(_ => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = new TestInputStream(this.data, options.abort); + return new client_streaming_call_1.ClientStreamingCall(method, requestHeaders, this.lastInput, headersPromise, responsePromise, statusPromise, trailersPromise); + } + duplex(method, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders() + .then(delay(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise + .then(delay(this.responseDelay, options.abort)) + .catch(() => { + }) + .then(() => this.streamResponses(method, outputStream, options.abort)) + .then(delay(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise + .then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise + .then(() => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = new TestInputStream(this.data, options.abort); + return new duplex_streaming_call_1.DuplexStreamingCall(method, requestHeaders, this.lastInput, headersPromise, outputStream, statusPromise, trailersPromise); } - } - - return result; } - - -/***/ }), - -/***/ 3573: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var register = __nccwpck_require__(1882) -var addHook = __nccwpck_require__(7344) -var removeHook = __nccwpck_require__(2913) - -// bind with array of arguments: https://stackoverflow.com/a/21792913 -var bind = Function.bind -var bindable = bind.bind(bind) - -function bindApi (hook, state, name) { - var removeHookRef = bindable(removeHook, null).apply(null, name ? [state, name] : [state]) - hook.api = { remove: removeHookRef } - hook.remove = removeHookRef - - ;['before', 'error', 'after', 'wrap'].forEach(function (kind) { - var args = name ? [state, kind, name] : [state, kind] - hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args) - }) +exports.TestTransport = TestTransport; +TestTransport.defaultHeaders = { + responseHeader: "test" +}; +TestTransport.defaultStatus = { + code: "OK", detail: "all good" +}; +TestTransport.defaultTrailers = { + responseTrailer: "test" +}; +function delay(ms, abort) { + return (v) => new Promise((resolve, reject) => { + if (abort === null || abort === void 0 ? void 0 : abort.aborted) { + reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); + } + else { + const id = setTimeout(() => resolve(v), ms); + if (abort) { + abort.addEventListener("abort", ev => { + clearTimeout(id); + reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); + }); + } + } + }); } - -function HookSingular () { - var singularHookName = 'h' - var singularHookState = { - registry: {} - } - var singularHook = register.bind(null, singularHookState, singularHookName) - bindApi(singularHook, singularHookState, singularHookName) - return singularHook +class TestInputStream { + constructor(data, abort) { + this._completed = false; + this._sent = []; + this.data = data; + this.abort = abort; + } + get sent() { + return this._sent; + } + get completed() { + return this._completed; + } + send(message) { + if (this.data.inputMessage instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.inputMessage); + } + const delayMs = this.data.inputMessage === undefined + ? 10 + : this.data.inputMessage; + return Promise.resolve(undefined) + .then(() => { + this._sent.push(message); + }) + .then(delay(delayMs, this.abort)); + } + complete() { + if (this.data.inputComplete instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.inputComplete); + } + const delayMs = this.data.inputComplete === undefined + ? 10 + : this.data.inputComplete; + return Promise.resolve(undefined) + .then(() => { + this._completed = true; + }) + .then(delay(delayMs, this.abort)); + } } -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() -} +/***/ 84175: +/***/ (function(__unused_webpack_module, exports) { -Hook.Singular = HookSingular.bind() -Hook.Collection = HookCollection.bind() +"use strict"; -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 +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.UnaryCall = void 0; +/** + * A unary RPC call. Unary means there is exactly one input message and + * exactly one output message unless an error occurred. + */ +class UnaryCall { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.request = request; + this.headers = headers; + this.response = response; + this.status = status; + this.trailers = trailers; + } + /** + * If you are only interested in the final outcome of this call, + * you can await it to receive a `FinishedUnaryCall`. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter(this, void 0, void 0, function* () { + let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + request: this.request, + headers, + response, + status, + trailers + }; + }); + } +} +exports.UnaryCall = UnaryCall; /***/ }), -/***/ 7344: -/***/ ((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; - }); - }; - } +/***/ 54253: +/***/ ((__unused_webpack_module, exports) => { - if (kind === "error") { - hook = function (method, options) { - return Promise.resolve() - .then(method.bind(null, options)) - .catch(function (error) { - return orig(error, options); - }); - }; - } +"use strict"; - state.registry[name].push({ - hook: hook, - orig: orig, - }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.assertFloat32 = exports.assertUInt32 = exports.assertInt32 = exports.assertNever = exports.assert = void 0; +/** + * assert that condition is true or throw error (with message) + */ +function assert(condition, msg) { + if (!condition) { + throw new Error(msg); + } +} +exports.assert = assert; +/** + * assert that value cannot exist = type `never`. throw runtime error if it does. + */ +function assertNever(value, msg) { + throw new Error(msg !== null && msg !== void 0 ? msg : 'Unexpected object: ' + value); +} +exports.assertNever = assertNever; +const FLOAT32_MAX = 3.4028234663852886e+38, FLOAT32_MIN = -3.4028234663852886e+38, UINT32_MAX = 0xFFFFFFFF, INT32_MAX = 0X7FFFFFFF, INT32_MIN = -0X80000000; +function assertInt32(arg) { + if (typeof arg !== "number") + throw new Error('invalid int 32: ' + typeof arg); + if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN) + throw new Error('invalid int 32: ' + arg); +} +exports.assertInt32 = assertInt32; +function assertUInt32(arg) { + if (typeof arg !== "number") + throw new Error('invalid uint 32: ' + typeof arg); + if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0) + throw new Error('invalid uint 32: ' + arg); +} +exports.assertUInt32 = assertUInt32; +function assertFloat32(arg) { + if (typeof arg !== "number") + throw new Error('invalid float 32: ' + typeof arg); + if (!Number.isFinite(arg)) + return; + if (arg > FLOAT32_MAX || arg < FLOAT32_MIN) + throw new Error('invalid float 32: ' + arg); } +exports.assertFloat32 = assertFloat32; /***/ }), -/***/ 1882: -/***/ ((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 = {}; - } +/***/ 20196: +/***/ ((__unused_webpack_module, exports) => { - if (Array.isArray(name)) { - return name.reverse().reduce(function (callback, name) { - return register.bind(null, state, name, callback, options); - }, method)(); - } +"use strict"; - return Promise.resolve().then(function () { - if (!state.registry[name]) { - return method(options); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.base64encode = exports.base64decode = void 0; +// lookup table from base64 character to byte +let encTable = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); +// lookup table from base64 character *code* to byte because lookup by number is fast +let decTable = []; +for (let i = 0; i < encTable.length; i++) + decTable[encTable[i].charCodeAt(0)] = i; +// support base64url variants +decTable["-".charCodeAt(0)] = encTable.indexOf("+"); +decTable["_".charCodeAt(0)] = encTable.indexOf("/"); +/** + * Decodes a base64 string to a byte array. + * + * - ignores white-space, including line breaks and tabs + * - allows inner padding (can decode concatenated base64 strings) + * - does not require padding + * - understands base64url encoding: + * "-" instead of "+", + * "_" instead of "/", + * no padding + */ +function base64decode(base64Str) { + // estimate byte size, not accounting for inner padding and whitespace + let es = base64Str.length * 3 / 4; + // if (es % 3 !== 0) + // throw new Error('invalid base64 string'); + if (base64Str[base64Str.length - 2] == '=') + es -= 2; + else if (base64Str[base64Str.length - 1] == '=') + es -= 1; + let bytes = new Uint8Array(es), bytePos = 0, // position in byte array + groupPos = 0, // position in base64 group + b, // current byte + p = 0 // previous byte + ; + for (let i = 0; i < base64Str.length; i++) { + b = decTable[base64Str.charCodeAt(i)]; + if (b === undefined) { + // noinspection FallThroughInSwitchStatementJS + switch (base64Str[i]) { + case '=': + groupPos = 0; // reset state when padding found + case '\n': + case '\r': + case '\t': + case ' ': + continue; // skip white-space, and padding + default: + throw Error(`invalid base64 string.`); + } + } + switch (groupPos) { + case 0: + p = b; + groupPos = 1; + break; + case 1: + bytes[bytePos++] = p << 2 | (b & 48) >> 4; + p = b; + groupPos = 2; + break; + case 2: + bytes[bytePos++] = (p & 15) << 4 | (b & 60) >> 2; + p = b; + groupPos = 3; + break; + case 3: + bytes[bytePos++] = (p & 3) << 6 | b; + groupPos = 0; + break; + } } - - return state.registry[name].reduce(function (method, registered) { - return registered.hook.bind(null, method, options); - }, method)(); - }); + if (groupPos == 1) + throw Error(`invalid base64 string.`); + return bytes.subarray(0, bytePos); +} +exports.base64decode = base64decode; +/** + * Encodes a byte array to a base64 string. + * Adds padding at the end. + * Does not insert newlines. + */ +function base64encode(bytes) { + let base64 = '', groupPos = 0, // position in base64 group + b, // current byte + p = 0; // carry over from previous byte + for (let i = 0; i < bytes.length; i++) { + b = bytes[i]; + switch (groupPos) { + case 0: + base64 += encTable[b >> 2]; + p = (b & 3) << 4; + groupPos = 1; + break; + case 1: + base64 += encTable[p | b >> 4]; + p = (b & 15) << 2; + groupPos = 2; + break; + case 2: + base64 += encTable[p | b >> 6]; + base64 += encTable[b & 63]; + groupPos = 0; + break; + } + } + // padding required? + if (groupPos) { + base64 += encTable[p]; + base64 += '='; + if (groupPos == 1) + base64 += '='; + } + return base64; } +exports.base64encode = base64encode; /***/ }), -/***/ 2913: -/***/ ((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); +/***/ 84921: +/***/ ((__unused_webpack_module, exports) => { - if (index === -1) { - return; - } +"use strict"; - state.registry[name].splice(index, 1); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.WireType = exports.mergeBinaryOptions = exports.UnknownFieldHandler = void 0; +/** + * This handler implements the default behaviour for unknown fields. + * When reading data, unknown fields are stored on the message, in a + * symbol property. + * When writing data, the symbol property is queried and unknown fields + * are serialized into the output again. + */ +var UnknownFieldHandler; +(function (UnknownFieldHandler) { + /** + * The symbol used to store unknown fields for a message. + * The property must conform to `UnknownFieldContainer`. + */ + UnknownFieldHandler.symbol = Symbol.for("protobuf-ts/unknown"); + /** + * Store an unknown field during binary read directly on the message. + * This method is compatible with `BinaryReadOptions.readUnknownField`. + */ + UnknownFieldHandler.onRead = (typeName, message, fieldNo, wireType, data) => { + let container = is(message) ? message[UnknownFieldHandler.symbol] : message[UnknownFieldHandler.symbol] = []; + container.push({ no: fieldNo, wireType, data }); + }; + /** + * Write unknown fields stored for the message to the writer. + * This method is compatible with `BinaryWriteOptions.writeUnknownFields`. + */ + UnknownFieldHandler.onWrite = (typeName, message, writer) => { + for (let { no, wireType, data } of UnknownFieldHandler.list(message)) + writer.tag(no, wireType).raw(data); + }; + /** + * List unknown fields stored for the message. + * Note that there may be multiples fields with the same number. + */ + UnknownFieldHandler.list = (message, fieldNo) => { + if (is(message)) { + let all = message[UnknownFieldHandler.symbol]; + return fieldNo ? all.filter(uf => uf.no == fieldNo) : all; + } + return []; + }; + /** + * Returns the last unknown field by field number. + */ + UnknownFieldHandler.last = (message, fieldNo) => UnknownFieldHandler.list(message, fieldNo).slice(-1)[0]; + const is = (message) => message && Array.isArray(message[UnknownFieldHandler.symbol]); +})(UnknownFieldHandler = exports.UnknownFieldHandler || (exports.UnknownFieldHandler = {})); +/** + * Merges binary write or read options. Later values override earlier values. + */ +function mergeBinaryOptions(a, b) { + return Object.assign(Object.assign({}, a), b); } +exports.mergeBinaryOptions = mergeBinaryOptions; +/** + * Protobuf binary format wire types. + * + * A wire type provides just enough information to find the length of the + * following value. + * + * See https://developers.google.com/protocol-buffers/docs/encoding#structure + */ +var WireType; +(function (WireType) { + /** + * Used for int32, int64, uint32, uint64, sint32, sint64, bool, enum + */ + WireType[WireType["Varint"] = 0] = "Varint"; + /** + * Used for fixed64, sfixed64, double. + * Always 8 bytes with little-endian byte order. + */ + WireType[WireType["Bit64"] = 1] = "Bit64"; + /** + * Used for string, bytes, embedded messages, packed repeated fields + * + * Only repeated numeric types (types which use the varint, 32-bit, + * or 64-bit wire types) can be packed. In proto3, such fields are + * packed by default. + */ + WireType[WireType["LengthDelimited"] = 2] = "LengthDelimited"; + /** + * Used for groups + * @deprecated + */ + WireType[WireType["StartGroup"] = 3] = "StartGroup"; + /** + * Used for groups + * @deprecated + */ + WireType[WireType["EndGroup"] = 4] = "EndGroup"; + /** + * Used for fixed32, sfixed32, float. + * Always 4 bytes with little-endian byte order. + */ + WireType[WireType["Bit32"] = 5] = "Bit32"; +})(WireType = exports.WireType || (exports.WireType = {})); /***/ }), -/***/ 3164: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var concatMap = __nccwpck_require__(8150); -var balanced = __nccwpck_require__(4357); - -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'; +/***/ 65210: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function numeric(str) { - return parseInt(str, 10) == str - ? parseInt(str, 10) - : str.charCodeAt(0); -} +"use strict"; -function escapeBraces(str) { - return str.split('\\\\').join(escSlash) - .split('\\{').join(escOpen) - .split('\\}').join(escClose) - .split('\\,').join(escComma) - .split('\\.').join(escPeriod); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BinaryReader = exports.binaryReadOptions = void 0; +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), +}; +/** + * Make options for reading binary data form partial options. + */ +function binaryReadOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; } - -function unescapeBraces(str) { - return str.split(escSlash).join('\\') - .split(escOpen).join('{') - .split(escClose).join('}') - .split(escComma).join(',') - .split(escPeriod).join('.'); +exports.binaryReadOptions = binaryReadOptions; +class BinaryReader { + constructor(buf, textDecoder) { + this.varint64 = goog_varint_1.varint64read; // dirty cast for `this` + /** + * Read a `uint32` field, an unsigned 32 bit varint. + */ + this.uint32 = goog_varint_1.varint32read; // dirty cast for `this` and access to protected `buf` + this.buf = buf; + this.len = buf.length; + this.pos = 0; + this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength); + this.textDecoder = textDecoder !== null && textDecoder !== void 0 ? textDecoder : new TextDecoder("utf-8", { + fatal: true, + ignoreBOM: true, + }); + } + /** + * Reads a tag - field number and wire type. + */ + tag() { + let tag = this.uint32(), fieldNo = tag >>> 3, wireType = tag & 7; + if (fieldNo <= 0 || wireType < 0 || wireType > 5) + throw new Error("illegal tag: field no " + fieldNo + " wire type " + wireType); + return [fieldNo, wireType]; + } + /** + * Skip one element on the wire and return the skipped data. + * Supports WireType.StartGroup since v2.0.0-alpha.23. + */ + skip(wireType) { + let start = this.pos; + // noinspection FallThroughInSwitchStatementJS + switch (wireType) { + case binary_format_contract_1.WireType.Varint: + while (this.buf[this.pos++] & 0x80) { + // ignore + } + break; + case binary_format_contract_1.WireType.Bit64: + this.pos += 4; + case binary_format_contract_1.WireType.Bit32: + this.pos += 4; + break; + case binary_format_contract_1.WireType.LengthDelimited: + let len = this.uint32(); + this.pos += len; + break; + case binary_format_contract_1.WireType.StartGroup: + // From descriptor.proto: Group type is deprecated, not supported in proto3. + // But we must still be able to parse and treat as unknown. + let t; + while ((t = this.tag()[1]) !== binary_format_contract_1.WireType.EndGroup) { + this.skip(t); + } + break; + default: + throw new Error("cant skip wire type " + wireType); + } + this.assertBounds(); + return this.buf.subarray(start, this.pos); + } + /** + * Throws error if position in byte array is out of range. + */ + assertBounds() { + if (this.pos > this.len) + throw new RangeError("premature EOF"); + } + /** + * Read a `int32` field, a signed 32 bit varint. + */ + int32() { + return this.uint32() | 0; + } + /** + * Read a `sint32` field, a signed, zigzag-encoded 32-bit varint. + */ + sint32() { + let zze = this.uint32(); + // decode zigzag + return (zze >>> 1) ^ -(zze & 1); + } + /** + * Read a `int64` field, a signed 64-bit varint. + */ + int64() { + return new pb_long_1.PbLong(...this.varint64()); + } + /** + * Read a `uint64` field, an unsigned 64-bit varint. + */ + uint64() { + return new pb_long_1.PbULong(...this.varint64()); + } + /** + * Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint. + */ + sint64() { + let [lo, hi] = this.varint64(); + // decode zig zag + let s = -(lo & 1); + lo = ((lo >>> 1 | (hi & 1) << 31) ^ s); + hi = (hi >>> 1 ^ s); + return new pb_long_1.PbLong(lo, hi); + } + /** + * Read a `bool` field, a variant. + */ + bool() { + let [lo, hi] = this.varint64(); + return lo !== 0 || hi !== 0; + } + /** + * Read a `fixed32` field, an unsigned, fixed-length 32-bit integer. + */ + fixed32() { + return this.view.getUint32((this.pos += 4) - 4, true); + } + /** + * Read a `sfixed32` field, a signed, fixed-length 32-bit integer. + */ + sfixed32() { + return this.view.getInt32((this.pos += 4) - 4, true); + } + /** + * Read a `fixed64` field, an unsigned, fixed-length 64 bit integer. + */ + fixed64() { + return new pb_long_1.PbULong(this.sfixed32(), this.sfixed32()); + } + /** + * Read a `fixed64` field, a signed, fixed-length 64-bit integer. + */ + sfixed64() { + return new pb_long_1.PbLong(this.sfixed32(), this.sfixed32()); + } + /** + * Read a `float` field, 32-bit floating point number. + */ + float() { + return this.view.getFloat32((this.pos += 4) - 4, true); + } + /** + * Read a `double` field, a 64-bit floating point number. + */ + double() { + return this.view.getFloat64((this.pos += 8) - 8, true); + } + /** + * Read a `bytes` field, length-delimited arbitrary data. + */ + bytes() { + let len = this.uint32(); + let start = this.pos; + this.pos += len; + this.assertBounds(); + return this.buf.subarray(start, start + len); + } + /** + * Read a `string` field, length-delimited data converted to UTF-8 text. + */ + string() { + return this.textDecoder.decode(this.bytes()); + } } +exports.BinaryReader = BinaryReader; -// 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); - } +/***/ 44354: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - parts.push.apply(parts, p); +"use strict"; - return parts; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BinaryWriter = exports.binaryWriteOptions = void 0; +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(), +}; +/** + * Make options for writing binary data form partial options. + */ +function binaryWriteOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; +} +exports.binaryWriteOptions = binaryWriteOptions; +class BinaryWriter { + constructor(textEncoder) { + /** + * Previous fork states. + */ + this.stack = []; + this.textEncoder = textEncoder !== null && textEncoder !== void 0 ? textEncoder : new TextEncoder(); + this.chunks = []; + this.buf = []; + } + /** + * Return all bytes written and reset this writer. + */ + finish() { + this.chunks.push(new Uint8Array(this.buf)); // flush the buffer + let len = 0; + for (let i = 0; i < this.chunks.length; i++) + len += this.chunks[i].length; + let bytes = new Uint8Array(len); + let offset = 0; + for (let i = 0; i < this.chunks.length; i++) { + bytes.set(this.chunks[i], offset); + offset += this.chunks[i].length; + } + this.chunks = []; + return bytes; + } + /** + * Start a new fork for length-delimited data like a message + * or a packed repeated field. + * + * Must be joined later with `join()`. + */ + fork() { + this.stack.push({ chunks: this.chunks, buf: this.buf }); + this.chunks = []; + this.buf = []; + return this; + } + /** + * Join the last fork. Write its length and bytes, then + * return to the previous state. + */ + join() { + // get chunk of fork + let chunk = this.finish(); + // restore previous state + let prev = this.stack.pop(); + if (!prev) + throw new Error('invalid state, fork stack empty'); + this.chunks = prev.chunks; + this.buf = prev.buf; + // write length of chunk as varint + this.uint32(chunk.byteLength); + return this.raw(chunk); + } + /** + * Writes a tag (field number and wire type). + * + * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`. + * + * Generated code should compute the tag ahead of time and call `uint32()`. + */ + tag(fieldNo, type) { + return this.uint32((fieldNo << 3 | type) >>> 0); + } + /** + * Write a chunk of raw bytes. + */ + raw(chunk) { + if (this.buf.length) { + this.chunks.push(new Uint8Array(this.buf)); + this.buf = []; + } + this.chunks.push(chunk); + return this; + } + /** + * Write a `uint32` value, an unsigned 32 bit varint. + */ + uint32(value) { + assert_1.assertUInt32(value); + // write value as varint 32, inlined for speed + while (value > 0x7f) { + this.buf.push((value & 0x7f) | 0x80); + value = value >>> 7; + } + this.buf.push(value); + return this; + } + /** + * Write a `int32` value, a signed 32 bit varint. + */ + int32(value) { + assert_1.assertInt32(value); + goog_varint_1.varint32write(value, this.buf); + return this; + } + /** + * Write a `bool` value, a variant. + */ + bool(value) { + this.buf.push(value ? 1 : 0); + return this; + } + /** + * Write a `bytes` value, length-delimited arbitrary data. + */ + bytes(value) { + this.uint32(value.byteLength); // write length of chunk as varint + return this.raw(value); + } + /** + * Write a `string` value, length-delimited data converted to UTF-8 text. + */ + string(value) { + let chunk = this.textEncoder.encode(value); + this.uint32(chunk.byteLength); // write length of chunk as varint + return this.raw(chunk); + } + /** + * Write a `float` value, 32-bit floating point number. + */ + float(value) { + assert_1.assertFloat32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setFloat32(0, value, true); + return this.raw(chunk); + } + /** + * Write a `double` value, a 64-bit floating point number. + */ + double(value) { + let chunk = new Uint8Array(8); + new DataView(chunk.buffer).setFloat64(0, value, true); + return this.raw(chunk); + } + /** + * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer. + */ + fixed32(value) { + assert_1.assertUInt32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setUint32(0, value, true); + return this.raw(chunk); + } + /** + * Write a `sfixed32` value, a signed, fixed-length 32-bit integer. + */ + sfixed32(value) { + assert_1.assertInt32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setInt32(0, value, true); + return this.raw(chunk); + } + /** + * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint. + */ + sint32(value) { + assert_1.assertInt32(value); + // zigzag encode + value = ((value << 1) ^ (value >> 31)) >>> 0; + goog_varint_1.varint32write(value, this.buf); + return this; + } + /** + * Write a `fixed64` value, a signed, fixed-length 64-bit integer. + */ + sfixed64(value) { + let chunk = new Uint8Array(8); + let view = new DataView(chunk.buffer); + let long = pb_long_1.PbLong.from(value); + view.setInt32(0, long.lo, true); + view.setInt32(4, long.hi, true); + return this.raw(chunk); + } + /** + * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer. + */ + fixed64(value) { + let chunk = new Uint8Array(8); + let view = new DataView(chunk.buffer); + let long = pb_long_1.PbULong.from(value); + view.setInt32(0, long.lo, true); + view.setInt32(4, long.hi, true); + return this.raw(chunk); + } + /** + * Write a `int64` value, a signed 64-bit varint. + */ + int64(value) { + let long = pb_long_1.PbLong.from(value); + goog_varint_1.varint64write(long.lo, long.hi, this.buf); + return this; + } + /** + * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint. + */ + sint64(value) { + let long = pb_long_1.PbLong.from(value), + // zigzag encode + sign = long.hi >> 31, lo = (long.lo << 1) ^ sign, hi = ((long.hi << 1) | (long.lo >>> 31)) ^ sign; + goog_varint_1.varint64write(lo, hi, this.buf); + return this; + } + /** + * Write a `uint64` value, an unsigned 64-bit varint. + */ + uint64(value) { + let long = pb_long_1.PbULong.from(value); + goog_varint_1.varint64write(long.lo, long.hi, this.buf); + return this; + } } +exports.BinaryWriter = BinaryWriter; -function expandTop(str) { - if (!str) - return []; - // 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); -} +/***/ 20085: +/***/ ((__unused_webpack_module, exports) => { -function identity(e) { - return e; -} +"use strict"; -function embrace(str) { - return '{' + str + '}'; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.listEnumNumbers = exports.listEnumNames = exports.listEnumValues = exports.isEnumObject = void 0; +/** + * Is this a lookup object generated by Typescript, for a Typescript enum + * generated by protobuf-ts? + * + * - No `const enum` (enum must not be inlined, we need reverse mapping). + * - No string enum (we need int32 for protobuf). + * - Must have a value for 0 (otherwise, we would need to support custom default values). + */ +function isEnumObject(arg) { + if (typeof arg != 'object' || arg === null) { + return false; + } + if (!arg.hasOwnProperty(0)) { + return false; + } + for (let k of Object.keys(arg)) { + let num = parseInt(k); + if (!Number.isNaN(num)) { + // is there a name for the number? + let nam = arg[num]; + if (nam === undefined) + return false; + // does the name resolve back to the number? + if (arg[nam] !== num) + return false; + } + else { + // is there a number for the name? + let num = arg[k]; + if (num === undefined) + return false; + // is it a string enum? + if (typeof num !== 'number') + return false; + // do we know the number? + if (arg[num] === undefined) + return false; + } + } + return true; } -function isPadded(el) { - return /^-?0\d/.test(el); +exports.isEnumObject = isEnumObject; +/** + * Lists all values of a Typescript enum, as an array of objects with a "name" + * property and a "number" property. + * + * Note that it is possible that a number appears more than once, because it is + * possible to have aliases in an enum. + * + * Throws if the enum does not adhere to the rules of enums generated by + * protobuf-ts. See `isEnumObject()`. + */ +function listEnumValues(enumObject) { + if (!isEnumObject(enumObject)) + throw new Error("not a typescript enum object"); + let values = []; + for (let [name, number] of Object.entries(enumObject)) + if (typeof number == "number") + values.push({ name, number }); + return values; } - -function lte(i, y) { - return i <= y; +exports.listEnumValues = listEnumValues; +/** + * Lists the names of a Typescript enum. + * + * Throws if the enum does not adhere to the rules of enums generated by + * protobuf-ts. See `isEnumObject()`. + */ +function listEnumNames(enumObject) { + return listEnumValues(enumObject).map(val => val.name); } -function gte(i, y) { - return i >= y; +exports.listEnumNames = listEnumNames; +/** + * Lists the numbers of a Typescript enum. + * + * Throws if the enum does not adhere to the rules of enums generated by + * protobuf-ts. See `isEnumObject()`. + */ +function listEnumNumbers(enumObject) { + return listEnumValues(enumObject) + .map(val => val.number) + .filter((num, index, arr) => arr.indexOf(num) == index); } +exports.listEnumNumbers = listEnumNumbers; -function expand(str, isTop) { - var expansions = []; - - var m = balanced('{', '}', str); - if (!m || /\$$/.test(m.pre)) return [str]; - - 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 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; - }); - } - } - } - // at this point, n is the parts, and we know it's not a comma set - // with a single entry. +/***/ }), - // 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) - : ['']; +/***/ 30433: +/***/ ((__unused_webpack_module, exports) => { - var N; +"use strict"; - 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; +// Copyright 2008 Google Inc. All rights reserved. +// +// 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. +// +// Code generated by the Protocol Buffer compiler is owned by the owner +// of the input file used when generating it. This code is not +// standalone and requires a support library to be linked with it. This +// support library is itself covered by the above license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.varint32read = exports.varint32write = exports.int64toString = exports.int64fromString = exports.varint64write = exports.varint64read = void 0; +/** + * Read a 64 bit varint as two JS numbers. + * + * Returns tuple: + * [0]: low bits + * [0]: high bits + * + * Copyright 2008 Google Inc. All rights reserved. + * + * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L175 + */ +function varint64read() { + let lowBits = 0; + let highBits = 0; + for (let shift = 0; shift < 28; shift += 7) { + let b = this.buf[this.pos++]; + lowBits |= (b & 0x7F) << shift; + if ((b & 0x80) == 0) { + this.assertBounds(); + return [lowBits, highBits]; + } } - 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; - } + let middleByte = this.buf[this.pos++]; + // last four bits of the first 32 bit number + lowBits |= (middleByte & 0x0F) << 28; + // 3 upper bits are part of the next 32 bit number + highBits = (middleByte & 0x70) >> 4; + if ((middleByte & 0x80) == 0) { + this.assertBounds(); + return [lowBits, highBits]; + } + for (let shift = 3; shift <= 31; shift += 7) { + let b = this.buf[this.pos++]; + highBits |= (b & 0x7F) << shift; + if ((b & 0x80) == 0) { + this.assertBounds(); + return [lowBits, highBits]; } - } - 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); + throw new Error('invalid varint'); +} +exports.varint64read = varint64read; +/** + * Write a 64 bit varint, given as two JS numbers, to the given bytes array. + * + * Copyright 2008 Google Inc. All rights reserved. + * + * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/writer.js#L344 + */ +function varint64write(lo, hi, bytes) { + for (let i = 0; i < 28; i = i + 7) { + const shift = lo >>> i; + const hasNext = !((shift >>> 7) == 0 && hi == 0); + const byte = (hasNext ? shift | 0x80 : shift) & 0xFF; + bytes.push(byte); + if (!hasNext) { + return; + } } - } - - return expansions; + const splitBits = ((lo >>> 28) & 0x0F) | ((hi & 0x07) << 4); + const hasMoreBits = !((hi >> 3) == 0); + bytes.push((hasMoreBits ? splitBits | 0x80 : splitBits) & 0xFF); + if (!hasMoreBits) { + return; + } + for (let i = 3; i < 31; i = i + 7) { + const shift = hi >>> i; + const hasNext = !((shift >>> 7) == 0); + const byte = (hasNext ? shift | 0x80 : shift) & 0xFF; + bytes.push(byte); + if (!hasNext) { + return; + } + } + bytes.push((hi >>> 31) & 0x01); } - +exports.varint64write = varint64write; +// constants for binary math +const TWO_PWR_32_DBL = (1 << 16) * (1 << 16); +/** + * Parse decimal string of 64 bit integer value as two JS numbers. + * + * Returns tuple: + * [0]: minus sign? + * [1]: low bits + * [2]: high bits + * + * Copyright 2008 Google Inc. + */ +function int64fromString(dec) { + // Check for minus sign. + let minus = dec[0] == '-'; + if (minus) + dec = dec.slice(1); + // Work 6 decimal digits at a time, acting like we're converting base 1e6 + // digits to binary. This is safe to do with floating point math because + // Number.isSafeInteger(ALL_32_BITS * 1e6) == true. + const base = 1e6; + let lowBits = 0; + let highBits = 0; + function add1e6digit(begin, end) { + // Note: Number('') is 0. + const digit1e6 = Number(dec.slice(begin, end)); + highBits *= base; + lowBits = lowBits * base + digit1e6; + // Carry bits from lowBits to highBits + if (lowBits >= TWO_PWR_32_DBL) { + highBits = highBits + ((lowBits / TWO_PWR_32_DBL) | 0); + lowBits = lowBits % TWO_PWR_32_DBL; + } + } + add1e6digit(-24, -18); + add1e6digit(-18, -12); + add1e6digit(-12, -6); + add1e6digit(-6); + return [minus, lowBits, highBits]; +} +exports.int64fromString = int64fromString; +/** + * Format 64 bit integer value (as two JS numbers) to decimal string. + * + * Copyright 2008 Google Inc. + */ +function int64toString(bitsLow, bitsHigh) { + // Skip the expensive conversion if the number is small enough to use the + // built-in conversions. + if ((bitsHigh >>> 0) <= 0x1FFFFF) { + return '' + (TWO_PWR_32_DBL * bitsHigh + (bitsLow >>> 0)); + } + // What this code is doing is essentially converting the input number from + // base-2 to base-1e7, which allows us to represent the 64-bit range with + // only 3 (very large) digits. Those digits are then trivial to convert to + // a base-10 string. + // The magic numbers used here are - + // 2^24 = 16777216 = (1,6777216) in base-1e7. + // 2^48 = 281474976710656 = (2,8147497,6710656) in base-1e7. + // Split 32:32 representation into 16:24:24 representation so our + // intermediate digits don't overflow. + let low = bitsLow & 0xFFFFFF; + let mid = (((bitsLow >>> 24) | (bitsHigh << 8)) >>> 0) & 0xFFFFFF; + let high = (bitsHigh >> 16) & 0xFFFF; + // Assemble our three base-1e7 digits, ignoring carries. The maximum + // value in a digit at this step is representable as a 48-bit integer, which + // can be stored in a 64-bit floating point number. + let digitA = low + (mid * 6777216) + (high * 6710656); + let digitB = mid + (high * 8147497); + let digitC = (high * 2); + // Apply carries from A to B and from B to C. + let base = 10000000; + if (digitA >= base) { + digitB += Math.floor(digitA / base); + digitA %= base; + } + if (digitB >= base) { + digitC += Math.floor(digitB / base); + digitB %= base; + } + // Convert base-1e7 digits to base-10, with optional leading zeroes. + function decimalFrom1e7(digit1e7, needLeadingZeros) { + let partial = digit1e7 ? String(digit1e7) : ''; + if (needLeadingZeros) { + return '0000000'.slice(partial.length) + partial; + } + return partial; + } + return decimalFrom1e7(digitC, /*needLeadingZeros=*/ 0) + + decimalFrom1e7(digitB, /*needLeadingZeros=*/ digitC) + + // If the final 1e7 digit didn't need leading zeros, we would have + // returned via the trivial code path at the top. + decimalFrom1e7(digitA, /*needLeadingZeros=*/ 1); +} +exports.int64toString = int64toString; +/** + * Write a 32 bit varint, signed or unsigned. Same as `varint64write(0, value, bytes)` + * + * Copyright 2008 Google Inc. All rights reserved. + * + * See https://github.com/protocolbuffers/protobuf/blob/1b18833f4f2a2f681f4e4a25cdf3b0a43115ec26/js/binary/encoder.js#L144 + */ +function varint32write(value, bytes) { + if (value >= 0) { + // write value as varint 32 + while (value > 0x7f) { + bytes.push((value & 0x7f) | 0x80); + value = value >>> 7; + } + bytes.push(value); + } + else { + for (let i = 0; i < 9; i++) { + bytes.push(value & 127 | 128); + value = value >> 7; + } + bytes.push(1); + } +} +exports.varint32write = varint32write; +/** + * Read an unsigned 32 bit varint. + * + * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L220 + */ +function varint32read() { + let b = this.buf[this.pos++]; + let result = b & 0x7F; + if ((b & 0x80) == 0) { + this.assertBounds(); + return result; + } + b = this.buf[this.pos++]; + result |= (b & 0x7F) << 7; + if ((b & 0x80) == 0) { + this.assertBounds(); + return result; + } + b = this.buf[this.pos++]; + result |= (b & 0x7F) << 14; + if ((b & 0x80) == 0) { + this.assertBounds(); + return result; + } + b = this.buf[this.pos++]; + result |= (b & 0x7F) << 21; + if ((b & 0x80) == 0) { + this.assertBounds(); + return result; + } + // Extract only last 4 bits + b = this.buf[this.pos++]; + result |= (b & 0x0F) << 28; + for (let readBytes = 5; ((b & 0x80) !== 0) && readBytes < 10; readBytes++) + b = this.buf[this.pos++]; + if ((b & 0x80) != 0) + throw new Error('invalid varint'); + this.assertBounds(); + // Result can have 32 bits, convert it to unsigned + return result >>> 0; +} +exports.varint32read = varint32read; /***/ }), -/***/ 3086: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 4061: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var util = __nccwpck_require__(3837); -var Stream = (__nccwpck_require__(2781).Stream); -var DelayedStream = __nccwpck_require__(9640); +"use strict"; -module.exports = CombinedStream; -function CombinedStream() { - this.writable = false; - this.readable = true; - this.dataSize = 0; - this.maxDataSize = 2 * 1024 * 1024; - this.pauseStreams = true; +// Public API of the protobuf-ts runtime. +// 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 })); +// Convenience JSON typings and corresponding type guards +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__(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__(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__(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__(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__(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__(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__(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__(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__(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__(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; } })); +Object.defineProperty(exports, "normalizeFieldInfo", ({ enumerable: true, get: function () { return reflection_info_1.normalizeFieldInfo; } })); +Object.defineProperty(exports, "readFieldOptions", ({ enumerable: true, get: function () { return reflection_info_1.readFieldOptions; } })); +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__(20903); +Object.defineProperty(exports, "ReflectionTypeCheck", ({ enumerable: true, get: function () { return reflection_type_check_1.ReflectionTypeCheck; } })); +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__(74863); +Object.defineProperty(exports, "reflectionScalarDefault", ({ enumerable: true, get: function () { return reflection_scalar_default_1.reflectionScalarDefault; } })); +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__(39473); +Object.defineProperty(exports, "reflectionEquals", ({ enumerable: true, get: function () { return reflection_equals_1.reflectionEquals; } })); +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__(57170); +Object.defineProperty(exports, "ReflectionBinaryWriter", ({ enumerable: true, get: function () { return reflection_binary_writer_1.ReflectionBinaryWriter; } })); +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__(68980); +Object.defineProperty(exports, "ReflectionJsonWriter", ({ enumerable: true, get: function () { return reflection_json_writer_1.ReflectionJsonWriter; } })); +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__(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__(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__(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__(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; } })); +Object.defineProperty(exports, "assertUInt32", ({ enumerable: true, get: function () { return assert_1.assertUInt32; } })); +Object.defineProperty(exports, "assertFloat32", ({ enumerable: true, get: function () { return assert_1.assertFloat32; } })); - this._released = false; - this._streams = []; - this._currentStream = null; - this._insideLoop = false; - this._pendingNext = false; -} -util.inherits(CombinedStream, Stream); -CombinedStream.create = function(options) { - var combinedStream = new this(); +/***/ }), - options = options || {}; - for (var option in options) { - combinedStream[option] = options[option]; - } +/***/ 48139: +/***/ ((__unused_webpack_module, exports) => { - return combinedStream; -}; +"use strict"; -CombinedStream.isStreamLike = function(stream) { - return (typeof stream !== 'function') - && (typeof stream !== 'string') - && (typeof stream !== 'boolean') - && (typeof stream !== 'number') - && (!Buffer.isBuffer(stream)); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.mergeJsonOptions = exports.jsonWriteOptions = exports.jsonReadOptions = void 0; +const defaultsWrite = { + emitDefaultValues: false, + enumAsInteger: false, + useProtoFieldName: false, + prettySpaces: 0, +}, defaultsRead = { + ignoreUnknownFields: false, }; +/** + * Make options for reading JSON data from partial options. + */ +function jsonReadOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; +} +exports.jsonReadOptions = jsonReadOptions; +/** + * Make options for writing JSON data from partial options. + */ +function jsonWriteOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; +} +exports.jsonWriteOptions = jsonWriteOptions; +/** + * Merges JSON write or read options. Later values override earlier values. Type registries are merged. + */ +function mergeJsonOptions(a, b) { + var _a, _b; + let c = Object.assign(Object.assign({}, a), b); + c.typeRegistry = [...((_a = a === null || a === void 0 ? void 0 : a.typeRegistry) !== null && _a !== void 0 ? _a : []), ...((_b = b === null || b === void 0 ? void 0 : b.typeRegistry) !== null && _b !== void 0 ? _b : [])]; + return c; +} +exports.mergeJsonOptions = mergeJsonOptions; -CombinedStream.prototype.append = function(stream) { - var isStreamLike = CombinedStream.isStreamLike(stream); - 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; - } +/***/ }), - this._handleErrors(stream); +/***/ 70661: +/***/ ((__unused_webpack_module, exports) => { - if (this.pauseStreams) { - stream.pause(); +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isJsonObject = exports.typeofJsonValue = void 0; +/** + * Get the type of a JSON value. + * Distinguishes between array, null and object. + */ +function typeofJsonValue(value) { + let t = typeof value; + if (t == "object") { + if (Array.isArray(value)) + return "array"; + if (value === null) + return "null"; } - } + return t; +} +exports.typeofJsonValue = typeofJsonValue; +/** + * Is this a JSON object (instead of an array or null)? + */ +function isJsonObject(value) { + return value !== null && typeof value == "object" && !Array.isArray(value); +} +exports.isJsonObject = isJsonObject; - this._streams.push(stream); - return this; -}; -CombinedStream.prototype.pipe = function(dest, options) { - Stream.prototype.pipe.call(this, dest, options); - this.resume(); - return dest; -}; +/***/ }), -CombinedStream.prototype._getNext = function() { - this._currentStream = null; +/***/ 34772: +/***/ ((__unused_webpack_module, exports) => { - if (this._insideLoop) { - this._pendingNext = true; - return; // defer call - } +"use strict"; - this._insideLoop = true; - try { - do { - this._pendingNext = false; - this._realGetNext(); - } while (this._pendingNext); - } finally { - this._insideLoop = false; - } -}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.lowerCamelCase = void 0; +/** + * Converts snake_case to lowerCamelCase. + * + * Should behave like protoc: + * https://github.com/protocolbuffers/protobuf/blob/e8ae137c96444ea313485ed1118c5e43b2099cf1/src/google/protobuf/compiler/java/java_helpers.cc#L118 + */ +function lowerCamelCase(snakeCase) { + let capNext = false; + const sb = []; + for (let i = 0; i < snakeCase.length; i++) { + let next = snakeCase.charAt(i); + if (next == '_') { + capNext = true; + } + else if (/\d/.test(next)) { + sb.push(next); + capNext = true; + } + else if (capNext) { + sb.push(next.toUpperCase()); + capNext = false; + } + else if (i == 0) { + sb.push(next.toLowerCase()); + } + else { + sb.push(next); + } + } + return sb.join(''); +} +exports.lowerCamelCase = lowerCamelCase; -CombinedStream.prototype._realGetNext = function() { - var stream = this._streams.shift(); +/***/ }), - if (typeof stream == 'undefined') { - this.end(); - return; - } +/***/ 1682: +/***/ ((__unused_webpack_module, exports) => { - if (typeof stream !== 'function') { - this._pipeNext(stream); - return; - } +"use strict"; - 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'); -}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MESSAGE_TYPE = void 0; +/** + * The symbol used as a key on message objects to store the message type. + * + * Note that this is an experimental feature - it is here to stay, but + * implementation details may change without notice. + */ +exports.MESSAGE_TYPE = Symbol.for("protobuf-ts/message-type"); -CombinedStream.prototype._reset = function() { - this.writable = false; - this._streams = []; - this._currentStream = null; -}; -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)); -}; +/***/ 63664: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -CombinedStream.prototype._updateDataSize = function() { - this.dataSize = 0; +"use strict"; - var self = this; - this._streams.forEach(function(stream) { - if (!stream.dataSize) { - return; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MessageType = void 0; +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); +const baseDescriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})); +/** + * This standard message type provides reflection-based + * operations to work with a message. + */ +class MessageType { + constructor(name, fields, options) { + this.defaultCheckDepth = 16; + this.typeName = name; + this.fields = fields.map(reflection_info_1.normalizeFieldInfo); + this.options = options !== null && options !== void 0 ? options : {}; + this.messagePrototype = Object.create(null, Object.assign(Object.assign({}, baseDescriptors), { [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); + this.refBinReader = new reflection_binary_reader_1.ReflectionBinaryReader(this); + this.refBinWriter = new reflection_binary_writer_1.ReflectionBinaryWriter(this); } - - self.dataSize += stream.dataSize; - }); - - if (this._currentStream && this._currentStream.dataSize) { - this.dataSize += this._currentStream.dataSize; - } -}; - -CombinedStream.prototype._emitError = function(err) { - this._reset(); - this.emit('error', err); -}; - - -/***/ }), - -/***/ 8150: -/***/ ((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); + create(value) { + let message = reflection_create_1.reflectionCreate(this); + if (value !== undefined) { + reflection_merge_partial_1.reflectionMergePartial(this, message, value); + } + return message; + } + /** + * Clone the message. + * + * Unknown fields are discarded. + */ + clone(message) { + let copy = this.create(); + reflection_merge_partial_1.reflectionMergePartial(this, copy, message); + return copy; + } + /** + * Determines whether two message of the same type have the same field values. + * Checks for deep equality, traversing repeated fields, oneof groups, maps + * and messages recursively. + * Will also return true if both messages are `undefined`. + */ + equals(a, b) { + return reflection_equals_1.reflectionEquals(this, a, b); + } + /** + * Is the given value assignable to our message type + * and contains no [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? + */ + is(arg, depth = this.defaultCheckDepth) { + return this.refTypeCheck.is(arg, depth, false); + } + /** + * Is the given value assignable to our message type, + * regardless of [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? + */ + isAssignable(arg, depth = this.defaultCheckDepth) { + return this.refTypeCheck.is(arg, depth, true); + } + /** + * Copy partial data into the target message. + */ + mergePartial(target, source) { + reflection_merge_partial_1.reflectionMergePartial(this, target, source); + } + /** + * Create a new message from binary format. + */ + fromBinary(data, options) { + let opt = binary_reader_1.binaryReadOptions(options); + return this.internalBinaryRead(opt.readerFactory(data), data.byteLength, opt); + } + /** + * Read a new message from a JSON value. + */ + fromJson(json, options) { + return this.internalJsonRead(json, json_format_contract_1.jsonReadOptions(options)); + } + /** + * Read a new message from a JSON string. + * This is equivalent to `T.fromJson(JSON.parse(json))`. + */ + fromJsonString(json, options) { + let value = JSON.parse(json); + return this.fromJson(value, options); + } + /** + * Write the message to canonical JSON value. + */ + toJson(message, options) { + return this.internalJsonWrite(message, json_format_contract_1.jsonWriteOptions(options)); + } + /** + * Convert the message to canonical JSON string. + * This is equivalent to `JSON.stringify(T.toJson(t))` + */ + toJsonString(message, options) { + var _a; + let value = this.toJson(message, options); + return JSON.stringify(value, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0); + } + /** + * Write the message to binary format. + */ + toBinary(message, options) { + let opt = binary_writer_1.binaryWriteOptions(options); + return this.internalBinaryWrite(message, opt.writerFactory(), opt).finish(); + } + /** + * This is an internal method. If you just want to read a message from + * JSON, use `fromJson()` or `fromJsonString()`. + * + * Reads JSON value and merges the fields into the target + * according to protobuf rules. If the target is omitted, + * a new instance is created first. + */ + internalJsonRead(json, options, target) { + if (json !== null && typeof json == "object" && !Array.isArray(json)) { + let message = target !== null && target !== void 0 ? target : this.create(); + this.refJsonReader.read(json, message, options); + return message; + } + throw new Error(`Unable to parse message ${this.typeName} from JSON ${json_typings_1.typeofJsonValue(json)}.`); + } + /** + * This is an internal method. If you just want to write a message + * to JSON, use `toJson()` or `toJsonString(). + * + * Writes JSON value and returns it. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.write(message, options); + } + /** + * This is an internal method. If you just want to write a message + * in binary format, use `toBinary()`. + * + * Serializes the message in binary format and appends it to the given + * writer. Returns passed writer. + */ + internalBinaryWrite(message, writer, options) { + this.refBinWriter.write(message, writer, options); + return writer; + } + /** + * This is an internal method. If you just want to read a message from + * binary data, use `fromBinary()`. + * + * Reads data from binary format and merges the fields into + * the target according to protobuf rules. If the target is + * omitted, a new instance is created first. + */ + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(); + this.refBinReader.read(reader, message, options, length); + return message; } - return res; -}; - -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; - - -/***/ }), - -/***/ 9640: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var Stream = (__nccwpck_require__(2781).Stream); -var util = __nccwpck_require__(3837); - -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]; - } - - delayedStream.source = source; - - var realEmit = source.emit; - source.emit = function() { - delayedStream._handleEmit(arguments); - return realEmit.apply(source, arguments); - }; - - source.on('error', function() {}); - if (delayedStream.pauseStream) { - source.pause(); - } - - return delayedStream; -}; - -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); -}; - -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; - - this._bufferedEvents.forEach(function(args) { - this.emit.apply(this, args); - }.bind(this)); - this._bufferedEvents = []; -}; - -DelayedStream.prototype.pipe = function() { - var r = Stream.prototype.pipe.apply(this, arguments); - this.resume(); - return r; -}; - -DelayedStream.prototype._handleEmit = function(args) { - if (this._released) { - this.emit.apply(this, args); - return; - } - - if (args[0] === 'data') { - this.dataSize += args[1].length; - this._checkIfMaxDataSizeExceeded(); - } - - this._bufferedEvents.push(args); -}; - -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)); -}; +exports.MessageType = MessageType; /***/ }), -/***/ 6036: +/***/ 78531: /***/ ((__unused_webpack_module, exports) => { "use strict"; - Object.defineProperty(exports, "__esModule", ({ value: true })); - -class Deprecation extends Error { - constructor(message) { - super(message); // Maintains proper stack trace (only available on V8) - - /* istanbul ignore next */ - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); +exports.getSelectedOneofValue = exports.clearOneofValue = exports.setUnknownOneofValue = exports.setOneofValue = exports.getOneofValue = exports.isOneofGroup = void 0; +/** + * Is the given value a valid oneof group? + * + * We represent protobuf `oneof` as algebraic data types (ADT) in generated + * code. But when working with messages of unknown type, the ADT does not + * help us. + * + * This type guard checks if the given object adheres to the ADT rules, which + * are as follows: + * + * 1) Must be an object. + * + * 2) Must have a "oneofKind" discriminator property. + * + * 3) If "oneofKind" is `undefined`, no member field is selected. The object + * must not have any other properties. + * + * 4) If "oneofKind" is a `string`, the member field with this name is + * selected. + * + * 5) If a member field is selected, the object must have a second property + * with this name. The property must not be `undefined`. + * + * 6) No extra properties are allowed. The object has either one property + * (no selection) or two properties (selection). + * + */ +function isOneofGroup(any) { + if (typeof any != 'object' || any === null || !any.hasOwnProperty('oneofKind')) { + return false; + } + switch (typeof any.oneofKind) { + case "string": + if (any[any.oneofKind] === undefined) + return false; + return Object.keys(any).length == 2; + case "undefined": + return Object.keys(any).length == 1; + default: + return false; } - - this.name = 'Deprecation'; - } - } - -exports.Deprecation = Deprecation; - - -/***/ }), - -/***/ 2287: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = realpath -realpath.realpath = realpath -realpath.sync = realpathSync -realpath.realpathSync = realpathSync -realpath.monkeypatch = monkeypatch -realpath.unmonkeypatch = unmonkeypatch - -var fs = __nccwpck_require__(7147) -var origRealpath = fs.realpath -var origRealpathSync = fs.realpathSync - -var version = process.version -var ok = /^v[0-5]\./.test(version) -var old = __nccwpck_require__(5456) - -function newError (er) { - return er && er.syscall === 'realpath' && ( - er.code === 'ELOOP' || - er.code === 'ENOMEM' || - er.code === 'ENAMETOOLONG' - ) +exports.isOneofGroup = isOneofGroup; +/** + * Returns the value of the given field in a oneof group. + */ +function getOneofValue(oneof, kind) { + return oneof[kind]; } - -function realpath (p, cache, cb) { - if (ok) { - return origRealpath(p, cache, cb) - } - - 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.getOneofValue = getOneofValue; +function setOneofValue(oneof, kind, value) { + if (oneof.oneofKind !== undefined) { + delete oneof[oneof.oneofKind]; + } + oneof.oneofKind = kind; + if (value !== undefined) { + oneof[kind] = value; } - }) } - -function realpathSync (p, cache) { - if (ok) { - return origRealpathSync(p, cache) - } - - try { - return origRealpathSync(p, cache) - } catch (er) { - if (newError(er)) { - return old.realpathSync(p, cache) - } else { - throw er +exports.setOneofValue = setOneofValue; +function setUnknownOneofValue(oneof, kind, value) { + if (oneof.oneofKind !== undefined) { + delete oneof[oneof.oneofKind]; + } + oneof.oneofKind = kind; + if (value !== undefined && kind !== undefined) { + oneof[kind] = value; } - } } - -function monkeypatch () { - fs.realpath = realpath - fs.realpathSync = realpathSync +exports.setUnknownOneofValue = setUnknownOneofValue; +/** + * Removes the selected field in a oneof group. + * + * Note that the recommended way to modify a oneof group is to set + * a new object: + * + * ```ts + * message.result = { oneofKind: undefined }; + * ``` + */ +function clearOneofValue(oneof) { + if (oneof.oneofKind !== undefined) { + delete oneof[oneof.oneofKind]; + } + oneof.oneofKind = undefined; } - -function unmonkeypatch () { - fs.realpath = origRealpath - fs.realpathSync = origRealpathSync +exports.clearOneofValue = clearOneofValue; +/** + * Returns the selected value of the given oneof group. + * + * Not that the recommended way to access a oneof group is to check + * the "oneofKind" property and let TypeScript narrow down the union + * type for you: + * + * ```ts + * if (message.result.oneofKind === "error") { + * message.result.error; // string + * } + * ``` + * + * In the rare case you just need the value, and do not care about + * which protobuf field is selected, you can use this function + * for convenience. + */ +function getSelectedOneofValue(oneof) { + if (oneof.oneofKind === undefined) { + return undefined; + } + return oneof[oneof.oneofKind]; } +exports.getSelectedOneofValue = getSelectedOneofValue; /***/ }), -/***/ 5456: +/***/ 47777: /***/ ((__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__(1017); -var isWindows = process.platform === 'win32'; -var fs = __nccwpck_require__(7147); - -// JavaScript implementation of realpath, ported from node pre-v6 - -var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); - -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 callback; +"use strict"; - function debugCallback(err) { - if (err) { - backtrace.message = err.message; - err = backtrace; - missingCallback(err); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PbLong = exports.PbULong = exports.detectBi = void 0; +const goog_varint_1 = __nccwpck_require__(30433); +let BI; +function detectBi() { + const dv = new DataView(new ArrayBuffer(8)); + const ok = globalThis.BigInt !== undefined + && typeof dv.getBigInt64 === "function" + && typeof dv.getBigUint64 === "function" + && typeof dv.setBigInt64 === "function" + && typeof dv.setBigUint64 === "function"; + BI = ok ? { + MIN: BigInt("-9223372036854775808"), + MAX: BigInt("9223372036854775807"), + UMIN: BigInt("0"), + UMAX: BigInt("18446744073709551615"), + C: BigInt, + V: dv, + } : undefined; +} +exports.detectBi = detectBi; +detectBi(); +function assertBi(bi) { + if (!bi) + throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support"); +} +// used to validate from(string) input (when bigint is unavailable) +const RE_DECIMAL_STR = /^-?[0-9]+$/; +// constants for binary math +const TWO_PWR_32_DBL = 0x100000000; +const HALF_2_PWR_32 = 0x080000000; +// base class for PbLong and PbULong provides shared code +class SharedPbLong { + /** + * Create a new instance with the given bits. + */ + constructor(lo, hi) { + this.lo = lo | 0; + this.hi = hi | 0; + } + /** + * Is this instance equal to 0? + */ + isZero() { + return this.lo == 0 && this.hi == 0; + } + /** + * Convert to a native number. + */ + toNumber() { + let result = this.hi * TWO_PWR_32_DBL + (this.lo >>> 0); + if (!Number.isSafeInteger(result)) + throw new Error("cannot convert to safe number"); + return result; } - } - - 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); +} +/** + * 64-bit unsigned integer as two 32-bit values. + * Converts between `string`, `number` and `bigint` representations. + */ +class PbULong extends SharedPbLong { + /** + * Create instance from a `string`, `number` or `bigint`. + */ + static from(value) { + if (BI) + // noinspection FallThroughInSwitchStatementJS + switch (typeof value) { + case "string": + if (value == "0") + return this.ZERO; + if (value == "") + throw new Error('string is no integer'); + value = BI.C(value); + case "number": + if (value === 0) + return this.ZERO; + value = BI.C(value); + case "bigint": + if (!value) + return this.ZERO; + if (value < BI.UMIN) + throw new Error('signed value for ulong'); + if (value > BI.UMAX) + throw new Error('ulong too large'); + BI.V.setBigUint64(0, value, true); + return new PbULong(BI.V.getInt32(0, true), BI.V.getInt32(4, true)); + } else - console.error(msg); - } + switch (typeof value) { + case "string": + if (value == "0") + return this.ZERO; + value = value.trim(); + if (!RE_DECIMAL_STR.test(value)) + throw new Error('string is no integer'); + let [minus, lo, hi] = goog_varint_1.int64fromString(value); + if (minus) + throw new Error('signed value for ulong'); + return new PbULong(lo, hi); + case "number": + if (value == 0) + return this.ZERO; + if (!Number.isSafeInteger(value)) + throw new Error('number is no integer'); + if (value < 0) + throw new Error('signed value for ulong'); + return new PbULong(value, value / TWO_PWR_32_DBL); + } + throw new Error('unknown value ' + typeof value); + } + /** + * Convert to decimal string. + */ + toString() { + return BI ? this.toBigInt().toString() : goog_varint_1.int64toString(this.lo, this.hi); + } + /** + * Convert to native bigint. + */ + toBigInt() { + assertBi(BI); + BI.V.setInt32(0, this.lo, true); + BI.V.setInt32(4, this.hi, true); + return BI.V.getBigUint64(0, true); } - } -} - -function maybeCallback(cb) { - return typeof cb === 'function' ? cb : rethrow(); -} - -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 = /^[\/]*/; } - -exports.realpathSync = function realpathSync(p, cache) { - // make p is absolute - p = pathModule.resolve(p); - - if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { - return cache[p]; - } - - 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(); - - 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.lstatSync(base); - knownHard[base] = true; +exports.PbULong = PbULong; +/** + * ulong 0 singleton. + */ +PbULong.ZERO = new PbULong(0, 0); +/** + * 64-bit signed integer as two 32-bit values. + * Converts between `string`, `number` and `bigint` representations. + */ +class PbLong extends SharedPbLong { + /** + * Create instance from a `string`, `number` or `bigint`. + */ + static from(value) { + if (BI) + // noinspection FallThroughInSwitchStatementJS + switch (typeof value) { + case "string": + if (value == "0") + return this.ZERO; + if (value == "") + throw new Error('string is no integer'); + value = BI.C(value); + case "number": + if (value === 0) + return this.ZERO; + value = BI.C(value); + case "bigint": + if (!value) + return this.ZERO; + if (value < BI.MIN) + throw new Error('signed long too small'); + if (value > BI.MAX) + throw new Error('signed long too large'); + BI.V.setBigInt64(0, value, true); + return new PbLong(BI.V.getInt32(0, true), BI.V.getInt32(4, true)); + } + else + switch (typeof value) { + case "string": + if (value == "0") + return this.ZERO; + value = value.trim(); + if (!RE_DECIMAL_STR.test(value)) + throw new Error('string is no integer'); + let [minus, lo, hi] = goog_varint_1.int64fromString(value); + if (minus) { + if (hi > HALF_2_PWR_32 || (hi == HALF_2_PWR_32 && lo != 0)) + throw new Error('signed long too small'); + } + else if (hi >= HALF_2_PWR_32) + throw new Error('signed long too large'); + let pbl = new PbLong(lo, hi); + return minus ? pbl.negate() : pbl; + case "number": + if (value == 0) + return this.ZERO; + if (!Number.isSafeInteger(value)) + throw new Error('number is no integer'); + return value > 0 + ? new PbLong(value, value / TWO_PWR_32_DBL) + : new PbLong(-value, -value / TWO_PWR_32_DBL).negate(); + } + throw new Error('unknown value ' + typeof value); } - } - - // 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; + /** + * Do we have a minus sign? + */ + isNegative() { + return (this.hi & HALF_2_PWR_32) !== 0; } - - 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; - } - - // 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; + /** + * Negate two's complement. + * Invert all the bits and add one to the result. + */ + negate() { + let hi = ~this.hi, lo = this.lo; + if (lo) + lo = ~lo + 1; + else + hi += 1; + return new PbLong(lo, hi); } - - // resolve the link, then start over - p = pathModule.resolve(resolvedLink, p.slice(pos)); - start(); - } - - if (cache) cache[original] = p; - - return p; -}; - - -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])); - } - - 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(); - - 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); + /** + * Convert to decimal string. + */ + toString() { + if (BI) + return this.toBigInt().toString(); + if (this.isNegative()) { + let n = this.negate(); + return '-' + goog_varint_1.int64toString(n.lo, n.hi); + } + return goog_varint_1.int64toString(this.lo, this.hi); } - } - - // 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); + /** + * Convert to native bigint. + */ + toBigInt() { + assertBi(BI); + BI.V.setInt32(0, this.lo, true); + BI.V.setInt32(4, this.hi, true); + return BI.V.getBigInt64(0, true); } +} +exports.PbLong = PbLong; +/** + * long 0 singleton. + */ +PbLong.ZERO = new PbLong(0, 0); - // 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); - } +/***/ 95290: +/***/ ((__unused_webpack_module, exports) => { - function gotStat(err, stat) { - if (err) return cb(err); +"use strict"; - // 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); +// Copyright (c) 2016, Daniel Wirtz All rights reserved. +// +// 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 its author, 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. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.utf8read = void 0; +const fromCharCodes = (chunk) => String.fromCharCode.apply(String, chunk); +/** + * @deprecated This function will no longer be exported with the next major + * release, since protobuf-ts has switch to TextDecoder API. If you need this + * function, please migrate to @protobufjs/utf8. For context, see + * https://github.com/timostamm/protobuf-ts/issues/184 + * + * Reads UTF8 bytes as a string. + * + * See [protobufjs / utf8](https://github.com/protobufjs/protobuf.js/blob/9893e35b854621cce64af4bf6be2cff4fb892796/lib/utf8/index.js#L40) + * + * Copyright (c) 2016, Daniel Wirtz + */ +function utf8read(bytes) { + if (bytes.length < 1) + return ""; + let pos = 0, // position in bytes + parts = [], chunk = [], i = 0, // char offset + t; // temporary + let len = bytes.length; + while (pos < len) { + t = bytes[pos++]; + if (t < 128) + chunk[i++] = t; + else if (t > 191 && t < 224) + chunk[i++] = (t & 31) << 6 | bytes[pos++] & 63; + else if (t > 239 && t < 365) { + t = ((t & 7) << 18 | (bytes[pos++] & 63) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63) - 0x10000; + chunk[i++] = 0xD800 + (t >> 10); + chunk[i++] = 0xDC00 + (t & 1023); + } + else + chunk[i++] = (t & 15) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63; + if (i > 8191) { + parts.push(fromCharCodes(chunk)); + i = 0; + } } - - // 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); - } + if (parts.length) { + if (i) + parts.push(fromCharCodes(chunk.slice(0, i))); + return parts.join(""); } - 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(); - } -}; + return fromCharCodes(chunk.slice(0, i)); +} +exports.utf8read = utf8read; /***/ }), -/***/ 4063: +/***/ 91593: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -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__(7147) -var path = __nccwpck_require__(1017) -var minimatch = __nccwpck_require__(5806) -var isAbsolute = __nccwpck_require__(3985) -var Minimatch = minimatch.Minimatch - -function alphasort (a, b) { - return a.localeCompare(b, 'en') -} - -function setupIgnores (self, options) { - self.ignore = options.ignore || [] - - if (!Array.isArray(self.ignore)) - self.ignore = [self.ignore] +"use strict"; - if (self.ignore.length) { - self.ignore = self.ignore.map(ignoreMap) - } -} - -// 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 }) - } - - return { - matcher: new Minimatch(pattern, { dot: true }), - gmatcher: gmatcher - } -} - -function setopts (self, pattern, options) { - if (!options) - options = {} - - // 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 - } - - 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) - - 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 - } - - 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 - - // 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 -} - -function finish (self) { - var nou = self.nounique - var all = nou ? [] : Object.create(null) - - 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 - }) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ReflectionBinaryReader = void 0; +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. + * + * https://developers.google.com/protocol-buffers/docs/encoding + */ +class ReflectionBinaryReader { + constructor(info) { + this.info = info; } - } - - if (!nou) - all = Object.keys(all) - - if (!self.nosort) - all = all.sort(alphasort) - - // 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]) + prepare() { + var _a; + if (!this.fieldNoToField) { + const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; + this.fieldNoToField = new Map(fieldsInput.map(field => [field.no, field])); + } } - 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 - }) + /** + * Reads a message from binary format into the target message. + * + * Repeated fields are appended. Map entries are added, overwriting + * existing keys. + * + * If a message field is already present, it will be merged with the + * new data. + */ + read(reader, message, options, length) { + this.prepare(); + const end = length === undefined ? reader.len : reader.pos + length; + while (reader.pos < end) { + // read the tag and find the field + const [fieldNo, wireType] = reader.tag(), field = this.fieldNoToField.get(fieldNo); + if (!field) { + let u = options.readUnknownField; + if (u == "throw") + throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.info.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? binary_format_contract_1.UnknownFieldHandler.onRead : u)(this.info.typeName, message, fieldNo, wireType, d); + continue; + } + // target object for the field we are reading + let target = message, repeated = field.repeat, localName = field.localName; + // if field is member of oneof ADT, use ADT as target + if (field.oneof) { + target = target[field.oneof]; + // if other oneof member selected, set new ADT + if (target.oneofKind !== localName) + target = message[field.oneof] = { + oneofKind: localName + }; + } + // we have handled oneof above, we just have read the value into `target[localName]` + switch (field.kind) { + case "scalar": + case "enum": + let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + let L = field.kind == "scalar" ? field.L : undefined; + if (repeated) { + let arr = target[localName]; // safe to assume presence of array, oneof cannot contain repeated values + if (wireType == binary_format_contract_1.WireType.LengthDelimited && T != reflection_info_1.ScalarType.STRING && T != reflection_info_1.ScalarType.BYTES) { + let e = reader.uint32() + reader.pos; + while (reader.pos < e) + arr.push(this.scalar(reader, T, L)); + } + else + arr.push(this.scalar(reader, T, L)); + } + else + target[localName] = this.scalar(reader, T, L); + break; + case "message": + if (repeated) { + let arr = target[localName]; // safe to assume presence of array, oneof cannot contain repeated values + let msg = field.T().internalBinaryRead(reader, reader.uint32(), options); + arr.push(msg); + } + else + target[localName] = field.T().internalBinaryRead(reader, reader.uint32(), options, target[localName]); + break; + case "map": + let [mapKey, mapVal] = this.mapEntry(field, reader, options); + // safe to assume presence of map object, oneof cannot contain repeated values + target[localName][mapKey] = mapVal; + break; + } + } } - } - - if (self.ignore.length) - all = all.filter(function(m) { - return !isIgnored(self, m) - }) - - 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) === '/' - - if (isDir && !slash) - m += '/' - else if (!isDir && slash) - m = m.slice(0, -1) - - if (m !== p) { - var mabs = makeAbs(self, m) - self.statCache[mabs] = self.statCache[abs] - self.cache[mabs] = self.cache[abs] + /** + * Read a map field, expecting key field = 1, value field = 2 + */ + mapEntry(field, reader, options) { + let length = reader.uint32(); + let end = reader.pos + length; + let key = undefined; // javascript only allows number or string for object properties + let val = undefined; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case 1: + if (field.K == reflection_info_1.ScalarType.BOOL) + key = reader.bool().toString(); + else + // long types are read as string, number types are okay as number + key = this.scalar(reader, field.K, reflection_info_1.LongType.STRING); + break; + case 2: + switch (field.V.kind) { + case "scalar": + val = this.scalar(reader, field.V.T, field.V.L); + break; + case "enum": + val = reader.int32(); + break; + case "message": + val = field.V.T().internalBinaryRead(reader, reader.uint32(), options); + break; + } + break; + default: + throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) in map entry for ${this.info.typeName}#${field.name}`); + } + } + if (key === undefined) { + let keyRaw = reflection_scalar_default_1.reflectionScalarDefault(field.K); + key = field.K == reflection_info_1.ScalarType.BOOL ? keyRaw.toString() : keyRaw; + } + if (val === undefined) + switch (field.V.kind) { + case "scalar": + val = reflection_scalar_default_1.reflectionScalarDefault(field.V.T, field.V.L); + break; + case "enum": + val = 0; + break; + case "message": + val = field.V.T().create(); + break; + } + return [key, val]; } - } - - 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, '/') - - return abs -} + scalar(reader, type, longType) { + switch (type) { + case reflection_info_1.ScalarType.INT32: + return reader.int32(); + case reflection_info_1.ScalarType.STRING: + return reader.string(); + case reflection_info_1.ScalarType.BOOL: + return reader.bool(); + case reflection_info_1.ScalarType.DOUBLE: + return reader.double(); + case reflection_info_1.ScalarType.FLOAT: + return reader.float(); + case reflection_info_1.ScalarType.INT64: + return reflection_long_convert_1.reflectionLongConvert(reader.int64(), longType); + case reflection_info_1.ScalarType.UINT64: + return reflection_long_convert_1.reflectionLongConvert(reader.uint64(), longType); + case reflection_info_1.ScalarType.FIXED64: + return reflection_long_convert_1.reflectionLongConvert(reader.fixed64(), longType); + case reflection_info_1.ScalarType.FIXED32: + return reader.fixed32(); + case reflection_info_1.ScalarType.BYTES: + return reader.bytes(); + case reflection_info_1.ScalarType.UINT32: + return reader.uint32(); + case reflection_info_1.ScalarType.SFIXED32: + return reader.sfixed32(); + case reflection_info_1.ScalarType.SFIXED64: + return reflection_long_convert_1.reflectionLongConvert(reader.sfixed64(), longType); + case reflection_info_1.ScalarType.SINT32: + return reader.sint32(); + case reflection_info_1.ScalarType.SINT64: + return reflection_long_convert_1.reflectionLongConvert(reader.sint64(), longType); + } + } +} +exports.ReflectionBinaryReader = ReflectionBinaryReader; -// 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 +/***/ }), - return self.ignore.some(function(item) { - return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) - }) -} +/***/ 57170: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function childrenIgnored (self, path) { - if (!self.ignore.length) - return false +"use strict"; - return self.ignore.some(function(item) { - return !!(item.gmatcher && item.gmatcher.match(path)) - }) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ReflectionBinaryWriter = void 0; +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. + * + * https://developers.google.com/protocol-buffers/docs/encoding + */ +class ReflectionBinaryWriter { + constructor(info) { + this.info = info; + } + prepare() { + if (!this.fields) { + const fieldsInput = this.info.fields ? this.info.fields.concat() : []; + this.fields = fieldsInput.sort((a, b) => a.no - b.no); + } + } + /** + * Writes the message to binary format. + */ + write(message, writer, options) { + this.prepare(); + for (const field of this.fields) { + let value, // this will be our field value, whether it is member of a oneof or not + emitDefault, // whether we emit the default value (only true for oneof members) + repeated = field.repeat, localName = field.localName; + // handle oneof ADT + if (field.oneof) { + const group = message[field.oneof]; + if (group.oneofKind !== localName) + continue; // if field is not selected, skip + value = group[localName]; + emitDefault = true; + } + else { + value = message[localName]; + emitDefault = false; + } + // we have handled oneof above. we just have to honor `emitDefault`. + switch (field.kind) { + case "scalar": + case "enum": + let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + if (repeated) { + assert_1.assert(Array.isArray(value)); + if (repeated == reflection_info_1.RepeatType.PACKED) + this.packed(writer, T, field.no, value); + else + for (const item of value) + this.scalar(writer, T, field.no, item, true); + } + else if (value === undefined) + assert_1.assert(field.opt); + else + this.scalar(writer, T, field.no, value, emitDefault || field.opt); + break; + case "message": + if (repeated) { + assert_1.assert(Array.isArray(value)); + for (const item of value) + this.message(writer, options, field.T(), field.no, item); + } + else { + this.message(writer, options, field.T(), field.no, value); + } + break; + case "map": + assert_1.assert(typeof value == 'object' && value !== null); + for (const [key, val] of Object.entries(value)) + this.mapEntry(writer, options, field, key, val); + break; + } + } + let u = options.writeUnknownFields; + if (u !== false) + (u === true ? binary_format_contract_1.UnknownFieldHandler.onWrite : u)(this.info.typeName, message, writer); + } + mapEntry(writer, options, field, key, value) { + writer.tag(field.no, binary_format_contract_1.WireType.LengthDelimited); + writer.fork(); + // javascript only allows number or string for object properties + // we convert from our representation to the protobuf type + let keyValue = key; + switch (field.K) { + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.UINT32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + keyValue = Number.parseInt(key); + break; + case reflection_info_1.ScalarType.BOOL: + assert_1.assert(key == 'true' || key == 'false'); + keyValue = key == 'true'; + break; + } + // write key, expecting key field number = 1 + this.scalar(writer, field.K, 1, keyValue, true); + // write value, expecting value field number = 2 + switch (field.V.kind) { + case 'scalar': + this.scalar(writer, field.V.T, 2, value, true); + break; + case 'enum': + this.scalar(writer, reflection_info_1.ScalarType.INT32, 2, value, true); + break; + case 'message': + this.message(writer, options, field.V.T(), 2, value); + break; + } + writer.join(); + } + message(writer, options, handler, fieldNo, value) { + if (value === undefined) + return; + handler.internalBinaryWrite(value, writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited).fork(), options); + writer.join(); + } + /** + * Write a single scalar value. + */ + scalar(writer, type, fieldNo, value, emitDefault) { + let [wireType, method, isDefault] = this.scalarInfo(type, value); + if (!isDefault || emitDefault) { + writer.tag(fieldNo, wireType); + writer[method](value); + } + } + /** + * Write an array of scalar values in packed format. + */ + packed(writer, type, fieldNo, value) { + if (!value.length) + return; + assert_1.assert(type !== reflection_info_1.ScalarType.BYTES && type !== reflection_info_1.ScalarType.STRING); + // write tag + writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited); + // begin length-delimited + writer.fork(); + // write values without tags + let [, method,] = this.scalarInfo(type); + for (let i = 0; i < value.length; i++) + writer[method](value[i]); + // end length delimited + writer.join(); + } + /** + * Get information for writing a scalar value. + * + * Returns tuple: + * [0]: appropriate WireType + * [1]: name of the appropriate method of IBinaryWriter + * [2]: whether the given value is a default value + * + * If argument `value` is omitted, [2] is always false. + */ + scalarInfo(type, value) { + let t = binary_format_contract_1.WireType.Varint; + let m; + let i = value === undefined; + let d = value === 0; + switch (type) { + case reflection_info_1.ScalarType.INT32: + m = "int32"; + break; + case reflection_info_1.ScalarType.STRING: + d = i || !value.length; + t = binary_format_contract_1.WireType.LengthDelimited; + m = "string"; + break; + case reflection_info_1.ScalarType.BOOL: + d = value === false; + m = "bool"; + break; + case reflection_info_1.ScalarType.UINT32: + m = "uint32"; + break; + case reflection_info_1.ScalarType.DOUBLE: + t = binary_format_contract_1.WireType.Bit64; + m = "double"; + break; + case reflection_info_1.ScalarType.FLOAT: + t = binary_format_contract_1.WireType.Bit32; + m = "float"; + break; + case reflection_info_1.ScalarType.INT64: + d = i || pb_long_1.PbLong.from(value).isZero(); + m = "int64"; + break; + case reflection_info_1.ScalarType.UINT64: + d = i || pb_long_1.PbULong.from(value).isZero(); + m = "uint64"; + break; + case reflection_info_1.ScalarType.FIXED64: + d = i || pb_long_1.PbULong.from(value).isZero(); + t = binary_format_contract_1.WireType.Bit64; + m = "fixed64"; + break; + case reflection_info_1.ScalarType.BYTES: + d = i || !value.byteLength; + t = binary_format_contract_1.WireType.LengthDelimited; + m = "bytes"; + break; + case reflection_info_1.ScalarType.FIXED32: + t = binary_format_contract_1.WireType.Bit32; + m = "fixed32"; + break; + case reflection_info_1.ScalarType.SFIXED32: + t = binary_format_contract_1.WireType.Bit32; + m = "sfixed32"; + break; + case reflection_info_1.ScalarType.SFIXED64: + d = i || pb_long_1.PbLong.from(value).isZero(); + t = binary_format_contract_1.WireType.Bit64; + m = "sfixed64"; + break; + case reflection_info_1.ScalarType.SINT32: + m = "sint32"; + break; + case reflection_info_1.ScalarType.SINT64: + d = i || pb_long_1.PbLong.from(value).isZero(); + m = "sint64"; + break; + } + return [t, m, i || d]; + } } +exports.ReflectionBinaryWriter = ReflectionBinaryWriter; /***/ }), -/***/ 7004: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -// 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. - -module.exports = glob - -var rp = __nccwpck_require__(2287) -var minimatch = __nccwpck_require__(5806) -var Minimatch = minimatch.Minimatch -var inherits = __nccwpck_require__(7187) -var EE = (__nccwpck_require__(2361).EventEmitter) -var path = __nccwpck_require__(1017) -var assert = __nccwpck_require__(9491) -var isAbsolute = __nccwpck_require__(3985) -var globSync = __nccwpck_require__(9859) -var common = __nccwpck_require__(4063) -var setopts = common.setopts -var ownProp = common.ownProp -var inflight = __nccwpck_require__(5950) -var util = __nccwpck_require__(3837) -var childrenIgnored = common.childrenIgnored -var isIgnored = common.isIgnored - -var once = __nccwpck_require__(4410) - -function glob (pattern, options, cb) { - if (typeof options === 'function') cb = options, options = {} - if (!options) options = {} - - if (options.sync) { - if (cb) - throw new TypeError('callback provided to sync glob') - return globSync(pattern, options) - } - - return new Glob(pattern, options, cb) -} - -glob.sync = globSync -var GlobSync = glob.GlobSync = globSync.GlobSync - -// old api surface -glob.glob = glob +/***/ 67317: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function extend (origin, add) { - if (add === null || typeof add !== 'object') { - return origin - } +"use strict"; - var keys = Object.keys(add) - var i = keys.length - while (i--) { - origin[keys[i]] = add[keys[i]] - } - return origin +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.containsMessageType = void 0; +const message_type_contract_1 = __nccwpck_require__(1682); +/** + * Check if the provided object is a proto message. + * + * Note that this is an experimental feature - it is here to stay, but + * implementation details may change without notice. + */ +function containsMessageType(msg) { + return msg[message_type_contract_1.MESSAGE_TYPE] != null; } +exports.containsMessageType = containsMessageType; -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 +/***/ }), - if (set.length > 1) - return true +/***/ 60390: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - for (var j = 0; j < set[0].length; j++) { - if (typeof set[0][j] !== 'string') - return true - } +"use strict"; - return false +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.reflectionCreate = void 0; +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) { + /** + * 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) + continue; + if (field.oneof) + msg[field.oneof] = { oneofKind: undefined }; + else if (field.repeat) + msg[name] = []; + else + switch (field.kind) { + case "scalar": + msg[name] = reflection_scalar_default_1.reflectionScalarDefault(field.T, field.L); + break; + case "enum": + // we require 0 to be default value for all enums + msg[name] = 0; + break; + case "map": + msg[name] = {}; + break; + } + } + return msg; } +exports.reflectionCreate = reflectionCreate; -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 - - // 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) - if (typeof cb === 'function') { - cb = once(cb) - this.on('error', cb) - this.on('end', function (matches) { - cb(null, matches) - }) - } - - var self = this - this._processing = 0 - - this._emitQueue = [] - this._processQueue = [] - this.paused = false - - if (this.noprocess) - return this +/***/ }), - if (n === 0) - return done() +/***/ 39473: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var sync = true - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false, done) - } - sync = false +"use strict"; - function done () { - --self._processing - if (self._processing <= 0) { - if (sync) { - process.nextTick(function () { - self._finish() - }) - } else { - self._finish() - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.reflectionEquals = void 0; +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 + * and messages recursively. + * Will also return true if both messages are `undefined`. + */ +function reflectionEquals(info, a, b) { + if (a === b) + return true; + if (!a || !b) + return false; + for (let field of info.fields) { + let localName = field.localName; + let val_a = field.oneof ? a[field.oneof][localName] : a[localName]; + let val_b = field.oneof ? b[field.oneof][localName] : b[localName]; + switch (field.kind) { + case "enum": + case "scalar": + let t = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + if (!(field.repeat + ? repeatedPrimitiveEq(t, val_a, val_b) + : primitiveEq(t, val_a, val_b))) + return false; + break; + case "map": + if (!(field.V.kind == "message" + ? repeatedMsgEq(field.V.T(), objectValues(val_a), objectValues(val_b)) + : repeatedPrimitiveEq(field.V.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.V.T, objectValues(val_a), objectValues(val_b)))) + return false; + break; + case "message": + let T = field.T(); + if (!(field.repeat + ? repeatedMsgEq(T, val_a, val_b) + : T.equals(val_a, val_b))) + return false; + break; + } } - } + return true; } - -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) +exports.reflectionEquals = reflectionEquals; +const objectValues = Object.values; +function primitiveEq(type, a, b) { + if (a === b) + return true; + if (type !== reflection_info_1.ScalarType.BYTES) + return false; + let ba = a; + let bb = b; + if (ba.length !== bb.length) + return false; + for (let i = 0; i < ba.length; i++) + if (ba[i] != bb[i]) + return false; + return true; +} +function repeatedPrimitiveEq(type, a, b) { + if (a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!primitiveEq(type, a[i], b[i])) + return false; + return true; +} +function repeatedMsgEq(type, a, b) { + if (a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!type.equals(a[i], b[i])) + return false; + return true; } -Glob.prototype._realpath = function () { - if (this._didRealpath) - return - this._didRealpath = true +/***/ }), - var n = this.matches.length - if (n === 0) - return this._finish() +/***/ 21370: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var self = this - for (var i = 0; i < this.matches.length; i++) - this._realpathSet(i, next) +"use strict"; - function next () { - if (--n === 0) - self._finish() - } +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__(34772); +/** + * Scalar value types. This is a subset of field types declared by protobuf + * enum google.protobuf.FieldDescriptorProto.Type The types GROUP and MESSAGE + * are omitted, but the numerical values are identical. + */ +var ScalarType; +(function (ScalarType) { + // 0 is reserved for errors. + // Order is weird for historical reasons. + ScalarType[ScalarType["DOUBLE"] = 1] = "DOUBLE"; + ScalarType[ScalarType["FLOAT"] = 2] = "FLOAT"; + // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if + // negative values are likely. + ScalarType[ScalarType["INT64"] = 3] = "INT64"; + ScalarType[ScalarType["UINT64"] = 4] = "UINT64"; + // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if + // negative values are likely. + ScalarType[ScalarType["INT32"] = 5] = "INT32"; + ScalarType[ScalarType["FIXED64"] = 6] = "FIXED64"; + ScalarType[ScalarType["FIXED32"] = 7] = "FIXED32"; + ScalarType[ScalarType["BOOL"] = 8] = "BOOL"; + ScalarType[ScalarType["STRING"] = 9] = "STRING"; + // Tag-delimited aggregate. + // Group type is deprecated and not supported in proto3. However, Proto3 + // implementations should still be able to parse the group wire format and + // treat group fields as unknown fields. + // TYPE_GROUP = 10, + // TYPE_MESSAGE = 11, // Length-delimited aggregate. + // New in version 2. + ScalarType[ScalarType["BYTES"] = 12] = "BYTES"; + ScalarType[ScalarType["UINT32"] = 13] = "UINT32"; + // TYPE_ENUM = 14, + ScalarType[ScalarType["SFIXED32"] = 15] = "SFIXED32"; + ScalarType[ScalarType["SFIXED64"] = 16] = "SFIXED64"; + ScalarType[ScalarType["SINT32"] = 17] = "SINT32"; + ScalarType[ScalarType["SINT64"] = 18] = "SINT64"; +})(ScalarType = exports.ScalarType || (exports.ScalarType = {})); +/** + * JavaScript representation of 64 bit integral types. Equivalent to the + * field option "jstype". + * + * By default, protobuf-ts represents 64 bit types as `bigint`. + * + * You can change the default behaviour by enabling the plugin parameter + * `long_type_string`, which will represent 64 bit types as `string`. + * + * Alternatively, you can change the behaviour for individual fields + * with the field option "jstype": + * + * ```protobuf + * uint64 my_field = 1 [jstype = JS_STRING]; + * uint64 other_field = 2 [jstype = JS_NUMBER]; + * ``` + */ +var LongType; +(function (LongType) { + /** + * Use JavaScript `bigint`. + * + * Field option `[jstype = JS_NORMAL]`. + */ + LongType[LongType["BIGINT"] = 0] = "BIGINT"; + /** + * Use JavaScript `string`. + * + * Field option `[jstype = JS_STRING]`. + */ + LongType[LongType["STRING"] = 1] = "STRING"; + /** + * Use JavaScript `number`. + * + * Large values will loose precision. + * + * Field option `[jstype = JS_NUMBER]`. + */ + LongType[LongType["NUMBER"] = 2] = "NUMBER"; +})(LongType = exports.LongType || (exports.LongType = {})); +/** + * Protobuf 2.1.0 introduced packed repeated fields. + * Setting the field option `[packed = true]` enables packing. + * + * In proto3, all repeated fields are packed by default. + * Setting the field option `[packed = false]` disables packing. + * + * Packed repeated fields are encoded with a single tag, + * then a length-delimiter, then the element values. + * + * Unpacked repeated fields are encoded with a tag and + * value for each element. + * + * `bytes` and `string` cannot be packed. + */ +var RepeatType; +(function (RepeatType) { + /** + * The field is not repeated. + */ + RepeatType[RepeatType["NO"] = 0] = "NO"; + /** + * The field is repeated and should be packed. + * Invalid for `bytes` and `string`, they cannot be packed. + */ + RepeatType[RepeatType["PACKED"] = 1] = "PACKED"; + /** + * The field is repeated but should not be packed. + * The only valid repeat type for repeated `bytes` and `string`. + */ + RepeatType[RepeatType["UNPACKED"] = 2] = "UNPACKED"; +})(RepeatType = exports.RepeatType || (exports.RepeatType = {})); +/** + * Turns PartialFieldInfo into FieldInfo. + */ +function normalizeFieldInfo(field) { + var _a, _b, _c, _d; + field.localName = (_a = field.localName) !== null && _a !== void 0 ? _a : lower_camel_case_1.lowerCamelCase(field.name); + field.jsonName = (_b = field.jsonName) !== null && _b !== void 0 ? _b : lower_camel_case_1.lowerCamelCase(field.name); + field.repeat = (_c = field.repeat) !== null && _c !== void 0 ? _c : RepeatType.NO; + field.opt = (_d = field.opt) !== null && _d !== void 0 ? _d : (field.repeat ? false : field.oneof ? false : field.kind == "message"); + return field; +} +exports.normalizeFieldInfo = normalizeFieldInfo; +/** + * Read custom field options from a generated message type. + * + * @deprecated use readFieldOption() + */ +function readFieldOptions(messageType, fieldName, extensionName, extensionType) { + var _a; + const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; + return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : undefined; } +exports.readFieldOptions = readFieldOptions; +function readFieldOption(messageType, fieldName, extensionName, extensionType) { + var _a; + const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; + if (!options) { + return undefined; + } + const optionVal = options[extensionName]; + if (optionVal === undefined) { + return optionVal; + } + return extensionType ? extensionType.fromJson(optionVal) : optionVal; +} +exports.readFieldOption = readFieldOption; +function readMessageOption(messageType, extensionName, extensionType) { + const options = messageType.options; + const optionVal = options[extensionName]; + if (optionVal === undefined) { + return optionVal; + } + return extensionType ? extensionType.fromJson(optionVal) : optionVal; +} +exports.readMessageOption = readMessageOption; -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() +/***/ 229: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - 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 +"use strict"; - if (--n === 0) { - self.matches[index] = set - cb() - } - }) - }) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ReflectionJsonReader = void 0; +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. + * + * https://developers.google.com/protocol-buffers/docs/proto3#json + */ +class ReflectionJsonReader { + constructor(info) { + this.info = info; + } + prepare() { + var _a; + if (this.fMap === undefined) { + this.fMap = {}; + const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; + for (const field of fieldsInput) { + this.fMap[field.name] = field; + this.fMap[field.jsonName] = field; + this.fMap[field.localName] = field; + } + } + } + // Cannot parse JSON for #. + assert(condition, fieldName, jsonValue) { + if (!condition) { + let what = json_typings_1.typeofJsonValue(jsonValue); + if (what == "number" || what == "boolean") + what = jsonValue.toString(); + throw new Error(`Cannot parse JSON ${what} for ${this.info.typeName}#${fieldName}`); + } + } + /** + * Reads a message from canonical JSON format into the target message. + * + * Repeated fields are appended. Map entries are added, overwriting + * existing keys. + * + * If a message field is already present, it will be merged with the + * new data. + */ + read(input, message, options) { + this.prepare(); + const oneofsHandled = []; + for (const [jsonKey, jsonValue] of Object.entries(input)) { + const field = this.fMap[jsonKey]; + if (!field) { + if (!options.ignoreUnknownFields) + throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${jsonKey}`); + continue; + } + const localName = field.localName; + // handle oneof ADT + let target; // this will be the target for the field value, whether it is member of a oneof or not + if (field.oneof) { + if (jsonValue === null && (field.kind !== 'enum' || field.T()[0] !== 'google.protobuf.NullValue')) { + continue; + } + // since json objects are unordered by specification, it is not possible to take the last of multiple oneofs + if (oneofsHandled.includes(field.oneof)) + throw new Error(`Multiple members of the oneof group "${field.oneof}" of ${this.info.typeName} are present in JSON.`); + oneofsHandled.push(field.oneof); + target = message[field.oneof] = { + oneofKind: localName + }; + } + else { + target = message; + } + // we have handled oneof above. we just have read the value into `target`. + if (field.kind == 'map') { + if (jsonValue === null) { + continue; + } + // check input + this.assert(json_typings_1.isJsonObject(jsonValue), field.name, jsonValue); + // our target to put map entries into + const fieldObj = target[localName]; + // read entries + for (const [jsonObjKey, jsonObjValue] of Object.entries(jsonValue)) { + this.assert(jsonObjValue !== null, field.name + " map value", null); + // read value + let val; + switch (field.V.kind) { + case "message": + val = field.V.T().internalJsonRead(jsonObjValue, options); + break; + case "enum": + val = this.enum(field.V.T(), jsonObjValue, field.name, options.ignoreUnknownFields); + if (val === false) + continue; + break; + case "scalar": + val = this.scalar(jsonObjValue, field.V.T, field.V.L, field.name); + break; + } + this.assert(val !== undefined, field.name + " map value", jsonObjValue); + // read key + let key = jsonObjKey; + if (field.K == reflection_info_1.ScalarType.BOOL) + key = key == "true" ? true : key == "false" ? false : key; + key = this.scalar(key, field.K, reflection_info_1.LongType.STRING, field.name).toString(); + fieldObj[key] = val; + } + } + else if (field.repeat) { + if (jsonValue === null) + continue; + // check input + this.assert(Array.isArray(jsonValue), field.name, jsonValue); + // our target to put array entries into + const fieldArr = target[localName]; + // read array entries + for (const jsonItem of jsonValue) { + this.assert(jsonItem !== null, field.name, null); + let val; + switch (field.kind) { + case "message": + val = field.T().internalJsonRead(jsonItem, options); + break; + case "enum": + val = this.enum(field.T(), jsonItem, field.name, options.ignoreUnknownFields); + if (val === false) + continue; + break; + case "scalar": + val = this.scalar(jsonItem, field.T, field.L, field.name); + break; + } + this.assert(val !== undefined, field.name, jsonValue); + fieldArr.push(val); + } + } + else { + switch (field.kind) { + case "message": + if (jsonValue === null && field.T().typeName != 'google.protobuf.Value') { + this.assert(field.oneof === undefined, field.name + " (oneof member)", null); + continue; + } + target[localName] = field.T().internalJsonRead(jsonValue, options, target[localName]); + break; + case "enum": + let val = this.enum(field.T(), jsonValue, field.name, options.ignoreUnknownFields); + if (val === false) + continue; + target[localName] = val; + break; + case "scalar": + target[localName] = this.scalar(jsonValue, field.T, field.L, field.name); + break; + } + } + } + } + /** + * Returns `false` for unrecognized string representations. + * + * google.protobuf.NullValue accepts only JSON `null` (or the old `"NULL_VALUE"`). + */ + enum(type, json, fieldName, ignoreUnknownFields) { + if (type[0] == 'google.protobuf.NullValue') + assert_1.assert(json === null || json === "NULL_VALUE", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type[0]} only accepts null.`); + if (json === null) + // we require 0 to be default value for all enums + return 0; + switch (typeof json) { + case "number": + assert_1.assert(Number.isInteger(json), `Unable to parse field ${this.info.typeName}#${fieldName}, enum can only be integral number, got ${json}.`); + return json; + case "string": + let localEnumName = json; + if (type[2] && json.substring(0, type[2].length) === type[2]) + // lookup without the shared prefix + localEnumName = json.substring(type[2].length); + let enumNumber = type[1][localEnumName]; + if (typeof enumNumber === 'undefined' && ignoreUnknownFields) { + return false; + } + assert_1.assert(typeof enumNumber == "number", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type[0]} has no value for "${json}".`); + return enumNumber; + } + assert_1.assert(false, `Unable to parse field ${this.info.typeName}#${fieldName}, cannot parse enum value from ${typeof json}".`); + } + scalar(json, type, longType, fieldName) { + let e; + try { + switch (type) { + // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". + // Either numbers or strings are accepted. Exponent notation is also accepted. + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + if (json === null) + return .0; + if (json === "NaN") + return Number.NaN; + if (json === "Infinity") + return Number.POSITIVE_INFINITY; + if (json === "-Infinity") + return Number.NEGATIVE_INFINITY; + if (json === "") { + e = "empty string"; + break; + } + if (typeof json == "string" && json.trim().length !== json.length) { + e = "extra whitespace"; + break; + } + if (typeof json != "string" && typeof json != "number") { + break; + } + let float = Number(json); + if (Number.isNaN(float)) { + e = "not a number"; + break; + } + if (!Number.isFinite(float)) { + // infinity and -infinity are handled by string representation above, so this is an error + e = "too large or small"; + break; + } + if (type == reflection_info_1.ScalarType.FLOAT) + assert_1.assertFloat32(float); + return float; + // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + case reflection_info_1.ScalarType.UINT32: + if (json === null) + return 0; + let int32; + if (typeof json == "number") + int32 = json; + else if (json === "") + e = "empty string"; + else if (typeof json == "string") { + if (json.trim().length !== json.length) + e = "extra whitespace"; + else + int32 = Number(json); + } + if (int32 === undefined) + break; + if (type == reflection_info_1.ScalarType.UINT32) + assert_1.assertUInt32(int32); + else + assert_1.assertInt32(int32); + return int32; + // int64, fixed64, uint64: JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + if (json === null) + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); + if (typeof json != "number" && typeof json != "string") + break; + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.from(json), longType); + case reflection_info_1.ScalarType.FIXED64: + case reflection_info_1.ScalarType.UINT64: + if (json === null) + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); + if (typeof json != "number" && typeof json != "string") + break; + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.from(json), longType); + // bool: + case reflection_info_1.ScalarType.BOOL: + if (json === null) + return false; + if (typeof json !== "boolean") + break; + return json; + // string: + case reflection_info_1.ScalarType.STRING: + if (json === null) + return ""; + if (typeof json !== "string") { + e = "extra whitespace"; + break; + } + try { + encodeURIComponent(json); + } + catch (e) { + e = "invalid UTF8"; + break; + } + return json; + // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. + // Either standard or URL-safe base64 encoding with/without paddings are accepted. + case reflection_info_1.ScalarType.BYTES: + if (json === null || json === "") + return new Uint8Array(0); + if (typeof json !== 'string') + break; + return base64_1.base64decode(json); + } + } + catch (error) { + e = error.message; + } + this.assert(false, fieldName + (e ? " - " + e : ""), json); + } } +exports.ReflectionJsonReader = ReflectionJsonReader; -Glob.prototype._mark = function (p) { - return common.mark(this, p) -} -Glob.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) -} +/***/ }), -Glob.prototype.abort = function () { - this.aborted = true - this.emit('abort') -} +/***/ 68980: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -Glob.prototype.pause = function () { - if (!this.paused) { - this.paused = true - this.emit('pause') - } -} +"use strict"; -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]) - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ReflectionJsonWriter = void 0; +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. + * + * https://developers.google.com/protocol-buffers/docs/proto3#json + */ +class ReflectionJsonWriter { + constructor(info) { + var _a; + this.fields = (_a = info.fields) !== null && _a !== void 0 ? _a : []; } - 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]) - } + /** + * Converts the message to a JSON object, based on the field descriptors. + */ + write(message, options) { + const json = {}, source = message; + for (const field of this.fields) { + // field is not part of a oneof, simply write as is + if (!field.oneof) { + let jsonValue = this.field(field, source[field.localName], options); + if (jsonValue !== undefined) + json[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue; + continue; + } + // field is part of a oneof + const group = source[field.oneof]; + if (group.oneofKind !== field.localName) + continue; // not selected, skip + const opt = field.kind == 'scalar' || field.kind == 'enum' + ? Object.assign(Object.assign({}, options), { emitDefaultValues: true }) : options; + let jsonValue = this.field(field, group[field.localName], opt); + assert_1.assert(jsonValue !== undefined); + json[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue; + } + return json; + } + field(field, value, options) { + let jsonValue = undefined; + if (field.kind == 'map') { + assert_1.assert(typeof value == "object" && value !== null); + const jsonObj = {}; + switch (field.V.kind) { + case "scalar": + for (const [entryKey, entryValue] of Object.entries(value)) { + const val = this.scalar(field.V.T, entryValue, field.name, false, true); + assert_1.assert(val !== undefined); + jsonObj[entryKey.toString()] = val; // JSON standard allows only (double quoted) string as property key + } + break; + case "message": + const messageType = field.V.T(); + for (const [entryKey, entryValue] of Object.entries(value)) { + const val = this.message(messageType, entryValue, field.name, options); + assert_1.assert(val !== undefined); + jsonObj[entryKey.toString()] = val; // JSON standard allows only (double quoted) string as property key + } + break; + case "enum": + const enumInfo = field.V.T(); + for (const [entryKey, entryValue] of Object.entries(value)) { + assert_1.assert(entryValue === undefined || typeof entryValue == 'number'); + const val = this.enum(enumInfo, entryValue, field.name, false, true, options.enumAsInteger); + assert_1.assert(val !== undefined); + jsonObj[entryKey.toString()] = val; // JSON standard allows only (double quoted) string as property key + } + break; + } + if (options.emitDefaultValues || Object.keys(jsonObj).length > 0) + jsonValue = jsonObj; + } + else if (field.repeat) { + assert_1.assert(Array.isArray(value)); + const jsonArr = []; + switch (field.kind) { + case "scalar": + for (let i = 0; i < value.length; i++) { + const val = this.scalar(field.T, value[i], field.name, field.opt, true); + assert_1.assert(val !== undefined); + jsonArr.push(val); + } + break; + case "enum": + const enumInfo = field.T(); + for (let i = 0; i < value.length; i++) { + assert_1.assert(value[i] === undefined || typeof value[i] == 'number'); + const val = this.enum(enumInfo, value[i], field.name, field.opt, true, options.enumAsInteger); + assert_1.assert(val !== undefined); + jsonArr.push(val); + } + break; + case "message": + const messageType = field.T(); + for (let i = 0; i < value.length; i++) { + const val = this.message(messageType, value[i], field.name, options); + assert_1.assert(val !== undefined); + jsonArr.push(val); + } + break; + } + // add converted array to json output + if (options.emitDefaultValues || jsonArr.length > 0 || options.emitDefaultValues) + jsonValue = jsonArr; + } + else { + switch (field.kind) { + case "scalar": + jsonValue = this.scalar(field.T, value, field.name, field.opt, options.emitDefaultValues); + break; + case "enum": + jsonValue = this.enum(field.T(), value, field.name, field.opt, options.emitDefaultValues, options.enumAsInteger); + break; + case "message": + jsonValue = this.message(field.T(), value, field.name, options); + break; + } + } + return jsonValue; + } + /** + * Returns `null` as the default for google.protobuf.NullValue. + */ + enum(type, value, fieldName, optional, emitDefaultValues, enumAsInteger) { + if (type[0] == 'google.protobuf.NullValue') + return !emitDefaultValues && !optional ? undefined : null; + if (value === undefined) { + assert_1.assert(optional); + return undefined; + } + if (value === 0 && !emitDefaultValues && !optional) + // we require 0 to be default value for all enums + return undefined; + assert_1.assert(typeof value == 'number'); + assert_1.assert(Number.isInteger(value)); + if (enumAsInteger || !type[1].hasOwnProperty(value)) + // if we don't now the enum value, just return the number + return value; + if (type[2]) + // restore the dropped prefix + return type[2] + type[1][value]; + return type[1][value]; + } + message(type, value, fieldName, options) { + if (value === undefined) + return options.emitDefaultValues ? null : undefined; + return type.internalJsonWrite(value, options); + } + scalar(type, value, fieldName, optional, emitDefaultValues) { + if (value === undefined) { + assert_1.assert(optional); + return undefined; + } + const ed = emitDefaultValues || optional; + // noinspection FallThroughInSwitchStatementJS + switch (type) { + // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + if (value === 0) + return ed ? 0 : undefined; + assert_1.assertInt32(value); + return value; + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.UINT32: + if (value === 0) + return ed ? 0 : undefined; + assert_1.assertUInt32(value); + return value; + // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". + // Either numbers or strings are accepted. Exponent notation is also accepted. + case reflection_info_1.ScalarType.FLOAT: + assert_1.assertFloat32(value); + case reflection_info_1.ScalarType.DOUBLE: + if (value === 0) + return ed ? 0 : undefined; + assert_1.assert(typeof value == 'number'); + if (Number.isNaN(value)) + return 'NaN'; + if (value === Number.POSITIVE_INFINITY) + return 'Infinity'; + if (value === Number.NEGATIVE_INFINITY) + return '-Infinity'; + return value; + // string: + case reflection_info_1.ScalarType.STRING: + if (value === "") + return ed ? '' : undefined; + assert_1.assert(typeof value == 'string'); + return value; + // bool: + case reflection_info_1.ScalarType.BOOL: + if (value === false) + return ed ? false : undefined; + assert_1.assert(typeof value == 'boolean'); + return value; + // JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + assert_1.assert(typeof value == 'number' || typeof value == 'string' || typeof value == 'bigint'); + let ulong = pb_long_1.PbULong.from(value); + if (ulong.isZero() && !ed) + return undefined; + return ulong.toString(); + // JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + assert_1.assert(typeof value == 'number' || typeof value == 'string' || typeof value == 'bigint'); + let long = pb_long_1.PbLong.from(value); + if (long.isZero() && !ed) + return undefined; + return long.toString(); + // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. + // Either standard or URL-safe base64 encoding with/without paddings are accepted. + case reflection_info_1.ScalarType.BYTES: + assert_1.assert(value instanceof Uint8Array); + if (!value.byteLength) + return ed ? "" : undefined; + return base64_1.base64encode(value); + } } - } } +exports.ReflectionJsonWriter = ReflectionJsonWriter; -Glob.prototype._process = function (pattern, index, inGlobStar, cb) { - assert(this instanceof Glob) - assert(typeof cb === 'function') - - if (this.aborted) - return - - this._processing++ - if (this.paused) { - this._processQueue.push([pattern, index, inGlobStar, cb]) - return - } - - //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. +/***/ }), - // 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 +/***/ 24612: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null - break +"use strict"; - 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 - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.reflectionLongConvert = void 0; +const reflection_info_1 = __nccwpck_require__(21370); +/** + * Utility method to convert a PbLong or PbUlong to a JavaScript + * representation during runtime. + * + * Works with generated field information, `undefined` is equivalent + * to `STRING`. + */ +function reflectionLongConvert(long, type) { + switch (type) { + case reflection_info_1.LongType.BIGINT: + return long.toBigInt(); + case reflection_info_1.LongType.NUMBER: + return long.toNumber(); + default: + // case undefined: + // case LongType.STRING: + return long.toString(); + } +} +exports.reflectionLongConvert = reflectionLongConvert; - var remain = pattern.slice(n) - // 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 +/***/ }), - var abs = this._makeAbs(read) +/***/ 7869: +/***/ ((__unused_webpack_module, exports) => { - //if ignored, skip _processing - if (childrenIgnored(this, read)) - return cb() +"use strict"; - 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) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.reflectionMergePartial = void 0; +/** + * Copy partial data into the target message. + * + * If a singular scalar or enum field is present in the source, it + * replaces the field in the target. + * + * If a singular message field is present in the source, it is merged + * with the target field by calling mergePartial() of the responsible + * message type. + * + * If a repeated field is present in the source, its values replace + * all values in the target array, removing extraneous values. + * Repeated message fields are copied, not merged. + * + * If a map field is present in the source, entries are added to the + * target map, replacing entries with the same key. Entries that only + * exist in the target remain. Entries with message values are copied, + * not merged. + * + * Note that this function differs from protobuf merge semantics, + * which appends repeated fields. + */ +function reflectionMergePartial(info, target, source) { + let fieldValue, // the field value we are working with + input = source, output; // where we want our field value to go + for (let field of info.fields) { + let name = field.localName; + if (field.oneof) { + const group = input[field.oneof]; // this is the oneof`s group in the source + if ((group === null || group === void 0 ? void 0 : group.oneofKind) == undefined) { // the user is free to omit + continue; // we skip this field, and all other members too + } + fieldValue = group[name]; // our value comes from the the oneof group of the source + output = target[field.oneof]; // and our output is the oneof group of the target + output.oneofKind = group.oneofKind; // always update discriminator + if (fieldValue == undefined) { + delete output[name]; // remove any existing value + continue; // skip further work on field + } + } + else { + fieldValue = input[name]; // we are using the source directly + output = target; // we want our field value to go directly into the target + if (fieldValue == undefined) { + continue; // skip further work on field, existing value is used as is + } + } + if (field.repeat) + output[name].length = fieldValue.length; // resize target array to match source array + // now we just work with `fieldValue` and `output` to merge the value + switch (field.kind) { + case "scalar": + case "enum": + if (field.repeat) + for (let i = 0; i < fieldValue.length; i++) + output[name][i] = fieldValue[i]; // not a reference type + else + output[name] = fieldValue; // not a reference type + break; + case "message": + let T = field.T(); + if (field.repeat) + for (let i = 0; i < fieldValue.length; i++) + output[name][i] = T.create(fieldValue[i]); + else if (output[name] === undefined) + output[name] = T.create(fieldValue); // nothing to merge with + else + T.mergePartial(output[name], fieldValue); + break; + case "map": + // Map and repeated fields are simply overwritten, not appended or merged + switch (field.V.kind) { + case "scalar": + case "enum": + Object.assign(output[name], fieldValue); // elements are not reference types + break; + case "message": + let T = field.V.T(); + for (let k of Object.keys(fieldValue)) + output[name][k] = T.create(fieldValue[k]); + break; + } + break; + } + } } +exports.reflectionMergePartial = reflectionMergePartial; -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) - }) -} -Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { +/***/ }), - // if the abs isn't a dir, then nothing can match! - if (!entries) - return cb() +/***/ 74863: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // 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) - } - } +"use strict"; - //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.reflectionScalarDefault = void 0; +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. + */ +function reflectionScalarDefault(type, longType = reflection_info_1.LongType.STRING) { + switch (type) { + case reflection_info_1.ScalarType.BOOL: + return false; + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + return 0.0; + case reflection_info_1.ScalarType.BYTES: + return new Uint8Array(0); + case reflection_info_1.ScalarType.STRING: + return ""; + default: + // case ScalarType.INT32: + // case ScalarType.UINT32: + // case ScalarType.SINT32: + // case ScalarType.FIXED32: + // case ScalarType.SFIXED32: + return 0; + } +} +exports.reflectionScalarDefault = reflectionScalarDefault; - 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. +/***/ }), - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null) +/***/ 20903: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - if (prefix) { - if (prefix !== '/') - e = prefix + '/' + e - else - e = prefix + e - } +"use strict"; - 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() - } - - // 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 +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ReflectionTypeCheck = void 0; +const reflection_info_1 = __nccwpck_require__(21370); +const oneof_1 = __nccwpck_require__(78531); +// noinspection JSMethodCanBeStatic +class ReflectionTypeCheck { + constructor(info) { + var _a; + this.fields = (_a = info.fields) !== null && _a !== void 0 ? _a : []; + } + prepare() { + if (this.data) + return; + const req = [], known = [], oneofs = []; + for (let field of this.fields) { + if (field.oneof) { + if (!oneofs.includes(field.oneof)) { + oneofs.push(field.oneof); + req.push(field.oneof); + known.push(field.oneof); + } + } + else { + known.push(field.localName); + switch (field.kind) { + case "scalar": + case "enum": + if (!field.opt || field.repeat) + req.push(field.localName); + break; + case "message": + if (field.repeat) + req.push(field.localName); + break; + case "map": + req.push(field.localName); + break; + } + } + } + this.data = { req, known, oneofs: Object.values(oneofs) }; + } + /** + * Is the argument a valid message as specified by the + * reflection information? + * + * Checks all field types recursively. The `depth` + * specifies how deep into the structure the check will be. + * + * With a depth of 0, only the presence of fields + * is checked. + * + * With a depth of 1 or more, the field types are checked. + * + * With a depth of 2 or more, the members of map, repeated + * and message fields are checked. + * + * Message fields will be checked recursively with depth - 1. + * + * The number of map entries / repeated values being checked + * is < depth. + */ + is(message, depth, allowExcessProperties = false) { + if (depth < 0) + return true; + if (message === null || message === undefined || typeof message != 'object') + return false; + this.prepare(); + let keys = Object.keys(message), data = this.data; + // if a required field is missing in arg, this cannot be a T + if (keys.length < data.req.length || data.req.some(n => !keys.includes(n))) + return false; + if (!allowExcessProperties) { + // if the arg contains a key we dont know, this is not a literal T + if (keys.some(k => !data.known.includes(k))) + return false; + } + // "With a depth of 0, only the presence and absence of fields is checked." + // "With a depth of 1 or more, the field types are checked." + if (depth < 1) { + return true; + } + // check oneof group + for (const name of data.oneofs) { + const group = message[name]; + if (!oneof_1.isOneofGroup(group)) + return false; + if (group.oneofKind === undefined) + continue; + const field = this.fields.find(f => f.localName === group.oneofKind); + if (!field) + return false; // we found no field, but have a kind, something is wrong + if (!this.field(group[group.oneofKind], field, allowExcessProperties, depth)) + return false; + } + // check types + for (const field of this.fields) { + if (field.oneof !== undefined) + continue; + if (!this.field(message[field.localName], field, allowExcessProperties, depth)) + return false; + } + return true; + } + field(arg, field, allowExcessProperties, depth) { + let repeated = field.repeat; + switch (field.kind) { + case "scalar": + if (arg === undefined) + return field.opt; + if (repeated) + return this.scalars(arg, field.T, depth, field.L); + return this.scalar(arg, field.T, field.L); + case "enum": + if (arg === undefined) + return field.opt; + if (repeated) + return this.scalars(arg, reflection_info_1.ScalarType.INT32, depth); + return this.scalar(arg, reflection_info_1.ScalarType.INT32); + case "message": + if (arg === undefined) + return true; + if (repeated) + return this.messages(arg, field.T(), allowExcessProperties, depth); + return this.message(arg, field.T(), allowExcessProperties, depth); + case "map": + if (typeof arg != 'object' || arg === null) + return false; + if (depth < 2) + return true; + if (!this.mapKeys(arg, field.K, depth)) + return false; + switch (field.V.kind) { + case "scalar": + return this.scalars(Object.values(arg), field.V.T, depth, field.V.L); + case "enum": + return this.scalars(Object.values(arg), reflection_info_1.ScalarType.INT32, depth); + case "message": + return this.messages(Object.values(arg), field.V.T(), allowExcessProperties, depth); + } + break; + } + return true; + } + message(arg, type, allowExcessProperties, depth) { + if (allowExcessProperties) { + return type.isAssignable(arg, depth); + } + return type.is(arg, depth); + } + messages(arg, type, allowExcessProperties, depth) { + if (!Array.isArray(arg)) + return false; + if (depth < 2) + return true; + if (allowExcessProperties) { + for (let i = 0; i < arg.length && i < depth; i++) + if (!type.isAssignable(arg[i], depth - 1)) + return false; + } + else { + for (let i = 0; i < arg.length && i < depth; i++) + if (!type.is(arg[i], depth - 1)) + return false; + } + return true; + } + scalar(arg, type, longType) { + let argType = typeof arg; + switch (type) { + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + switch (longType) { + case reflection_info_1.LongType.BIGINT: + return argType == "bigint"; + case reflection_info_1.LongType.NUMBER: + return argType == "number" && !isNaN(arg); + default: + return argType == "string"; + } + case reflection_info_1.ScalarType.BOOL: + return argType == 'boolean'; + case reflection_info_1.ScalarType.STRING: + return argType == 'string'; + case reflection_info_1.ScalarType.BYTES: + return arg instanceof Uint8Array; + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + return argType == 'number' && !isNaN(arg); + default: + // case ScalarType.UINT32: + // case ScalarType.FIXED32: + // case ScalarType.INT32: + // case ScalarType.SINT32: + // case ScalarType.SFIXED32: + return argType == 'number' && Number.isInteger(arg); + } + } + scalars(arg, type, depth, longType) { + if (!Array.isArray(arg)) + return false; + if (depth < 2) + return true; + if (Array.isArray(arg)) + for (let i = 0; i < arg.length && i < depth; i++) + if (!this.scalar(arg[i], type, longType)) + return false; + return true; + } + mapKeys(map, type, depth) { + let keys = Object.keys(map); + switch (type) { + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + case reflection_info_1.ScalarType.UINT32: + return this.scalars(keys.slice(0, depth).map(k => parseInt(k)), type, depth); + case reflection_info_1.ScalarType.BOOL: + return this.scalars(keys.slice(0, depth).map(k => k == 'true' ? true : k == 'false' ? false : k), type, depth); + default: + return this.scalars(keys, type, depth, reflection_info_1.LongType.STRING); + } } - this._process([e].concat(remain), index, inGlobStar, cb) - } - cb() } +exports.ReflectionTypeCheck = ReflectionTypeCheck; -Glob.prototype._emitMatch = function (index, e) { - if (this.aborted) - return - - if (isIgnored(this, e)) - return - - if (this.paused) { - this._emitQueue.push([index, e]) - return - } - var abs = isAbsolute(e) ? e : this._makeAbs(e) +/***/ }), - if (this.mark) - e = this._mark(e) +/***/ 61659: +/***/ ((module, exports, __nccwpck_require__) => { - if (this.absolute) - e = abs +"use strict"; +/** + * @author Toru Nagashima + * See LICENSE file in root directory for full license. + */ - if (this.matches[index][e]) - return - if (this.nodir) { - var c = this.cache[abs] - if (c === 'DIR' || Array.isArray(c)) - return - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - this.matches[index][e] = true +var eventTargetShim = __nccwpck_require__(84697); - var st = this.statCache[abs] - if (st) - this.emit('stat', e, st) +/** + * The signal class. + * @see https://dom.spec.whatwg.org/#abortsignal + */ +class AbortSignal extends eventTargetShim.EventTarget { + /** + * AbortSignal cannot be constructed directly. + */ + constructor() { + super(); + throw new TypeError("AbortSignal cannot be constructed directly"); + } + /** + * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise. + */ + get aborted() { + const aborted = abortedFlags.get(this); + if (typeof aborted !== "boolean") { + throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this === null ? "null" : typeof this}`); + } + return aborted; + } +} +eventTargetShim.defineEventAttribute(AbortSignal.prototype, "abort"); +/** + * Create an AbortSignal object. + */ +function createAbortSignal() { + const signal = Object.create(AbortSignal.prototype); + eventTargetShim.EventTarget.call(signal); + abortedFlags.set(signal, false); + return signal; +} +/** + * Abort a given signal. + */ +function abortSignal(signal) { + if (abortedFlags.get(signal) !== false) { + return; + } + abortedFlags.set(signal, true); + signal.dispatchEvent({ type: "abort" }); +} +/** + * Aborted flag for each instances. + */ +const abortedFlags = new WeakMap(); +// Properties should be enumerable. +Object.defineProperties(AbortSignal.prototype, { + aborted: { enumerable: true }, +}); +// `toString()` should return `"[object AbortSignal]"` +if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, { + configurable: true, + value: "AbortSignal", + }); +} - this.emit('match', e) +/** + * The AbortController. + * @see https://dom.spec.whatwg.org/#abortcontroller + */ +class AbortController { + /** + * Initialize this controller. + */ + constructor() { + signals.set(this, createAbortSignal()); + } + /** + * Returns the `AbortSignal` object associated with this object. + */ + get signal() { + return getSignal(this); + } + /** + * Abort and signal to any observers that the associated activity is to be aborted. + */ + abort() { + abortSignal(getSignal(this)); + } +} +/** + * Associated signals. + */ +const signals = new WeakMap(); +/** + * Get the associated signal of a given controller. + */ +function getSignal(controller) { + const signal = signals.get(controller); + if (signal == null) { + throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? "null" : typeof controller}`); + } + return signal; +} +// Properties should be enumerable. +Object.defineProperties(AbortController.prototype, { + signal: { enumerable: true }, + abort: { enumerable: true }, +}); +if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(AbortController.prototype, Symbol.toStringTag, { + configurable: true, + value: "AbortController", + }); } -Glob.prototype._readdirInGlobStar = function (abs, cb) { - if (this.aborted) - return +exports.AbortController = AbortController; +exports.AbortSignal = AbortSignal; +exports["default"] = AbortController; - // follow all symlinked directories forever - // just proceed as if this is a non-globstar situation - if (this.follow) - return this._readdir(abs, false, cb) +module.exports = AbortController +module.exports.AbortController = module.exports["default"] = AbortController +module.exports.AbortSignal = AbortSignal +//# sourceMappingURL=abort-controller.js.map - var lstatkey = 'lstat\0' + abs - var self = this - var lstatcb = inflight(lstatkey, lstatcb_) - if (lstatcb) - self.fs.lstat(abs, lstatcb) +/***/ }), - function lstatcb_ (er, lstat) { - if (er && er.code === 'ENOENT') - return cb() +/***/ 81231: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var isSym = lstat && lstat.isSymbolicLink() - self.symlinks[abs] = isSym +/** + * archiver-utils + * + * Copyright (c) 2012-2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-archiver/blob/master/LICENSE-MIT + */ +var fs = __nccwpck_require__(77758); +var path = __nccwpck_require__(71017); + +var flatten = __nccwpck_require__(42394); +var difference = __nccwpck_require__(44031); +var union = __nccwpck_require__(11620); +var isPlainObject = __nccwpck_require__(46169); + +var glob = __nccwpck_require__(38211); + +var file = module.exports = {}; + +var pathSeparatorRe = /[\/\\]/g; + +// Process specified wildcard glob patterns or filenames against a +// callback, excluding and uniquing files in the result set. +var processPatterns = function(patterns, fn) { + // Filepaths to return. + var result = []; + // Iterate over flattened patterns array. + flatten(patterns).forEach(function(pattern) { + // If the first character is ! it should be omitted + var exclusion = pattern.indexOf('!') === 0; + // If the pattern is an exclusion, remove the ! + if (exclusion) { pattern = pattern.slice(1); } + // Find all matching files for this pattern. + var matches = fn(pattern); + if (exclusion) { + // If an exclusion, remove matching files. + result = difference(result, matches); + } else { + // Otherwise add matching files. + result = union(result, matches); + } + }); + return result; +}; - // 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) +// True if the file path exists. +file.exists = function() { + var filepath = path.join.apply(path, arguments); + return fs.existsSync(filepath); +}; + +// Return an array of all file paths that match the given wildcard patterns. +file.expand = function(...args) { + // If the first argument is an options object, save those options to pass + // into the File.prototype.glob.sync method. + var options = isPlainObject(args[0]) ? args.shift() : {}; + // Use the first argument if it's an Array, otherwise convert the arguments + // object to an array and use that. + var patterns = Array.isArray(args[0]) ? args[0] : args; + // Return empty set if there are no patterns or filepaths. + if (patterns.length === 0) { return []; } + // Return all matching filepaths. + var matches = processPatterns(patterns, function(pattern) { + // Find all matching files for this pattern. + return glob.sync(pattern, options); + }); + // Filter result set? + if (options.filter) { + matches = matches.filter(function(filepath) { + filepath = path.join(options.cwd || '', filepath); + try { + if (typeof options.filter === 'function') { + return options.filter(filepath); + } else { + // If the file is of the right type and exists, this should work. + return fs.statSync(filepath)[options.filter](); + } + } catch(e) { + // Otherwise, it's probably not the right type. + return false; + } + }); } -} - -Glob.prototype._readdir = function (abs, inGlobStar, cb) { - if (this.aborted) - return - - cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) - if (!cb) - return + return matches; +}; + +// Build a multi task "files" object dynamically. +file.expandMapping = function(patterns, destBase, options) { + options = Object.assign({ + rename: function(destBase, destPath) { + return path.join(destBase || '', destPath); + } + }, options); + var files = []; + var fileByDest = {}; + // Find all files matching pattern, using passed-in options. + file.expand(options, patterns).forEach(function(src) { + var destPath = src; + // Flatten? + if (options.flatten) { + destPath = path.basename(destPath); + } + // Change the extension? + if (options.ext) { + destPath = destPath.replace(/(\.[^\/]*)?$/, options.ext); + } + // Generate destination filename. + var dest = options.rename(destBase, destPath, options); + // Prepend cwd to src path if necessary. + if (options.cwd) { src = path.join(options.cwd, src); } + // Normalize filepaths to be unix-style. + dest = dest.replace(pathSeparatorRe, '/'); + src = src.replace(pathSeparatorRe, '/'); + // Map correct src path to dest path. + if (fileByDest[dest]) { + // If dest already exists, push this src onto that dest's src array. + fileByDest[dest].src.push(src); + } else { + // Otherwise create a new src-dest file mapping object. + files.push({ + src: [src], + dest: dest, + }); + // And store a reference for later use. + fileByDest[dest] = files[files.length - 1]; + } + }); + return files; +}; - //console.error('RD %j %j', +inGlobStar, abs) - if (inGlobStar && !ownProp(this.symlinks, abs)) - return this._readdirInGlobStar(abs, cb) +// reusing bits of grunt's multi-task source normalization +file.normalizeFilesArray = function(data) { + var files = []; - if (ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (!c || c === 'FILE') - return cb() + data.forEach(function(obj) { + var prop; + if ('src' in obj || 'dest' in obj) { + files.push(obj); + } + }); - if (Array.isArray(c)) - return cb(null, c) + if (files.length === 0) { + return []; } - 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) - } -} + files = _(files).chain().forEach(function(obj) { + if (!('src' in obj) || !obj.src) { return; } + // Normalize .src properties to flattened array. + if (Array.isArray(obj.src)) { + obj.src = flatten(obj.src); + } else { + obj.src = [obj.src]; + } + }).map(function(obj) { + // Build options object, removing unwanted properties. + var expandOptions = Object.assign({}, obj); + delete expandOptions.src; + delete expandOptions.dest; + + // Expand file mappings. + if (obj.expand) { + return file.expandMapping(obj.src, obj.dest, expandOptions).map(function(mapObj) { + // Copy obj properties to result. + var result = Object.assign({}, obj); + // Make a clone of the orig obj available. + result.orig = Object.assign({}, obj); + // Set .src and .dest, processing both as templates. + result.src = mapObj.src; + result.dest = mapObj.dest; + // Remove unwanted properties. + ['expand', 'cwd', 'flatten', 'rename', 'ext'].forEach(function(prop) { + delete result[prop]; + }); + return result; + }); + } -Glob.prototype._readdirEntries = function (abs, entries, cb) { - if (this.aborted) - return + // Copy obj properties to result, adding an .orig property. + var result = Object.assign({}, obj); + // Make a clone of the orig obj available. + result.orig = Object.assign({}, obj); - // 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 ('src' in result) { + // Expose an expand-on-demand getter method as .src. + Object.defineProperty(result, 'src', { + enumerable: true, + get: function fn() { + var src; + if (!('result' in fn)) { + src = obj.src; + // If src is an array, flatten it. Otherwise, make it into an array. + src = Array.isArray(src) ? flatten(src) : [src]; + // Expand src files, memoizing result. + fn.result = file.expand(expandOptions, src); + } + return fn.result; + } + }); } - } - this.cache[abs] = entries - return cb(null, entries) -} + if ('dest' in result) { + result.dest = obj.dest; + } -Glob.prototype._readdirError = function (f, er, cb) { - if (this.aborted) - return + return result; + }).flatten().value(); - // 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 + return files; +}; - 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 cb() -} +/***/ 82072: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -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) - }) -} +/** + * archiver-utils + * + * Copyright (c) 2015 Chris Talkington. + * Licensed under the MIT license. + * https://github.com/archiverjs/archiver-utils/blob/master/LICENSE + */ +var fs = __nccwpck_require__(77758); +var path = __nccwpck_require__(71017); +var isStream = __nccwpck_require__(41554); +var lazystream = __nccwpck_require__(12084); +var normalizePath = __nccwpck_require__(55388); +var defaults = __nccwpck_require__(3508); +var Stream = (__nccwpck_require__(12781).Stream); +var PassThrough = (__nccwpck_require__(45193).PassThrough); -Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { - //console.error('pgs2', prefix, remain[0], entries) +var utils = module.exports = {}; +utils.file = __nccwpck_require__(81231); - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return cb() +utils.collectStream = function(source, callback) { + var collection = []; + var size = 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) + source.on('error', callback); - // the noGlobStar pattern exits the inGlobStar state - this._process(noGlobStar, index, false, cb) + source.on('data', function(chunk) { + collection.push(chunk); + size += chunk.length; + }); - var isSym = this.symlinks[abs] - var len = entries.length + source.on('end', function() { + var buf = Buffer.alloc(size); + var offset = 0; - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) - return cb() + collection.forEach(function(data) { + data.copy(buf, offset); + offset += data.length; + }); - for (var i = 0; i < len; i++) { - var e = entries[i] - if (e.charAt(0) === '.' && !this.dot) - continue + callback(null, buf); + }); +}; - // these two cases enter the inGlobStar state - var instead = gspref.concat(entries[i], remainWithoutGlobStar) - this._process(instead, index, true, cb) +utils.dateify = function(dateish) { + dateish = dateish || new Date(); - var below = gspref.concat(entries[i], remain) - this._process(below, index, true, cb) + if (dateish instanceof Date) { + dateish = dateish; + } else if (typeof dateish === 'string') { + dateish = new Date(dateish); + } else { + dateish = new Date(); } - cb() -} + return dateish; +}; -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 is slightly different from lodash version +utils.defaults = function(object, source, guard) { + var args = arguments; + args[0] = args[0] || {}; - //console.error('ps2', prefix, exists) + return defaults(...args); +}; - if (!this.matches[index]) - this.matches[index] = Object.create(null) +utils.isStream = function(source) { + return isStream(source); +}; - // If it doesn't exist, then just mark the lack of results - if (!exists) - return cb() +utils.lazyReadStream = function(filepath) { + return new lazystream.Readable(function() { + return fs.createReadStream(filepath); + }); +}; - 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 += '/' - } +utils.normalizeInputSource = function(source) { + if (source === null) { + return Buffer.alloc(0); + } else if (typeof source === 'string') { + return Buffer.from(source); + } else if (utils.isStream(source)) { + // Always pipe through a PassThrough stream to guarantee pausing the stream if it's already flowing, + // since it will only be processed in a (distant) future iteration of the event loop, and will lose + // data if already flowing now. + return source.pipe(new PassThrough()); } - if (process.platform === 'win32') - prefix = prefix.replace(/\\/g, '/') - - // Mark this as a match - this._emitMatch(index, prefix) - cb() -} - -// Returns either 'DIR', 'FILE', or false -Glob.prototype._stat = function (f, cb) { - var abs = this._makeAbs(f) - var needDir = f.slice(-1) === '/' - - if (f.length > this.maxLength) - return cb() + return source; +}; - if (!this.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs] +utils.sanitizePath = function(filepath) { + return normalizePath(filepath, false).replace(/^\w+:/, '').replace(/^(\.\.\/|\/)+/, ''); +}; - if (Array.isArray(c)) - c = 'DIR' +utils.trailingSlashIt = function(str) { + return str.slice(-1) !== '/' ? str + '/' : str; +}; - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return cb(null, c) +utils.unixifyPath = function(filepath) { + return normalizePath(filepath, false).replace(/^\w+:/, ''); +}; - if (needDir && c === 'FILE') - return cb() +utils.walkdir = function(dirpath, base, callback) { + var results = []; - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. + if (typeof base === 'function') { + callback = base; + base = dirpath; } - 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) - } - } + fs.readdir(dirpath, function(err, list) { + var i = 0; + var file; + var filepath; - 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) + if (err) { + return callback(err); } - } -} -Glob.prototype._stat2 = function (f, abs, er, stat, cb) { - if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { - this.statCache[abs] = false - return cb() - } + (function next() { + file = list[i++]; - var needDir = f.slice(-1) === '/' - this.statCache[abs] = stat + if (!file) { + return callback(null, results); + } - if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) - return cb(null, false, stat) + filepath = path.join(dirpath, file); - var c = true - if (stat) - c = stat.isDirectory() ? 'DIR' : 'FILE' - this.cache[abs] = this.cache[abs] || c + fs.stat(filepath, function(err, stats) { + results.push({ + path: filepath, + relative: path.relative(base, filepath).replace(/\\/g, '/'), + stats: stats + }); - if (needDir && c === 'FILE') - return cb() + if (stats && stats.isDirectory()) { + utils.walkdir(filepath, base, function(err, res) { + if(err){ + return callback(err); + } - return cb(null, c, stat) -} + res.forEach(function(dirEntry) { + results.push(dirEntry); + }); + + next(); + }); + } else { + next(); + } + }); + })(); + }); +}; /***/ }), -/***/ 9859: +/***/ 43084: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = globSync -globSync.GlobSync = GlobSync - -var rp = __nccwpck_require__(2287) -var minimatch = __nccwpck_require__(5806) -var Minimatch = minimatch.Minimatch -var Glob = (__nccwpck_require__(7004).Glob) -var util = __nccwpck_require__(3837) -var path = __nccwpck_require__(1017) -var assert = __nccwpck_require__(9491) -var isAbsolute = __nccwpck_require__(3985) -var common = __nccwpck_require__(4063) -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') - - 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') +/** + * 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); - if (!(this instanceof GlobSync)) - return new GlobSync(pattern, options) +var formats = {}; - setopts(this, pattern, options) +/** + * 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); +}; - if (this.noprocess) - return this +/** + * 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)); - 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) + return instance; + } else { + throw new Error('create(' + format + '): format not registered'); } - this._finish() -} +}; -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 - } - } - }) +/** + * 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'); } - common.finish(this) -} - - -GlobSync.prototype._process = function (pattern, index, inGlobStar) { - assert.ok(this instanceof GlobSync) - // Get the first [n] parts of pattern that are all strings. - var n = 0 - while (typeof pattern[n] === 'string') { - n ++ + if (typeof module !== 'function') { + throw new Error('register(' + format + '): format module invalid'); } - // now n is the index of the first one that is *not* a string. - // 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 + if (typeof module.prototype.append !== 'function' || typeof module.prototype.finalize !== 'function') { + throw new Error('register(' + format + '): format module missing methods'); + } - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null - break + formats[format] = module; +}; - 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 +/** + * 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; +}; - var remain = pattern.slice(n) +vending.registerFormat('zip', __nccwpck_require__(8987)); +vending.registerFormat('tar', __nccwpck_require__(33614)); +vending.registerFormat('json', __nccwpck_require__(99827)); - // 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 +module.exports = vending; - var abs = this._makeAbs(read) +/***/ }), - //if ignored, skip processing - if (childrenIgnored(this, read)) - return +/***/ 35010: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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) -} +/** + * 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); +var inherits = (__nccwpck_require__(73837).inherits); +var ArchiverError = __nccwpck_require__(13143); +var Transform = (__nccwpck_require__(45193).Transform); -GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { - var entries = this._readdir(abs, inGlobStar) +var win32 = process.platform === 'win32'; - // if the abs isn't a dir, then nothing can match! - if (!entries) - return +/** + * @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); + } - // 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) - } + if (typeof format !== 'string') { + options = format; + format = 'zip'; } - var len = matchedEntries.length - // If there are no matched entries, then nothing matches. - if (len === 0) - return + options = this.options = util.defaults(options, { + highWaterMark: 1024 * 1024, + statConcurrency: 4 + }); - // 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. + Transform.call(this, options); - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null) + this._format = false; + this._module = false; + this._pending = 0; + this._pointer = 0; - 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._entriesCount = 0; + this._entriesProcessedCount = 0; + this._fsEntriesTotalBytes = 0; + this._fsEntriesProcessedBytes = 0; - 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 - } + this._queue = async.queue(this._onQueueTask.bind(this), 1); + this._queue.drain(this._onQueueDrain.bind(this)); - // 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) - } -} + this._statQueue = async.queue(this._onStatQueueTask.bind(this), options.statConcurrency); + this._statQueue.drain(this._onQueueDrain.bind(this)); + this._state = { + aborted: false, + finalize: false, + finalizing: false, + finalized: false, + modulePiped: false + }; -GlobSync.prototype._emitMatch = function (index, e) { - if (isIgnored(this, e)) - return + this._streams = []; +}; - var abs = this._makeAbs(e) +inherits(Archiver, Transform); - if (this.mark) - e = this._mark(e) +/** + * Internal logic for `abort`. + * + * @private + * @return void + */ +Archiver.prototype._abort = function() { + this._state.aborted = true; + this._queue.kill(); + this._statQueue.kill(); - if (this.absolute) { - e = abs + if (this._queue.idle()) { + this._shutdown(); } +}; - if (this.matches[index][e]) - return - - if (this.nodir) { - var c = this.cache[abs] - if (c === 'DIR' || Array.isArray(c)) - return - } +/** + * 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 || {}; - this.matches[index][e] = true + var task = { + source: null, + filepath: filepath + }; - if (this.stat) - this._stat(e) -} + if (!data.name) { + data.name = filepath; + } + data.sourcePath = filepath; + task.data = data; + this._entriesCount++; -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) + 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; + } - 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 + this._queue.push(task); } + } else { + this._statQueue.push(task); } +}; - 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) +/** + * Internal logic for `finalize`. + * + * @private + * @return void + */ +Archiver.prototype._finalize = function() { + if (this._state.finalizing || this._state.finalized || this._state.aborted) { + return; + } - return entries -} + this._state.finalizing = true; -GlobSync.prototype._readdir = function (abs, inGlobStar) { - var entries + this._moduleFinalize(); - if (inGlobStar && !ownProp(this.symlinks, abs)) - return this._readdirInGlobStar(abs) + this._state.finalizing = false; + this._state.finalized = true; +}; - if (ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (!c || c === 'FILE') - return null +/** + * 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 (Array.isArray(c)) - return c + if (this._state.finalize && this._pending === 0 && this._queue.idle() && this._statQueue.idle()) { + this._finalize(); + return true; } - try { - return this._readdirEntries(abs, this.fs.readdirSync(abs)) - } catch (er) { - this._readdirError(abs, er) - return null + return false; +}; + +/** + * 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; } -} -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 + this._module.append(source, data, function(err) { + this._task = null; + + if (this._state.aborted) { + this._shutdown(); + return; } - } - this.cache[abs] = entries + if (err) { + this.emit('error', err); + setImmediate(callback); + return; + } - // mark and cache dir-ness - return entries -} + /** + * 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++; -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 + if (data.stats && data.stats.size) { + this._fsEntriesProcessedBytes += data.stats.size; + } + + /** + * @event Archiver#progress + * @type {ProgressData} + */ + this.emit('progress', { + entries: { + total: this._entriesCount, + processed: this._entriesProcessedCount + }, + fs: { + totalBytes: this._fsEntriesTotalBytes, + processedBytes: this._fsEntriesProcessedBytes } - break + }); - case 'ENOENT': // not terribly unusual - case 'ELOOP': - case 'ENAMETOOLONG': - case 'UNKNOWN': - this.cache[this._makeAbs(f)] = false - break + setImmediate(callback); + }.bind(this)); +}; - 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 +/** + * 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')); } -} +}; -GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { +/** + * 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; +}; - var entries = this._readdir(abs, inGlobStar) +/** + * 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; + } - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return + return this._module.supports[key]; +}; - // 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) +/** + * Unpipes the module from our internal stream. + * + * @private + * @return void + */ +Archiver.prototype._moduleUnpipe = function() { + this._module.unpipe(this); + this._state.modulePiped = false; +}; - // the noGlobStar pattern exits the inGlobStar state - this._process(noGlobStar, index, 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 + }); - var len = entries.length - var isSym = this.symlinks[abs] + if (stats && data.stats === false) { + data.stats = stats; + } - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) - return + var isDir = data.type === 'directory'; - for (var i = 0; i < len; i++) { - var e = entries[i] - if (e.charAt(0) === '.' && !this.dot) - continue + if (data.name) { + if (typeof data.prefix === 'string' && '' !== data.prefix) { + data.name = data.prefix + '/' + data.name; + data.prefix = null; + } - // these two cases enter the inGlobStar state - var instead = gspref.concat(entries[i], remainWithoutGlobStar) - this._process(instead, index, true) + data.name = util.sanitizePath(data.name); - var below = gspref.concat(entries[i], remain) - this._process(below, index, true) + if (data.type !== 'symlink' && data.name.slice(-1) === '/') { + isDir = true; + data.type = 'directory'; + } else if (isDir) { + data.name += '/'; + } } -} - -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) - - if (!this.matches[index]) - this.matches[index] = Object.create(null) - // If it doesn't exist, then just mark the lack of results - if (!exists) - return - - if (prefix && isAbsolute(prefix) && !this.nomount) { - var trail = /[\/\\]$/.test(prefix) - if (prefix.charAt(0) === '/') { - prefix = path.join(this.root, prefix) + // 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 { - prefix = path.resolve(this.root, prefix) - if (trail) - prefix += '/' + data.mode = data.stats.mode & 4095; } + + // 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; } - if (process.platform === 'win32') - prefix = prefix.replace(/\\/g, '/') + if (data.stats && data.date === null) { + data.date = data.stats.mtime; + } else { + data.date = util.dateify(data.date); + } - // Mark this as a match - this._emitMatch(index, prefix) -} + return data; +}; -// Returns either 'DIR', 'FILE', or false -GlobSync.prototype._stat = function (f) { - var abs = this._makeAbs(f) - var needDir = f.slice(-1) === '/' +/** + * 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); +}; - if (f.length > this.maxLength) - return false +/** + * 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.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs] + if (this._state.finalize && this._pending === 0 && this._queue.idle() && this._statQueue.idle()) { + this._finalize(); + } +}; - if (Array.isArray(c)) - c = 'DIR' +/** + * 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(); + } + callback(); + } - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return c + if (this._state.finalizing || this._state.finalized || this._state.aborted) { + fullCallback(); + return; + } - if (needDir && c === 'FILE') - return false + this._task = task; + this._moduleAppend(task.source, task.data, fullCallback); +}; - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. +/** + * 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; } - 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 - } + fs.lstat(task.filepath, function(err, stats) { + if (this._state.aborted) { + setImmediate(callback); + return; } - if (lstat && lstat.isSymbolicLink()) { - try { - stat = this.fs.statSync(abs) - } catch (er) { - stat = lstat - } - } else { - stat = lstat + if (err) { + this._entriesCount--; + + /** + * @event Archiver#warning + * @type {ErrorData} + */ + this.emit('warning', err); + setImmediate(callback); + return; } - } - this.statCache[abs] = stat + task = this._updateQueueTaskWithStats(task, stats); - var c = true - if (stat) - c = stat.isDirectory() ? 'DIR' : 'FILE' - - this.cache[abs] = this.cache[abs] || c + if (task) { + if (stats.size) { + this._fsEntriesTotalBytes += stats.size; + } - if (needDir && c === 'FILE') - return false + this._queue.push(task); + } - return c -} + setImmediate(callback); + }.bind(this)); +}; -GlobSync.prototype._mark = function (p) { - return common.mark(this, p) -} +/** + * Unpipes the module and ends our internal stream. + * + * @private + * @return void + */ +Archiver.prototype._shutdown = function() { + this._moduleUnpipe(); + this.end(); +}; -GlobSync.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) -} +/** + * 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; + } + callback(null, chunk); +}; -/***/ }), +/** + * 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)); + } -/***/ 5950: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return null; + } -var wrappy = __nccwpck_require__(4025) -var reqs = Object.create(null) -var once = __nccwpck_require__(4410) + task.data = this._normalizeEntryData(task.data, stats); -module.exports = wrappy(inflight) + return task; +}; -function inflight (key, cb) { - if (reqs[key]) { - reqs[key].push(cb) - return null - } else { - reqs[key] = [cb] - return makeres(key) +/** + * 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; } -} - -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] - } - } - }) -} + this._abort(); -function slice (args) { - var length = args.length - var array = [] + return this; +}; - for (var i = 0; i < length; i++) array[i] = args[i] - return array -} +/** + * 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; + } + data = this._normalizeEntryData(data); -/***/ }), + if (typeof data.name !== 'string' || data.name.length === 0) { + this.emit('error', new ArchiverError('ENTRYNAMEREQUIRED')); + return this; + } -/***/ 7187: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (data.type === 'directory' && !this._moduleSupports('directory')) { + this.emit('error', new ArchiverError('DIRECTORYNOTSUPPORTED', { name: data.name })); + return this; + } -try { - var util = __nccwpck_require__(3837); - /* istanbul ignore next */ - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; -} catch (e) { - /* istanbul ignore next */ - module.exports = __nccwpck_require__(7956); -} + source = util.normalizeInputSource(source); + 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._entriesCount++; + this._queue.push({ + data: data, + source: source + }); -/***/ 7956: -/***/ ((module) => { + return this; +}; -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 - } +/** + * 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++; -/***/ 646: -/***/ ((__unused_webpack_module, exports) => { + if (destpath === false) { + destpath = ''; + } else if (typeof destpath !== 'string'){ + destpath = dirpath; + } -"use strict"; + var dataFunction = false; + if (typeof data === 'function') { + dataFunction = data; + data = {}; + } else if (typeof data !== 'object') { + data = {}; + } + var globOptions = { + stat: true, + dot: true + }; -Object.defineProperty(exports, "__esModule", ({ value: true })); + function onGlobEnd() { + this._pending--; + this._maybeFinalize(); + } -/*! - * is-plain-object - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ + function onGlobError(err) { + this.emit('error', err); + } -function isObject(o) { - return Object.prototype.toString.call(o) === '[object Object]'; -} + function onGlobMatch(match){ + globber.pause(); -function isPlainObject(o) { - var ctor,prot; + 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); - if (isObject(o) === false) return false; + try { + if (dataFunction) { + entryData = dataFunction(entryData); - // If has modified constructor - ctor = o.constructor; - if (ctor === undefined) return true; + if (entryData === false) { + ignoreMatch = true; + } else if (typeof entryData !== 'object') { + throw new ArchiverError('DIRECTORYFUNCTIONINVALIDDATA', { dirpath: dirpath }); + } + } + } catch(e) { + this.emit('error', e); + return; + } - // If has modified prototype - prot = ctor.prototype; - if (isObject(prot) === false) return false; + if (ignoreMatch) { + globber.resume(); + return; + } - // If constructor does not have an Object-specific method - if (prot.hasOwnProperty('isPrototypeOf') === false) { - return false; + this._append(match.absolute, entryData); } - // Most likely a plain Object - return true; -} + var globber = glob(dirpath, globOptions); + globber.on('error', onGlobError.bind(this)); + globber.on('match', onGlobMatch.bind(this)); + globber.on('end', onGlobEnd.bind(this)); -exports.isPlainObject = isPlainObject; + return this; +}; +/** + * 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; + } -/***/ 7043: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this._append(filepath, data); -/*! - * mime-db - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015-2022 Douglas Christopher Wilson - * MIT Licensed - */ + return this; +}; /** - * Module exports. + * 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++; -module.exports = __nccwpck_require__(3765) + options = util.defaults(options, { + stat: true, + pattern: pattern + }); + function onGlobEnd() { + this._pending--; + this._maybeFinalize(); + } -/***/ }), + function onGlobError(err) { + this.emit('error', err); + } -/***/ 4826: -/***/ ((__unused_webpack_module, 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"; -/*! - * mime-types - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ + this._append(match.absolute, entryData); + } + 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; +}; /** - * Module dependencies. - * @private + * 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); + } -var db = __nccwpck_require__(7043) -var extname = (__nccwpck_require__(1017).extname) + if (this._state.finalize) { + var finalizingError = new ArchiverError('FINALIZING'); + this.emit('error', finalizingError); + return Promise.reject(finalizingError); + } -/** - * Module variables. - * @private - */ + this._state.finalize = true; -var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ -var TEXT_TYPE_REGEXP = /^text\//i + if (this._pending === 0 && this._queue.idle() && this._statQueue.idle()) { + this._finalize(); + } -/** - * Module exports. - * @public - */ + var self = this; -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) + return new Promise(function(resolve, reject) { + var errored; -// Populate the extensions/types maps -populateMaps(exports.extensions, exports.types) + self._module.on('end', function() { + if (!errored) { + resolve(); + } + }) + + self._module.on('error', function(err) { + errored = true; + reject(err); + }) + }) +}; /** - * Get the default charset for a MIME type. + * Sets the module format name used for archiving. * - * @param {string} type - * @return {boolean|string} + * @param {String} format The name of the format. + * @return {this} */ - -function charset (type) { - if (!type || typeof type !== 'string') { - return false - } - - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type) - var mime = match && db[match[1].toLowerCase()] - - if (mime && mime.charset) { - return mime.charset +Archiver.prototype.setFormat = function(format) { + if (this._format) { + this.emit('error', new ArchiverError('FORMATSET')); + return this; } - // default text/* to utf-8 - if (match && TEXT_TYPE_REGEXP.test(match[1])) { - return 'UTF-8' - } + this._format = format; - return false -} + return this; +}; /** - * Create a full Content-Type header given a MIME type or extension. + * Sets the module used for archiving. * - * @param {string} str - * @return {boolean|string} + * @param {Function} module The function for archiver to interact with. + * @return {this} */ - -function contentType (str) { - // TODO: should this even be in this module? - if (!str || typeof str !== 'string') { - return false +Archiver.prototype.setModule = function(module) { + if (this._state.aborted) { + this.emit('error', new ArchiverError('ABORTED')); + return this; } - var mime = str.indexOf('/') === -1 - ? exports.lookup(str) - : str - - if (!mime) { - return false + if (this._state.module) { + this.emit('error', new ArchiverError('MODULESET')); + return this; } - // TODO: use content-type or other module - if (mime.indexOf('charset') === -1) { - var charset = exports.charset(mime) - if (charset) mime += '; charset=' + charset.toLowerCase() - } + this._module = module; + this._modulePipe(); - return mime -} + return this; +}; /** - * Get the default extension for a MIME type. + * Appends a symlink to the instance. * - * @param {string} type - * @return {boolean|string} + * 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; + } -function extension (type) { - if (!type || typeof type !== 'string') { - return false + if (typeof filepath !== 'string' || filepath.length === 0) { + this.emit('error', new ArchiverError('SYMLINKFILEPATHREQUIRED')); + return this; } - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type) + if (typeof target !== 'string' || target.length === 0) { + this.emit('error', new ArchiverError('SYMLINKTARGETREQUIRED', { filepath: filepath })); + return this; + } - // get extensions - var exts = match && exports.extensions[match[1].toLowerCase()] + if (!this._moduleSupports('symlink')) { + this.emit('error', new ArchiverError('SYMLINKNOTSUPPORTED', { filepath: filepath })); + return this; + } - if (!exts || !exts.length) { - return false + var data = {}; + data.type = 'symlink'; + data.name = filepath.replace(/\\/g, '/'); + data.linkname = target.replace(/\\/g, '/'); + data.sourceType = 'buffer'; + + if (typeof mode === "number") { + data.mode = mode; } - return exts[0] -} + this._entriesCount++; + this._queue.push({ + data: data, + source: Buffer.concat([]) + }); + + return this; +}; /** - * Lookup the MIME type for a file path/extension. + * Returns the current length (in bytes) that has been emitted. * - * @param {string} path - * @return {boolean|string} + * @return {Number} */ +Archiver.prototype.pointer = function() { + return this._pointer; +}; -function lookup (path) { - if (!path || typeof path !== 'string') { - return false - } - - // get the extension ("ext" or ".ext" or full path) - var extension = extname('x.' + path) - .toLowerCase() - .substr(1) - - if (!extension) { - return false - } +/** + * 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; +}; - return exports.types[extension] || false -} +module.exports = Archiver; /** - * Populate the extensions and types maps. - * @private + * @typedef {Object} CoreOptions + * @global + * @property {Number} [statConcurrency=4] Sets the number of workers used to + * process the internal fs stat queue. */ -function populateMaps (extensions, types) { - // source preference (least -> most) - var preference = ['nginx', 'apache', undefined, 'iana'] +/** + * @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` + */ - Object.keys(db).forEach(function forEachMimeType (type) { - var mime = db[type] - var exts = mime.extensions +/** + * @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. + */ - if (!exts || !exts.length) { - return - } +/** + * @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). + */ - // mime -> extensions - extensions[type] = exts +/** + * @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) + */ - // extension -> mime - for (var i = 0; i < exts.length; i++) { - var extension = exts[i] - if (types[extension]) { - var from = preference.indexOf(db[types[extension]].source) - var to = preference.indexOf(mime.source) +/***/ }), - if (types[extension] !== 'application/octet-stream' && - (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { - // skip the remapping - continue - } - } +/***/ 13143: +/***/ ((module, exports, __nccwpck_require__) => { - // set the extension -> mime - types[extension] = type - } - }) +/** + * Archiver Core + * + * @ignore + * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} + * @copyright (c) 2012-2014 Chris Talkington, contributors. + */ + +var util = __nccwpck_require__(73837); + +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 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; } +util.inherits(ArchiverError, Error); + +exports = module.exports = ArchiverError; /***/ }), -/***/ 5806: +/***/ 99827: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = minimatch -minimatch.Minimatch = Minimatch - -var path = (function () { try { return __nccwpck_require__(1017) } catch (e) {}}()) || { - sep: '/' -} -minimatch.sep = path.sep +/** + * 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__(45193).Transform); -var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} -var expand = __nccwpck_require__(3164) +var crc32 = __nccwpck_require__(54119); +var util = __nccwpck_require__(82072); -var plTypes = { - '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, - '?': { open: '(?:', close: ')?' }, - '+': { open: '(?:', close: ')+' }, - '*': { open: '(?:', close: ')*' }, - '@': { open: '(?:', close: ')' } -} +/** + * @constructor + * @param {(JsonOptions|TransformOptions)} options + */ +var Json = function(options) { + if (!(this instanceof Json)) { + return new Json(options); + } -// any single thing other than / -// don't need to escape / when using new RegExp() -var qmark = '[^/]' + options = this.options = util.defaults(options, {}); -// * => any number of characters -var star = qmark + '*?' + Transform.call(this, options); -// ** 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})($|\\\/)).)*?' + this.supports = { + directory: true, + symlink: true + }; -// not a ^ or / followed by a dot, -// followed by anything, any number of times. -var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' + this.files = []; +}; -// characters that need to be escaped in RegExp. -var reSpecials = charSet('().*{}+?[]^$\\!') +inherits(Json, Transform); -// "abc" -> { a:true, b:true, c:true } -function charSet (s) { - return s.split('').reduce(function (set, c) { - set[c] = true - return set - }, {}) -} +/** + * [_transform description] + * + * @private + * @param {Buffer} chunk + * @param {String} encoding + * @param {Function} callback + * @return void + */ +Json.prototype._transform = function(chunk, encoding, callback) { + callback(null, chunk); +}; -// normalizes slashes. -var slashSplit = /\/+/ +/** + * [_writeStringified description] + * + * @private + * @return void + */ +Json.prototype._writeStringified = function() { + var fileString = JSON.stringify(this.files); + this.write(fileString); +}; -minimatch.filter = filter -function filter (pattern, options) { - options = options || {} - return function (p, i, list) { - return minimatch(p, pattern, options) - } -} +/** + * [append description] + * + * @param {(Buffer|Stream)} source + * @param {EntryData} data + * @param {Function} callback + * @return void + */ +Json.prototype.append = function(source, data, callback) { + var self = this; -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 -} + data.crc32 = 0; -minimatch.defaults = function (def) { - if (!def || typeof def !== 'object' || !Object.keys(def).length) { - return minimatch - } + function onend(err, sourceBuffer) { + if (err) { + callback(err); + return; + } - var orig = minimatch + data.size = sourceBuffer.length || 0; + data.crc32 = crc32.unsigned(sourceBuffer); - var m = function minimatch (p, pattern, options) { - return orig(p, pattern, ext(def, options)) - } + self.files.push(data); - 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 + callback(null, data); } - m.filter = function filter (pattern, options) { - return orig.filter(pattern, ext(def, options)) + if (data.sourceType === 'buffer') { + onend(null, source); + } else if (data.sourceType === 'stream') { + util.collectStream(source, onend); } +}; - m.defaults = function defaults (options) { - return orig.defaults(ext(def, options)) - } +/** + * [finalize description] + * + * @return void + */ +Json.prototype.finalize = function() { + this._writeStringified(); + this.end(); +}; - m.makeRe = function makeRe (pattern, options) { - return orig.makeRe(pattern, ext(def, options)) - } +module.exports = Json; - m.braceExpand = function braceExpand (pattern, options) { - return orig.braceExpand(pattern, ext(def, options)) - } +/** + * @typedef {Object} JsonOptions + * @global + */ - m.match = function (list, pattern, options) { - return orig.match(list, pattern, ext(def, options)) - } - return m -} +/***/ }), -Minimatch.defaults = function (def) { - return minimatch.defaults(def).Minimatch -} +/***/ 33614: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function minimatch (p, pattern, options) { - assertValidPattern(pattern) +/** + * 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 (!options) options = {} +var engine = __nccwpck_require__(2283); +var util = __nccwpck_require__(82072); - // shortcut: comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - return false +/** + * @constructor + * @param {TarOptions} options + */ +var Tar = function(options) { + if (!(this instanceof Tar)) { + return new Tar(options); } - return new Minimatch(pattern, options).match(p) -} + options = this.options = util.defaults(options, { + gzip: false + }); -function Minimatch (pattern, options) { - if (!(this instanceof Minimatch)) { - return new Minimatch(pattern, options) + if (typeof options.gzipOptions !== 'object') { + options.gzipOptions = {}; } - assertValidPattern(pattern) - - if (!options) options = {} + this.supports = { + directory: true, + symlink: true + }; - pattern = pattern.trim() + this.engine = engine.pack(options); + this.compressor = false; - // windows support: need to use /, not \ - if (!options.allowWindowsEscape && path.sep !== '/') { - pattern = pattern.split(path.sep).join('/') + if (options.gzip) { + this.compressor = zlib.createGzip(options.gzipOptions); + this.compressor.on('error', this._onCompressorError.bind(this)); } +}; - this.options = options - this.set = [] - this.pattern = pattern - this.regexp = null - this.negate = false - this.comment = false - this.empty = false - this.partial = !!options.partial +/** + * [_onCompressorError description] + * + * @private + * @param {Error} err + * @return void + */ +Tar.prototype._onCompressorError = function(err) { + this.engine.emit('error', err); +}; - // make the set of regexps etc. - this.make() -} +/** + * [append description] + * + * @param {(Buffer|Stream)} source + * @param {TarEntryData} data + * @param {Function} callback + * @return void + */ +Tar.prototype.append = function(source, data, callback) { + var self = this; -Minimatch.prototype.debug = function () {} + data.mtime = data.date; -Minimatch.prototype.make = make -function make () { - var pattern = this.pattern - var options = this.options + function append(err, sourceBuffer) { + if (err) { + callback(err); + return; + } - // empty patterns and comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - this.comment = true - return + self.engine.entry(data, sourceBuffer, function(err) { + callback(err, data); + }); } - if (!pattern) { - this.empty = true - return + + 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); } +}; - // step 1: figure out negation, etc. - this.parseNegate() +/** + * [finalize description] + * + * @return void + */ +Tar.prototype.finalize = function() { + this.engine.finalize(); +}; - // step 2: expand braces - var set = this.globSet = this.braceExpand() +/** + * [on description] + * + * @return this.engine + */ +Tar.prototype.on = function() { + return this.engine.on.apply(this.engine, arguments); +}; - if (options.debug) this.debug = function debug() { console.error.apply(console, 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); + } +}; - this.debug(this.pattern, set) +/** + * [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); + } +}; - // 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) - }) +module.exports = Tar; - this.debug(this.pattern, set) +/** + * @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. + */ - // glob --> regexps - set = set.map(function (s, si, set) { - return s.map(this.parse, this) - }, this) +/** + * @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. + */ - this.debug(this.pattern, set) +/** + * TarStream Module + * @external TarStream + * @see {@link https://github.com/mafintosh/tar-stream} + */ - // filter out everything that didn't compile properly. - set = set.filter(function (s) { - return s.indexOf(false) === -1 - }) - this.debug(this.pattern, set) +/***/ }), - this.set = set -} +/***/ 8987: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Minimatch.prototype.parseNegate = parseNegate -function parseNegate () { - var pattern = this.pattern - var negate = false - var options = this.options - var negateOffset = 0 +/** + * 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); - if (options.nonegate) return +/** + * @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 + }); - for (var i = 0, l = pattern.length - ; i < l && pattern.charAt(i) === '!' - ; i++) { - negate = !negate - negateOffset++ - } + this.supports = { + directory: true, + symlink: true + }; - if (negateOffset) this.pattern = pattern.substr(negateOffset) - this.negate = negate -} + this.engine = new engine(options); +}; -// 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) -} +/** + * @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); +}; -Minimatch.prototype.braceExpand = braceExpand +/** + * @return void + */ +Zip.prototype.finalize = function() { + this.engine.finalize(); +}; -function braceExpand (pattern, options) { - if (!options) { - if (this instanceof Minimatch) { - options = this.options - } else { - options = {} - } - } +/** + * @return this.engine + */ +Zip.prototype.on = function() { + return this.engine.on.apply(this.engine, arguments); +}; - pattern = typeof pattern === 'undefined' - ? this.pattern : pattern +/** + * @return this.engine + */ +Zip.prototype.pipe = function() { + return this.engine.pipe.apply(this.engine, arguments); +}; - assertValidPattern(pattern) +/** + * @return this.engine + */ +Zip.prototype.unpipe = function() { + return this.engine.unpipe.apply(this.engine, arguments); +}; - // 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] - } +module.exports = Zip; - return expand(pattern) -} +/** + * @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. + */ -var MAX_PATTERN_LENGTH = 1024 * 64 -var assertValidPattern = function (pattern) { - if (typeof pattern !== 'string') { - throw new TypeError('invalid pattern') - } +/** + * @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. + */ - if (pattern.length > MAX_PATTERN_LENGTH) { - throw new TypeError('pattern is too long') - } -} +/** + * ZipStream Module + * @external ZipStream + * @see {@link https://www.archiverjs.com/zip-stream/ZipStream.html} + */ -// 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) - var options = this.options +/***/ }), - // shortcuts - if (pattern === '**') { - if (!options.noglobstar) - return GLOBSTAR - else - pattern = '*' - } - if (pattern === '') return '' +/***/ 57888: +/***/ (function(__unused_webpack_module, exports) { - 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 +(function (global, factory) { + true ? factory(exports) : + 0; +})(this, (function (exports) { 'use strict'; + + /** + * 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 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 + function initialParams (fn) { + return function (...args/*, callback*/) { + var callback = args.pop(); + return fn.call(this, args, callback); + }; } - } - 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) + /* istanbul ignore file */ - // skip over any that are escaped. - if (escaping && reSpecials[c]) { - re += '\\' + c - escaping = false - continue - } + var hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask; + var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; + var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; - switch (c) { - /* istanbul ignore next */ - case '/': { - // completely not allowed, even escaped. - // Should already be path-split by now. - return false - } + function fallback(fn) { + setTimeout(fn, 0); + } - case '\\': - clearStateChar() - escaping = true - continue + function wrap(defer) { + return (fn, ...args) => defer(() => fn(...args)); + } - // 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) + var _defer$1; - // 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 + 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); + + /** + * 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) + } } - // 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 + 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); + } + }); + } - case '(': - if (inClass) { - re += '(' - continue - } + 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)); + }); + } - if (!stateChar) { - re += '\\(' - continue + function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (err) { + setImmediate$1(e => { throw e }, err); } + } - 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 + function isAsync(fn) { + return fn[Symbol.toStringTag] === 'AsyncFunction'; + } - case ')': - if (inClass || !patternListStack.length) { - re += '\\)' - continue - } + function isAsyncGenerator(fn) { + return fn[Symbol.toStringTag] === 'AsyncGenerator'; + } - 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 + function isAsyncIterable(obj) { + return typeof obj[Symbol.asyncIterator] === 'function'; + } - case '|': - if (inClass || !patternListStack.length || escaping) { - re += '\\|' - escaping = false - continue + 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); + }) } - clearStateChar() - re += '|' - continue + return awaitable + } - // these are mostly the same in regexp and glob - case '[': - // swallow any state-tracking char before the [ - clearStateChar() + 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; + }; + } - if (inClass) { - re += '\\' + c - continue - } + function _asyncMap(eachfn, arr, iteratee, callback) { + arr = arr || []; + var results = []; + var counter = 0; + var _iteratee = wrapAsync(iteratee); - inClass = true - classStart = i - reClassStart = re.length - re += c - continue + return eachfn(arr, (value, _, iterCb) => { + var index = counter++; + _iteratee(value, (err, v) => { + results[index] = v; + iterCb(err); + }); + }, err => { + callback(err, results); + }); + } - 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 - } + function isArrayLike(value) { + return value && + typeof value.length === 'number' && + value.length >= 0 && + value.length % 1 === 0; + } - // 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 + // 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 + } - // finish up the class. - hasMagic = true - inClass = false - re += c - continue + function getIterator (coll) { + return coll[Symbol.iterator] && coll[Symbol.iterator](); + } - default: - // swallow any state char that wasn't consumed - clearStateChar() + function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? {value: coll[i], key: i} : null; + } + } - if (escaping) { - // no need - escaping = false - } else if (reSpecials[c] - && !(c === '^' && inClass)) { - re += '\\' + 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}; } + } - re += c + 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; + }; + } - } // switch - } // for + function createIterator(coll) { + if (isArrayLike(coll)) { + return createArrayIterator(coll); + } - // 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] - } + var iterator = getIterator(coll); + return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); + } - // 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 = '\\' - } + 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); + }; + } - // 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 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); + } - this.debug('tail=%j\n %s', tail, tail, pl, re) - var t = pl.type === '*' ? star - : pl.type === '?' ? qmark - : '\\' + pl.type + function iterateeCallback(err, result) { + //console.log('iterateeCallback') + running -= 1; + if (canceled) return + if (err) return handleError(err) - hasMagic = true - re = re.slice(0, pl.reStart) + t + '\\(' + tail - } + if (err === false) { + done = true; + canceled = true; + return + } - // handle trailing things that only matter at the very end. - clearStateChar() - if (escaping) { - // trailing \\ - re += '\\\\' - } + if (result === breakLoop$1 || (done && running <= 0)) { + done = true; + //console.log('done iterCb') + return callback(null); + } + replenish(); + } - // 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 - } + function handleError(err) { + if (canceled) return + awaiting = false; + done = true; + callback(err); + } - // 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] + replenish(); + } - 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) + 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; - nlLast += nlAfter + 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(); + } + } - // 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 + 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; + } - var dollar = '' - if (nlAfter === '' && isSub !== SUBPARSE) { - dollar = '$' - } - var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast - re = newRe - } + replenish(); + }; + }; - // 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 - } + /** + * 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(coll, limit, iteratee, callback) { + return eachOfLimit$2(limit)(coll, wrapAsync(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); + } + + /** + * 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); + } + + 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) { + * 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); + + /** + * 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 = applyEach$1(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$1(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); + + /** + * 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$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; + }); - if (addPatternStart) { - re = patternStart + re - } + return callback + } + + /** + * 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; + } - // parsing just a piece of a larger pattern. - if (isSub === SUBPARSE) { - return [re, hasMagic] - } + var results = {}; + var runningTasks = 0; + var canceled = false; + var hasError = false; - // 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) - } + var listeners = Object.create(null); - 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 readyTasks = []; - regExp._glob = pattern - regExp._src = re + // for cycle detection: + var readyToCheck = []; // tasks that have been identified as reachable + // without the possibility of returning to an ancestor task + var uncheckedDependencies = {}; - return regExp -} + Object.keys(tasks).forEach(key => { + var task = tasks[key]; + if (!Array.isArray(task)) { + // no dependencies + enqueueTask(key, [task]); + readyToCheck.push(key); + return; + } -minimatch.makeRe = function (pattern, options) { - return new Minimatch(pattern, options || {}).makeRe() -} + 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; -Minimatch.prototype.makeRe = makeRe -function makeRe () { - if (this.regexp || this.regexp === false) return this.regexp + 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); + } + }); + }); + }); - // 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 + checkForDeadlocks(); + processQueue(); - if (!set.length) { - this.regexp = false - return this.regexp - } - var options = this.options + function enqueueTask(key, task) { + readyTasks.push(() => runTask(key, task)); + } - var twoStar = options.noglobstar ? star - : options.dot ? twoStarDot - : twoStarNoDot - var flags = options.nocase ? 'i' : '' + 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(); + } - var re = set.map(function (pattern) { - return pattern.map(function (p) { - return (p === GLOBSTAR) ? twoStar - : (typeof p === 'string') ? regExpEscape(p) - : p._src - }).join('\\\/') - }).join('|') + } - // must match entire pattern - // ending in a * or ** will make it less strict. - re = '^(?:' + re + ')$' + function addListener(taskName, fn) { + var taskListeners = listeners[taskName]; + if (!taskListeners) { + taskListeners = listeners[taskName] = []; + } - // can match anything, as long as it's not this. - if (this.negate) re = '^(?!' + re + ').*$' + taskListeners.push(fn); + } - try { - this.regexp = new RegExp(re, flags) - } catch (ex) /* istanbul ignore next - should be impossible */ { - this.regexp = false - } - return this.regexp -} + function taskComplete(taskName) { + var taskListeners = listeners[taskName] || []; + taskListeners.forEach(fn => fn()); + processQueue(); + } -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 -} -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 === '' + function runTask(key, task) { + if (hasError) return; - if (f === '/' && partial) return true + 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); + } + }); - var options = this.options + 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); + } + }); + } - // windows: need to use /, not \ - if (path.sep !== '/') { - f = f.split(path.sep).join('/') - } + if (counter !== numTasks) { + throw new Error( + 'async.auto cannot execute tasks due to a recursive dependency' + ); + } + } - // treat the test path as a set of pathparts. - f = f.split(slashSplit) - this.debug(this.pattern, 'split', f) + 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; + } - // 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. + return callback[PROMISE_SYMBOL] + } + + 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*)$/; + + 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()); + } + + /** + * 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 = {}; + + 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); + + if (Array.isArray(taskFn)) { + params = [...taskFn]; + taskFn = params.pop(); + + 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 set = this.set - this.debug(this.pattern, 'set', set) + // remove callback param + if (!fnIsAsync) params.pop(); - // 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 - } + newTasks[key] = params.concat(newTask); + } - 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 - } - } + function newTask(results, taskCb) { + var newArgs = params.map(name => results[name]); + newArgs.push(taskCb); + wrapAsync(taskFn)(...newArgs); + } + }); - // 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 auto(newTasks, callback); + } -// 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 + // 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; + } - this.debug('matchOne', - { 'this': this, file: file, pattern: pattern }) + 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; - this.debug('matchOne', file.length, pattern.length) + node.prev = node.next = null; + this.length -= 1; + return node; + } - 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] + empty () { + while(this.head) this.shift(); + return this; + } - this.debug(pattern, p, f) + 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; + } - // should be impossible. - // some invalid regexp stuff in the set. - /* istanbul ignore if */ - if (p === false) return false + 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; + } - if (p === GLOBSTAR) { - this.debug('GLOBSTAR', [pattern, p, f]) + unshift(node) { + if (this.head) this.insertBefore(this.head, node); + else setInitial(this, node); + } - // "**" - // 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 + push(node) { + if (this.tail) this.insertAfter(this.tail, node); + else setInitial(this, node); } - return true - } - // ok, let's see if we can swallow whatever we can. - while (fr < fl) { - var swallowee = file[fr] + shift() { + return this.head && this.removeLink(this.head); + } - this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) + pop() { + return this.tail && this.removeLink(this.tail); + } - // 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 - } + toArray() { + return [...this] + } - // ** swallows a segment, and continue. - this.debug('globstar swallow a segment, and continue') - fr++ + *[Symbol.iterator] () { + var cur = this.head; + while (cur) { + yield cur.data; + cur = cur.next; + } } - } - // 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 + remove (testFn) { + var curr = this.head; + while(curr) { + var {next} = curr; + if (testFn(curr)) { + this.removeLink(curr); + } + curr = next; + } + return this; + } } - // 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) + function setInitial(dll, node) { + dll.length = 1; + dll.head = dll.tail = node; } - if (!hit) return false - } + function queue$1(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } + else if(concurrency === 0) { + throw new RangeError('Concurrency must not be zero'); + } - // 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/* + var _worker = wrapAsync(worker); + var numRunning = 0; + var workersList = []; + const events = { + error: [], + drain: [], + saturated: [], + unsaturated: [], + empty: [] + }; - // 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] === '') - } + function on (event, handler) { + events[event].push(handler); + } - // should be unreachable. - /* istanbul ignore next */ - throw new Error('wtf?') -} + function once (event, handler) { + const handleAndRemove = (...args) => { + off(event, handleAndRemove); + handler(...args); + }; + events[event].push(handleAndRemove); + } -// replace stuff like \* with * -function globUnescape (s) { - return s.replace(/\\(.)/g, '$1') -} + 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 regExpEscape (s) { - return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') -} + function trigger (event, ...args) { + events[event].forEach(handler => handler(...args)); + } + 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; -/***/ }), + 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); + } -/***/ 4956: -/***/ ((module, exports, __nccwpck_require__) => { + var item = q._createTaskItem( + data, + rejectOnError ? promiseCallback : + (callback || promiseCallback) + ); -"use strict"; + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + if (!processingScheduled) { + processingScheduled = true; + setImmediate$1(() => { + processingScheduled = false; + q.process(); + }); + } -Object.defineProperty(exports, "__esModule", ({ value: true })); + if (rejectOnError || !callback) { + return new Promise((resolve, reject) => { + res = resolve; + rej = reject; + }) + } + } -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + function _createCB(tasks) { + return function (err, ...args) { + numRunning -= 1; -var Stream = _interopDefault(__nccwpck_require__(2781)); -var http = _interopDefault(__nccwpck_require__(3685)); -var Url = _interopDefault(__nccwpck_require__(7310)); -var whatwgUrl = _interopDefault(__nccwpck_require__(1324)); -var https = _interopDefault(__nccwpck_require__(5687)); -var zlib = _interopDefault(__nccwpck_require__(9796)); + for (var i = 0, l = tasks.length; i < l; i++) { + var task = tasks[i]; -// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + var index = workersList.indexOf(task); + if (index === 0) { + workersList.shift(); + } else if (index > 0) { + workersList.splice(index, 1); + } -// fix for "Readable" isn't a named export issue -const Readable = Stream.Readable; + task.callback(err, ...args); -const BUFFER = Symbol('buffer'); -const TYPE = Symbol('type'); + if (err != null) { + trigger('error', err, task.data); + } + } -class Blob { - constructor() { - this[TYPE] = ''; + if (numRunning <= (q.concurrency - q.buffer) ) { + trigger('unsaturated'); + } - const blobParts = arguments[0]; - const options = arguments[1]; + if (q.idle()) { + trigger('drain'); + } + q.process(); + }; + } - const buffers = []; - let size = 0; + 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 + } - if (blobParts) { - const a = blobParts; - const length = Number(a.length); - for (let i = 0; i < length; i++) { - const element = a[i]; - let buffer; - if (element instanceof Buffer) { - buffer = element; - } else if (ArrayBuffer.isView(element)) { - buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); - } else if (element instanceof ArrayBuffer) { - buffer = Buffer.from(element); - } else if (element instanceof Blob) { - buffer = element[BUFFER]; - } else { - buffer = Buffer.from(typeof element === 'string' ? element : String(element)); - } - size += buffer.length; - buffers.push(buffer); - } - } - - this[BUFFER] = Buffer.concat(buffers); - - 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; - - 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); - - const buffer = this[BUFFER]; - const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); - const blob = new Blob([], { type: arguments[2] }); - blob[BUFFER] = slicedBuffer; - return blob; - } -} + 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); -Object.defineProperties(Blob.prototype, { - size: { enumerable: true }, - type: { enumerable: true }, - slice: { enumerable: true } -}); + }; -Object.defineProperty(Blob.prototype, Symbol.toStringTag, { - value: 'Blob', - writable: false, - enumerable: false, - configurable: 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); + } -/** - * fetch-error.js - * - * FetchError interface for operational errors - */ + numRunning += 1; -/** - * 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); + if (q._tasks.length === 0) { + trigger('empty'); + } - this.message = message; - this.type = type; + if (numRunning === q.concurrency) { + trigger('saturated'); + } - // when err.type is `system`, err.code contains system error code - if (systemError) { - this.code = this.errno = systemError.code; - } + 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 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://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/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); + + /** + * 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; - // hide custom error implementation details from end-users - Error.captureStackTrace(this, this.constructor); -} + var cb = args[args.length - 1]; + if (typeof cb == 'function') { + args.pop(); + } else { + cb = promiseCallback(); + } -FetchError.prototype = Object.create(Error.prototype); -FetchError.prototype.constructor = FetchError; -FetchError.prototype.name = 'FetchError'; + reduce$1(_functions, args, (newargs, fn, iterCb) => { + fn.apply(that, newargs.concat((err, ...nextargs) => { + iterCb(err, nextargs); + })); + }, + (err, results) => cb(err, ...results)); -let convert; -try { - convert = (__nccwpck_require__(8069).convert); -} catch (e) {} + return cb[PROMISE_SYMBOL] + }; + } -const INTERNALS = Symbol('Body internals'); + /** + * 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()); + } + + /** + * 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); + + /** + * 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]); + } + } -// fix an issue where "PassThrough" isn't a named export for node <10 -const PassThrough = Stream.PassThrough; + return callback(err, result); + }); + } + var concatLimit$1 = awaitify(concatLimit, 4); + + /** + * 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); + + /** + * 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); + }; + } -/** - * 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; + 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); - var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref$size = _ref.size; + 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)); + }); + }; + } - let size = _ref$size === undefined ? 0 : _ref$size; - var _ref$timeout = _ref.timeout; - let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + /** + * 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); + + /** + * 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) + } + 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$2(1), coll, iteratee, callback) + } + + var detectSeries$1 = awaitify(detectSeries, 3); + + 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 (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; + /** + * 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'); + + /** + * 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); + } + + return check(null, true); + } + + var doWhilst$1 = awaitify(doWhilst, 3); + + /** + * 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 _withoutIndex(iteratee) { + return (value, index, callback) => iteratee(value, callback); + } + + /** + * 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); + } + + var each = awaitify(eachLimit$2, 3); + + /** + * 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); + } + var eachLimit$1 = awaitify(eachLimit, 4); + + /** + * 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. + + * @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); + + /** + * 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 (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; - }); - } -} + /** + * 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); + + /** + * 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); + + /** + * 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 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); + }); + } -Body.prototype = { - get body() { - return this[INTERNALS].body; - }, + 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)); + }); + } - get bodyUsed() { - return this[INTERNALS].disturbed; - }, + function _filter(eachfn, coll, iteratee, callback) { + var filter = isArrayLike(coll) ? filterArray : filterGeneric; + return filter(eachfn, coll, wrapAsync(iteratee), callback); + } - /** - * Decode response as ArrayBuffer - * - * @return Promise - */ - arrayBuffer() { - return consumeBody.call(this).then(function (buf) { - return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); - }); - }, + /** + * 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); + + /** + * 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 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); + + /** + * Calls the asynchronous function `fn` with a callback parameter that allows it + * to call itself again, in series, indefinitely. + + * 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 next(err) { + if (err) return done(err); + if (err === false) return; + task(next); + } + return next(); + } + var forever$1 = awaitify(forever, 2); + + /** + * 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; + + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + var {key} = mapResults[i]; + var {val} = mapResults[i]; + + if (hasOwnProperty.call(result, key)) { + result[key].push(val); + } else { + result[key] = [val]; + } + } + } - /** - * Return raw response as Blob - * - * @return Promise - */ - blob() { - let ct = this.headers && this.headers.get('content-type') || ''; - return consumeBody.call(this).then(function (buf) { - return Object.assign( - // Prevent copying - new Blob([], { - type: ct.toLowerCase() - }), { - [BUFFER]: buf - }); - }); - }, + return callback(err, result); + }); + } - /** - * Decode response as json - * - * @return Promise - */ - json() { - var _this2 = this; + var groupByLimit$1 = awaitify(groupByLimit, 4); + + /** + * 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) + } + + /** + * 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) + } + + /** + * 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'); + + /** + * 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)); + } + + var mapValuesLimit$1 = awaitify(mapValuesLimit, 4); + + /** + * 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) + } + + /** + * 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) + } + + /** + * 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; + } - 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')); - } - }); - }, + /* istanbul ignore file */ - /** - * Decode response as text - * - * @return Promise - */ - text() { - return consumeBody.call(this).then(function (buffer) { - return buffer.toString(); - }); - }, + /** + * 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; - /** - * Decode response as buffer (non-spec api) - * - * @return Promise - */ - buffer() { - return consumeBody.call(this); - }, + if (hasNextTick) { + _defer = process.nextTick; + } else if (hasSetImmediate) { + _defer = setImmediate; + } else { + _defer = fallback; + } - /** - * 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; + var nextTick = wrap(_defer); - return consumeBody.call(this).then(function (buffer) { - return convertBody(buffer, _this3.headers); - }); - } -}; + var _parallel = awaitify((eachfn, tasks, callback) => { + var results = isArrayLike(tasks) ? [] : {}; -// 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 } -}); + 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); + + /** + * 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); + } + + /** + * 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); + } + + /** + * 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() + */ + + /** + * 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); + } -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); - } - } -}; + // 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; + } -/** - * 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; + get length() { + return this.heap.length; + } - if (this[INTERNALS].disturbed) { - return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); - } + empty () { + this.heap = []; + return this; + } - this[INTERNALS].disturbed = true; + percUp(index) { + let p; - if (this[INTERNALS].error) { - return Body.Promise.reject(this[INTERNALS].error); - } + 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; - let body = this.body; + index = p; + } + } - // body is null - if (body === null) { - return Body.Promise.resolve(Buffer.alloc(0)); - } + percDown(index) { + let l; - // body is blob - if (isBlob(body)) { - body = body.stream(); - } + while ((l=leftChi(index)) < this.heap.length) { + if (l+1 < this.heap.length && smaller(this.heap[l+1], this.heap[l])) { + l = l+1; + } - // body is buffer - if (Buffer.isBuffer(body)) { - return Body.Promise.resolve(body); - } + if (smaller(this.heap[index], this.heap[l])) { + break; + } - // istanbul ignore if: should never happen - if (!(body instanceof Stream)) { - return Body.Promise.resolve(Buffer.alloc(0)); - } + let t = this.heap[index]; + this.heap[index] = this.heap[l]; + this.heap[l] = t; - // body is stream - // get ready to actually consume the body - let accum = []; - let accumBytes = 0; - let abort = false; + index = l; + } + } - return new Body.Promise(function (resolve, reject) { - let resTimeout; + push(node) { + node.pushCount = ++this.pushCount; + this.heap.push(node); + this.percUp(this.heap.length-1); + } - // 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); - } + unshift(node) { + return this.heap.push(node); + } - // 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)); - } - }); + shift() { + let [top] = this.heap; - body.on('data', function (chunk) { - if (abort || chunk === null) { - return; - } + this.heap[0] = this.heap[this.heap.length-1]; + this.heap.pop(); + this.percDown(0); - 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; - } + return top; + } - accumBytes += chunk.length; - accum.push(chunk); - }); + toArray() { + return [...this]; + } - body.on('end', function () { - if (abort) { - return; - } + *[Symbol.iterator] () { + for (let i = 0; i < this.heap.length; i++) { + yield this.heap[i].data; + } + } - clearTimeout(resTimeout); + 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++; + } + } - 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)); - } - }); - }); -} + this.heap.splice(j); -/** - * 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'); - } + for (let i = parent(this.heap.length-1); i >= 0; i--) { + this.percDown(i); + } - const ct = headers.get('content-type'); - let charset = 'utf-8'; - let res, str; + return this; + } + } - // header - if (ct) { - res = /charset=([^;]*)/i.exec(ct); - } + function leftChi(i) { + return (i<<1)+1; + } - // no charset in content type, peek at response body for at most 1024 bytes - str = buffer.slice(0, 1024).toString(); + function parent(i) { + return ((i+1)>>1)-1; + } - // html5 - if (!res && str) { - res = / { + return { + data, + priority, + callback + }; + }; - // html4 - if (!res && str) { - res = / { return {data, priority}; }); + } - if (res) { - res = /charset=(.*)/i.exec(res.pop()); - } - } + // Override push to accept second parameter representing priority + q.push = function(data, priority = 0, callback) { + return push(createDataItems(data, priority), callback); + }; - // xml - if (!res && str) { - res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str); - } + q.pushAsync = function(data, priority = 0, callback) { + return pushAsync(createDataItems(data, priority), callback); + }; - // found charset - if (res) { - charset = res.pop(); + // Remove unshift functions + delete q.unshift; + delete q.unshiftAsync; + + return q; + } + + /** + * 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); + } + } + + var race$1 = awaitify(race, 2); + + /** + * 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); + } + + /** + * 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); + }); - // prevent decode issues when sites use incorrect encoding - // ref: https://hsivonen.fi/encoding-menu/ - if (charset === 'gb2312' || charset === 'gbk') { - charset = 'gb18030'; - } - } + return _fn.apply(this, args); + }); + } - // turn raw buffers into a single utf-8 buffer - return convert(buffer, 'UTF-8', charset).toString(); -} + /** + * 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; + } -/** - * Detect a URLSearchParams object - * ref: https://github.com/bitinn/node-fetch/issues/296#issuecomment-307598143 - * - * @param Object obj Object to detect by type or brand - * @return String - */ -function isURLSearchParams(obj) { - // Duck-typing as a necessary condition. - if (typeof obj !== 'object' || typeof obj.append !== 'function' || typeof obj.delete !== 'function' || typeof obj.get !== 'function' || typeof obj.getAll !== 'function' || typeof obj.has !== 'function' || typeof obj.set !== 'function') { - return false; - } + 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); - // Brand-checking and more duck-typing as optional condition. - return obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function'; -} + /** + * 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); -/** - * 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]); -} + /** + * 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); -/** - * 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; + function constant(value) { + return function () { + return value; + } + } - // don't allow cloning a used body - if (instance.bodyUsed) { - throw new Error('cannot clone body after it is used'); - } + /** + * 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; - // 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; - } + function retry(opts, task, callback) { + var options = { + times: DEFAULT_TIMES, + intervalFunc: constant(DEFAULT_INTERVAL) + }; - return body; -} + if (arguments.length < 3 && typeof opts === 'function') { + callback = task || promiseCallback(); + task = opts; + } else { + parseTimes(options, opts); + callback = callback || promiseCallback(); + } -/** - * 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'; - } -} + if (typeof task !== 'function') { + throw new Error("Invalid arguments for async.retry"); + } -/** - * 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; + var _task = wrapAsync(task); + 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); + } + }); + } - 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; - } -} + retryAttempt(); + return callback[PROMISE_SYMBOL] + } -/** - * 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; + function parseTimes(acc, t) { + if (typeof t === 'object') { + acc.times = +t.times || DEFAULT_TIMES; + acc.intervalFunc = typeof t.interval === 'function' ? + t.interval : + constant(+t.interval || DEFAULT_INTERVAL); - 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); - } -} + 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"); + } + } + + /** + * 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); + } + + if (opts) retry(opts, taskFn, callback); + else retry(taskFn, callback); + + return callback[PROMISE_SYMBOL] + }); + } -// expose Promise -Body.Promise = global.Promise; + /** + * 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); + } + + /** + * 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); + + /** + * 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) + } + 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 someSeries$1 = awaitify(someSeries, 3); + + /** + * 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}); + }); + }, (err, results) => { + if (err) return callback(err); + callback(null, results.sort(comparator).map(v => v.value)); + }); -/** - * headers.js - * - * Headers class offers convenient helpers - */ - -const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/; -const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/; + function comparator(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + } + } + var sortBy$1 = awaitify(sortBy, 3); -function validateName(name) { - name = `${name}`; - if (invalidTokenRegex.test(name) || name === '') { - throw new TypeError(`${name} is not a legal HTTP header name`); - } -} + /** + * 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); -function validateValue(value) { - value = `${value}`; - if (invalidHeaderCharRegex.test(value)) { - throw new TypeError(`${value} is not a legal HTTP header value`); - } -} + return initialParams((args, callback) => { + var timedOut = false; + var timer; -/** - * 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 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); + } -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; + args.push((...cbArgs) => { + if (!timedOut) { + callback(...cbArgs); + clearTimeout(timer); + } + }); - this[MAP] = Object.create(null); + // setup timer and call original function + timer = setTimeout(timeoutCallback, milliseconds); + fn(...args); + }); + } - if (init instanceof Headers) { - const rawHeaders = init.raw(); - const headerNames = Object.keys(rawHeaders); + function range(size) { + var result = Array(size); + while (size--) { + result[size] = size; + } + return result; + } - for (const headerName of headerNames) { - for (const value of rawHeaders[headerName]) { - this.append(headerName, value); - } - } + /** + * 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); + } + + /** + * 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) + } + + /** + * 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) + } + + /** + * 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); + + eachOf$1(coll, (v, k, cb) => { + _iteratee(accumulator, v, k, cb); + }, err => callback(err, accumulator)); + return callback[PROMISE_SYMBOL] + } + + /** + * 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); - return; - } + if (args.length < 2) { + [result] = args; + } else { + result = args; + } + error = err; + taskCb(err ? null : {}); + }); + }, () => callback(error, result)); + } - // 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'); - } + var tryEach$1 = awaitify(tryEach); - // 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)); - } + /** + * 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); + }; + } - 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'); - } - } + /** + * 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 = []; + + 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'); + * }, + * 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; + + 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); + } + + nextTask([]); + } + + var waterfall$1 = awaitify(waterfall); + + /** + * 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 + */ + + + 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, + + // 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 + }; - /** - * 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; - } + 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; + + Object.defineProperty(exports, '__esModule', { value: true }); - return this[MAP][key].join(', '); - } +})); - /** - * Iterate over all headers - * - * @param Function callback Executed for each item with parameters (value, name, thisArg) - * @param Boolean thisArg `this` context for callback function - * @return Void - */ - forEach(callback) { - let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; - 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]; +/***/ }), - callback.call(thisArg, value, name, this); - pairs = getHeaders(this); - i++; - } - } +/***/ 14812: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * 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]; - } +module.exports = +{ + parallel : __nccwpck_require__(8210), + serial : __nccwpck_require__(50445), + serialOrdered : __nccwpck_require__(3578) +}; - /** - * Append a value onto existing header - * - * @param String name Header name - * @param String value Header value - * @return Void - */ - append(name, value) { - name = `${name}`; - value = `${value}`; - validateName(name); - validateValue(value); - const key = find(this[MAP], name); - if (key !== undefined) { - this[MAP][key].push(value); - } else { - this[MAP][name] = [value]; - } - } - /** - * Check for header name existence - * - * @param String name Header name - * @return Boolean - */ - has(name) { - name = `${name}`; - validateName(name); - return find(this[MAP], name) !== undefined; - } +/***/ }), - /** - * 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]; - } - } +/***/ 1700: +/***/ ((module) => { - /** - * Return raw headers (non-spec api) - * - * @return Object - */ - raw() { - return this[MAP]; - } +// API +module.exports = abort; - /** - * Get an iterator on keys. - * - * @return Iterator - */ - keys() { - return createHeadersIterator(this, 'key'); - } +/** + * Aborts leftover active jobs + * + * @param {object} state - current state object + */ +function abort(state) +{ + Object.keys(state.jobs).forEach(clean.bind(state)); - /** - * Get an iterator on values. - * - * @return Iterator - */ - values() { - return createHeadersIterator(this, 'value'); - } + // reset leftover jobs + state.jobs = {}; +} - /** - * Get an iterator on entries. - * - * This is the default iterator of the Headers object. - * - * @return Iterator - */ - [Symbol.iterator]() { - return createHeadersIterator(this, 'key+value'); - } +/** + * 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](); + } } -Headers.prototype.entries = Headers.prototype[Symbol.iterator]; -Object.defineProperty(Headers.prototype, Symbol.toStringTag, { - value: 'Headers', - writable: false, - enumerable: false, - configurable: true -}); -Object.defineProperties(Headers.prototype, { - get: { enumerable: true }, - forEach: { enumerable: true }, - set: { enumerable: true }, - append: { enumerable: true }, - has: { enumerable: true }, - delete: { enumerable: true }, - keys: { enumerable: true }, - values: { enumerable: true }, - entries: { enumerable: true } -}); +/***/ }), -function getHeaders(headers) { - let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; +/***/ 72794: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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(', ')]; - }); -} +var defer = __nccwpck_require__(15295); -const INTERNAL = Symbol('internal'); +// API +module.exports = async; -function createHeadersIterator(target, kind) { - const iterator = Object.create(HeadersIteratorPrototype); - iterator[INTERNAL] = { - target, - kind, - index: 0 - }; - return iterator; -} +/** + * 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; -const HeadersIteratorPrototype = Object.setPrototypeOf({ - next() { - // istanbul ignore if - if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { - throw new TypeError('Value of `this` is not a HeadersIterator'); - } + // check if async happened + defer(function() { isAsync = true; }); - var _INTERNAL = this[INTERNAL]; - const target = _INTERNAL.target, - kind = _INTERNAL.kind, - index = _INTERNAL.index; + return function async_callback(err, result) + { + if (isAsync) + { + callback(err, result); + } + else + { + defer(function nextTick_callback() + { + callback(err, result); + }); + } + }; +} - const values = getHeaders(target, kind); - const len = values.length; - if (index >= len) { - return { - value: undefined, - done: true - }; - } - this[INTERNAL].index = index + 1; +/***/ }), - return { - value: values[index], - done: false - }; - } -}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); +/***/ 15295: +/***/ ((module) => { -Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { - value: 'HeadersIterator', - writable: false, - enumerable: false, - configurable: true -}); +module.exports = defer; /** - * Export the Headers object in a form that Node.js can consume. + * Runs provided function on next iteration of the event loop * - * @param Headers headers - * @return Object + * @param {function} fn - function to run */ -function exportNodeCompatibleHeaders(headers) { - const obj = Object.assign({ __proto__: null }, headers[MAP]); - - // 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]; - } +function defer(fn) +{ + var nextTick = typeof setImmediate == 'function' + ? setImmediate + : ( + typeof process == 'object' && typeof process.nextTick == 'function' + ? process.nextTick + : null + ); - return obj; + if (nextTick) + { + nextTick(fn); + } + else + { + setTimeout(fn, 0); + } } -/** - * Create a Headers object from an object of headers, ignoring those that do - * not conform to HTTP grammar productions. - * - * @param Object obj Object of headers - * @return Headers - */ -function createHeadersLenient(obj) { - const headers = new Headers(); - for (const name of Object.keys(obj)) { - if (invalidTokenRegex.test(name)) { - continue; - } - if (Array.isArray(obj[name])) { - for (const val of obj[name]) { - if (invalidHeaderCharRegex.test(val)) { - continue; - } - if (headers[MAP][name] === undefined) { - headers[MAP][name] = [val]; - } else { - headers[MAP][name].push(val); - } - } - } else if (!invalidHeaderCharRegex.test(obj[name])) { - headers[MAP][name] = [obj[name]]; - } - } - return headers; -} -const INTERNALS$1 = Symbol('Response internals'); +/***/ }), -// fix an issue where "STATUS_CODES" aren't a named export for node <10 -const STATUS_CODES = http.STATUS_CODES; +/***/ 9023: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var async = __nccwpck_require__(72794) + , abort = __nccwpck_require__(1700) + ; + +// API +module.exports = iterate; /** - * Response class + * Iterates over each job object * - * @param Stream body Readable stream - * @param Object opts Response options - * @return Void + * @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 */ -class Response { - constructor() { - let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; - let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - 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); - } - } - - this[INTERNALS$1] = { - url: opts.url, - status, - statusText: opts.statusText || STATUS_CODES[status], - headers, - counter: opts.counter - }; - } +function iterate(list, iterator, state, callback) +{ + // store current index + var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; - get url() { - return this[INTERNALS$1].url || ''; - } + state.jobs[key] = runJob(iterator, key, list[key], function(error, output) + { + // don't repeat yourself + // skip secondary callbacks + if (!(key in state.jobs)) + { + return; + } - get status() { - return this[INTERNALS$1].status; - } + // clean up jobs + delete state.jobs[key]; - /** - * Convenience property representing if the request ended normally - */ - get ok() { - return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; - } + if (error) + { + // don't process rest of the results + // stop still active jobs + // and reset the list + abort(state); + } + else + { + state.results[key] = output; + } - get redirected() { - return this[INTERNALS$1].counter > 0; - } + // return salvaged results + callback(error, state.results); + }); +} - get statusText() { - return this[INTERNALS$1].statusText; - } +/** + * 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; - get headers() { - return this[INTERNALS$1].headers; - } + // 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)); + } - /** - * 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 - }); - } + return aborter; } -Body.mixIn(Response.prototype); - -Object.defineProperties(Response.prototype, { - url: { enumerable: true }, - status: { enumerable: true }, - ok: { enumerable: true }, - redirected: { enumerable: true }, - statusText: { enumerable: true }, - headers: { enumerable: true }, - clone: { enumerable: true } -}); -Object.defineProperty(Response.prototype, Symbol.toStringTag, { - value: 'Response', - writable: false, - enumerable: false, - configurable: true -}); +/***/ }), -const INTERNALS$2 = Symbol('Request internals'); -const URL = Url.URL || whatwgUrl.URL; +/***/ 42474: +/***/ ((module) => { -// fix an issue where "format", "parse" aren't a named export for node <10 -const parse_url = Url.parse; -const format_url = Url.format; +// API +module.exports = state; /** - * Wrapper around `new URL` to handle arbitrary URLs + * Creates initial state object + * for iteration over list * - * @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 + * @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 */ - if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { - urlStr = new URL(urlStr).toString(); - } +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 + } + ; - // Fallback to old implementation for arbitrary URLs - return parse_url(urlStr); + 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]); + }); + } + + return initState; } -const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; -/** - * Check if a value is an instance of Request. - * - * @param Mixed input - * @return Boolean - */ -function isRequest(input) { - return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; -} +/***/ }), -function isAbortSignal(signal) { - const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); - return !!(proto && proto.constructor.name === 'AbortSignal'); -} +/***/ 37942: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var abort = __nccwpck_require__(1700) + , async = __nccwpck_require__(72794) + ; + +// API +module.exports = terminator; /** - * Request class + * Terminates jobs in the attached state context * - * @param Mixed input Url or Request instance - * @param Object init Custom options - * @return Void + * @this AsyncKitState# + * @param {function} callback - final callback to invoke after termination */ -class Request { - constructor(input) { - let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - let parsedURL; - - // normalize input - if (!isRequest(input)) { - if (input && input.href) { - // in order to support Node.js' Url objects; though WHATWG's URL objects - // will fall into this branch also (since their `toString()` will return - // `href` property anyway) - parsedURL = parseURL(input.href); - } else { - // coerce input to a string before attempting to parse - parsedURL = parseURL(`${input}`); - } - input = {}; - } else { - parsedURL = parseURL(input.url); - } - - let method = init.method || input.method || 'GET'; - method = method.toUpperCase(); +function terminator(callback) +{ + if (!Object.keys(this.jobs).length) + { + return; + } - if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { - throw new TypeError('Request with GET/HEAD method cannot have body'); - } + // fast forward iteration index + this.index = this.size; - let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + // abort jobs + abort(this); - Body.call(this, inputBody, { - timeout: init.timeout || input.timeout || 0, - size: init.size || input.size || 0 - }); + // send back results we have so far + async(callback)(null, this.results); +} - const headers = new Headers(init.headers || input.headers || {}); - if (inputBody != null && !headers.has('Content-Type')) { - const contentType = extractContentType(inputBody); - if (contentType) { - headers.append('Content-Type', contentType); - } - } +/***/ }), - let signal = isRequest(input) ? input.signal : null; - if ('signal' in init) signal = init.signal; +/***/ 8210: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (signal != null && !isAbortSignal(signal)) { - throw new TypeError('Expected signal to be an instanceof AbortSignal'); - } +var iterate = __nccwpck_require__(9023) + , initState = __nccwpck_require__(42474) + , terminator = __nccwpck_require__(37942) + ; - this[INTERNALS$2] = { - method, - redirect: init.redirect || input.redirect || 'follow', - headers, - parsedURL, - signal - }; +// Public API +module.exports = parallel; - // 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; - } +/** + * 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); - get method() { - return this[INTERNALS$2].method; - } + while (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, function(error, result) + { + if (error) + { + callback(error, result); + return; + } - get url() { - return format_url(this[INTERNALS$2].parsedURL); - } + // looks like it's the last one + if (Object.keys(state.jobs).length === 0) + { + callback(null, state.results); + return; + } + }); - get headers() { - return this[INTERNALS$2].headers; - } + state.index++; + } - get redirect() { - return this[INTERNALS$2].redirect; - } + return terminator.bind(state, callback); +} - get signal() { - return this[INTERNALS$2].signal; - } - /** - * Clone this request - * - * @return Request - */ - clone() { - return new Request(this); - } -} +/***/ }), -Body.mixIn(Request.prototype); +/***/ 50445: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Object.defineProperty(Request.prototype, Symbol.toStringTag, { - value: 'Request', - writable: false, - enumerable: false, - configurable: true -}); +var serialOrdered = __nccwpck_require__(3578); -Object.defineProperties(Request.prototype, { - method: { enumerable: true }, - url: { enumerable: true }, - headers: { enumerable: true }, - redirect: { enumerable: true }, - clone: { enumerable: true }, - signal: { enumerable: true } -}); +// Public API +module.exports = serial; /** - * Convert a Request to Node.js http request options. + * Runs iterator over provided array elements in series * - * @param Request A Request instance - * @return Object The options object to be passed to http.request + * @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 getNodeRequestOptions(request) { - const parsedURL = request[INTERNALS$2].parsedURL; - const headers = new Headers(request[INTERNALS$2].headers); +function serial(list, iterator, callback) +{ + return serialOrdered(list, iterator, null, callback); +} - // fetch step 1.3 - if (!headers.has('Accept')) { - headers.set('Accept', '*/*'); - } - // Basic fetch - if (!parsedURL.protocol || !parsedURL.hostname) { - throw new TypeError('Only absolute URLs are supported'); - } +/***/ }), - if (!/^https?:$/.test(parsedURL.protocol)) { - throw new TypeError('Only HTTP(S) protocols are supported'); - } +/***/ 3578: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { - throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); - } +var iterate = __nccwpck_require__(9023) + , initState = __nccwpck_require__(42474) + , terminator = __nccwpck_require__(37942) + ; - // 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); - } +// Public API +module.exports = serialOrdered; +// sorting helpers +module.exports.ascending = ascending; +module.exports.descending = descending; - // 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)'); - } +/** + * 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); - // HTTP-network-or-cache fetch step 2.15 - if (request.compress && !headers.has('Accept-Encoding')) { - headers.set('Accept-Encoding', 'gzip,deflate'); - } + iterate(list, iterator, state, function iteratorHandler(error, result) + { + if (error) + { + callback(error, result); + return; + } - let agent = request.agent; - if (typeof agent === 'function') { - agent = agent(parsedURL); - } + state.index++; - if (!headers.has('Connection') && !agent) { - headers.set('Connection', 'close'); - } + // are we there yet? + if (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, iteratorHandler); + return; + } - // HTTP-network fetch step 4.2 - // chunked encoding is handled by Node.js + // done here + callback(null, state.results); + }); - return Object.assign({}, parsedURL, { - method: request.method, - headers: exportNodeCompatibleHeaders(headers), - agent - }); + return terminator.bind(state, callback); } +/* + * -- Sort methods + */ + /** - * abort-error.js + * sort helper to sort array elements in ascending order * - * AbortError interface for cancelled requests + * @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; +} /** - * Create AbortError instance + * sort helper to sort array elements in descending order * - * @param String message Error message for human - * @return AbortError + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result */ -function AbortError(message) { - Error.call(this, message); +function descending(a, b) +{ + return -1 * ascending(a, b); +} - this.type = 'aborted'; - this.message = message; - // hide custom error implementation details from end-users - Error.captureStackTrace(this, this.constructor); -} +/***/ }), -AbortError.prototype = Object.create(Error.prototype); -AbortError.prototype.constructor = AbortError; -AbortError.prototype.name = 'AbortError'; +/***/ 33497: +/***/ ((module) => { -const URL$1 = Url.URL || whatwgUrl.URL; +function isBuffer (value) { + return Buffer.isBuffer(value) || value instanceof Uint8Array +} -// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 -const PassThrough$1 = Stream.PassThrough; +function isEncoding (encoding) { + return Buffer.isEncoding(encoding) +} -const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { - const orig = new URL$1(original).hostname; - const dest = new URL$1(destination).hostname; +function alloc (size, fill, encoding) { + return Buffer.alloc(size, fill, encoding) +} - return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); -}; +function allocUnsafe (size) { + return Buffer.allocUnsafe(size) +} -/** - * Fetch function - * - * @param Mixed url Absolute url or Request instance - * @param Object opts Fetch options - * @return Promise - */ -function fetch(url, opts) { +function allocUnsafeSlow (size) { + return Buffer.allocUnsafeSlow(size) +} - // allow custom promise - if (!fetch.Promise) { - throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); - } +function byteLength (string, encoding) { + return Buffer.byteLength(string, encoding) +} - Body.Promise = fetch.Promise; +function compare (a, b) { + return Buffer.compare(a, b) +} - // 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 concat (buffers, totalLength) { + return Buffer.concat(buffers, totalLength) +} - const send = (options.protocol === 'https:' ? https : http).request; - const signal = request.signal; +function copy (source, target, targetStart, start, end) { + return toBuffer(source).copy(target, targetStart, start, end) +} - let response = null; +function equals (a, b) { + return toBuffer(a).equals(b) +} - const abort = function abort() { - let error = new AbortError('The user aborted a request.'); - reject(error); - if (request.body && request.body instanceof Stream.Readable) { - request.body.destroy(error); - } - if (!response || !response.body) return; - response.body.emit('error', error); - }; +function fill (buffer, value, offset, end, encoding) { + return toBuffer(buffer).fill(value, offset, end, encoding) +} - if (signal && signal.aborted) { - abort(); - return; - } +function from (value, encodingOrOffset, length) { + return Buffer.from(value, encodingOrOffset, length) +} - const abortAndFinalize = function abortAndFinalize() { - abort(); - finalize(); - }; +function includes (buffer, value, byteOffset, encoding) { + return toBuffer(buffer).includes(value, byteOffset, encoding) +} - // send request - const req = send(options); - let reqTimeout; +function indexOf (buffer, value, byfeOffset, encoding) { + return toBuffer(buffer).indexOf(value, byfeOffset, encoding) +} - if (signal) { - signal.addEventListener('abort', abortAndFinalize); - } +function lastIndexOf (buffer, value, byteOffset, encoding) { + return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding) +} - function finalize() { - req.abort(); - if (signal) signal.removeEventListener('abort', abortAndFinalize); - clearTimeout(reqTimeout); - } +function swap16 (buffer) { + return toBuffer(buffer).swap16() +} - if (request.timeout) { - req.once('socket', function (socket) { - reqTimeout = setTimeout(function () { - reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); - finalize(); - }, request.timeout); - }); - } +function swap32 (buffer) { + return toBuffer(buffer).swap32() +} - req.on('error', function (err) { - reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); - finalize(); - }); +function swap64 (buffer) { + return toBuffer(buffer).swap64() +} - req.on('response', function (res) { - clearTimeout(reqTimeout); +function toBuffer (buffer) { + if (Buffer.isBuffer(buffer)) return buffer + return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength) +} - const headers = createHeadersLenient(res.headers); +function toString (buffer, encoding, start, end) { + return toBuffer(buffer).toString(encoding, start, end) +} - // HTTP fetch step 5 - if (fetch.isRedirect(res.statusCode)) { - // HTTP fetch step 5.2 - const location = headers.get('Location'); +function write (buffer, string, offset, length, encoding) { + return toBuffer(buffer).write(string, offset, length, encoding) +} - // 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; - } - } +function writeDoubleLE (buffer, value, offset) { + return toBuffer(buffer).writeDoubleLE(value, offset) +} - // 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; - } +function writeFloatLE (buffer, value, offset) { + return toBuffer(buffer).writeFloatLE(value, offset) +} - // HTTP-redirect fetch step 5 - if (request.counter >= request.follow) { - reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); - finalize(); - return; - } +function writeUInt32LE (buffer, value, offset) { + return toBuffer(buffer).writeUInt32LE(value, offset) +} - // 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 - }; +function writeInt32LE (buffer, value, offset) { + return toBuffer(buffer).writeInt32LE(value, offset) +} - if (!isDomainOrSubdomain(request.url, locationURL)) { - for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { - requestOpts.headers.delete(name); - } - } +function readDoubleLE (buffer, offset) { + return toBuffer(buffer).readDoubleLE(offset) +} - // 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; - } +function readFloatLE (buffer, offset) { + return toBuffer(buffer).readFloatLE(offset) +} - // 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'); - } +function readUInt32LE (buffer, offset) { + return toBuffer(buffer).readUInt32LE(offset) +} - // HTTP-redirect fetch step 15 - resolve(fetch(new Request(locationURL, requestOpts))); - finalize(); - return; - } - } +function readInt32LE (buffer, offset) { + return toBuffer(buffer).readInt32LE(offset) +} - // prepare response - res.once('end', function () { - if (signal) signal.removeEventListener('abort', abortAndFinalize); - }); - let body = res.pipe(new PassThrough$1()); +module.exports = { + isBuffer, + isEncoding, + alloc, + allocUnsafe, + allocUnsafeSlow, + byteLength, + compare, + concat, + copy, + equals, + fill, + from, + includes, + indexOf, + lastIndexOf, + swap16, + swap32, + swap64, + toBuffer, + toString, + write, + writeDoubleLE, + writeFloatLE, + writeUInt32LE, + writeInt32LE, + readDoubleLE, + readFloatLE, + readUInt32LE, + readInt32LE +} - const response_options = { - url: request.url, - status: res.statusCode, - statusText: res.statusMessage, - headers: headers, - size: request.size, - timeout: request.timeout, - counter: request.counter - }; - // HTTP-network fetch step 12.1.1.3 - const codings = headers.get('Content-Encoding'); +/***/ }), - // HTTP-network fetch step 12.1.1.4: handle content codings +/***/ 9417: +/***/ ((module) => { - // 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; - } +"use strict"; - // 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 - }; +module.exports = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); - // for gzip - if (codings == 'gzip' || codings == 'x-gzip') { - body = body.pipe(zlib.createGunzip(zlibOptions)); - response = new Response(body, response_options); - resolve(response); - return; - } + var r = range(a, b, str); - // 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); - }); - return; - } + 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) + }; +} - // for br - if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { - body = body.pipe(zlib.createBrotliDecompress()); - response = new Response(body, response_options); - resolve(response); - return; - } +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} - // otherwise, use response as-is - response = new Response(body, response_options); - resolve(response); - }); +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; - writeToStream(req, request); - }); -} -/** - * 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; -}; + if (ai >= 0 && bi > 0) { + if(a===b) { + return [ai, bi]; + } + begs = []; + left = str.length; -// expose Promise -fetch.Promise = global.Promise; + 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; + } -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; + bi = str.indexOf(b, i + 1); + } + + i = ai < bi && ai >= 0 ? ai : bi; + } + + if (begs.length) { + result = [ left, right ]; + } + } + + return result; +} /***/ }), -/***/ 4410: +/***/ 83682: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var wrappy = __nccwpck_require__(4025) -module.exports = wrappy(once) -module.exports.strict = wrappy(onceStrict) +var register = __nccwpck_require__(44670) +var addHook = __nccwpck_require__(5549) +var removeHook = __nccwpck_require__(6819) -once.proto = once(function () { - Object.defineProperty(Function.prototype, 'once', { - value: function () { - return once(this) - }, - configurable: true - }) +// bind with array of arguments: https://stackoverflow.com/a/21792913 +var bind = Function.bind +var bindable = bind.bind(bind) - Object.defineProperty(Function.prototype, 'onceStrict', { - value: function () { - return onceStrict(this) - }, - configurable: true +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 once (fn) { - var f = function () { - if (f.called) return f.value - f.called = true - return f.value = fn.apply(this, arguments) +function HookSingular () { + var singularHookName = 'h' + var singularHookState = { + registry: {} } - f.called = false - return f + var singularHook = register.bind(null, singularHookState, singularHookName) + bindApi(singularHook, singularHookState, singularHookName) + return singularHook } -function onceStrict (fn) { - var f = function () { - if (f.called) - throw new Error(f.onceError) - f.called = true - return f.value = fn.apply(this, arguments) +function HookCollection () { + var state = { + registry: {} } - var name = fn.name || 'Function wrapped with `once`' - f.onceError = name + " shouldn't be called more than once" - f.called = false - return f + + 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 + /***/ }), -/***/ 3985: +/***/ 5549: /***/ ((module) => { -"use strict"; +module.exports = addHook; +function addHook(state, kind, name, hook) { + var orig = hook; + if (!state.registry[name]) { + state.registry[name] = []; + } -function posix(path) { - return path.charAt(0) === '/'; -} + if (kind === "before") { + hook = function (method, options) { + return Promise.resolve() + .then(orig.bind(null, options)) + .then(method.bind(null, options)); + }; + } -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) !== ':'); + 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; + }); + }; + } - // UNC paths are always absolute - return Boolean(result[2] || isUnc); -} + if (kind === "error") { + hook = function (method, options) { + return Promise.resolve() + .then(method.bind(null, options)) + .catch(function (error) { + return orig(error, options); + }); + }; + } -module.exports = process.platform === 'win32' ? win32 : posix; -module.exports.posix = posix; -module.exports.win32 = win32; + state.registry[name].push({ + hook: hook, + orig: orig, + }); +} /***/ }), -/***/ 1464: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 44670: +/***/ ((module) => { -"use strict"; -/*eslint no-var:0, prefer-arrow-callback: 0, object-shorthand: 0 */ +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 = {}; + } -var Punycode = __nccwpck_require__(5477); + 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); + } -var internals = {}; + return state.registry[name].reduce(function (method, registered) { + return registered.hook.bind(null, method, options); + }, method)(); + }); +} -// -// Read rules from file. -// -internals.rules = (__nccwpck_require__(7672).map)(function (rule) { +/***/ }), - return { - rule: rule, - suffix: rule.replace(/^(\*\.|\!)/, ''), - punySuffix: -1, - wildcard: rule.charAt(0) === '*', - exception: rule.charAt(0) === '!' - }; -}); +/***/ 6819: +/***/ ((module) => { +module.exports = removeHook; -// -// Check is given string ends with `suffix`. -// -internals.endsWith = function (str, suffix) { +function removeHook(state, name, method) { + if (!state.registry[name]) { + return; + } - return str.indexOf(suffix, str.length - suffix.length) !== -1; -}; + var index = state.registry[name] + .map(function (registered) { + return registered.orig; + }) + .indexOf(method); + if (index === -1) { + return; + } -// -// Find rule for a given domain. -// -internals.findRule = function (domain) { + state.registry[name].splice(index, 1); +} - var punyDomain = Punycode.toASCII(domain); - return internals.rules.reduce(function (memo, rule) { - if (rule.punySuffix === -1){ - rule.punySuffix = Punycode.toASCII(rule.suffix); - } - if (!internals.endsWith(punyDomain, '.' + rule.punySuffix) && punyDomain !== rule.punySuffix) { - return memo; - } - // This has been commented out as it never seems to run. This is because - // sub tlds always appear after their parents and we never find a shorter - // match. - //if (memo) { - // var memoSuffix = Punycode.toASCII(memo.suffix); - // if (memoSuffix.length >= punySuffix.length) { - // return memo; - // } - //} - return rule; - }, null); -}; +/***/ }), +/***/ 66474: +/***/ ((module, exports, __nccwpck_require__) => { -// -// Error codes and messages. -// -exports.errorCodes = { - DOMAIN_TOO_SHORT: 'Domain name too short.', - DOMAIN_TOO_LONG: 'Domain name too long. It should be no more than 255 chars.', - LABEL_STARTS_WITH_DASH: 'Domain name label can not start with a dash.', - LABEL_ENDS_WITH_DASH: 'Domain name label can not end with a dash.', - LABEL_TOO_LONG: 'Domain name label should be at most 63 chars long.', - LABEL_TOO_SHORT: 'Domain name label should be at least 1 character long.', - LABEL_INVALID_CHARS: 'Domain name label can only contain alphanumeric characters or dashes.' -}; - - -// -// Validate domain name and throw if not valid. -// -// From wikipedia: -// -// Hostnames are composed of series of labels concatenated with dots, as are all -// domain names. Each label must be between 1 and 63 characters long, and the -// entire hostname (including the delimiting dots) has a maximum of 255 chars. -// -// Allowed chars: -// -// * `a-z` -// * `0-9` -// * `-` but not as a starting or ending character -// * `.` as a separator for the textual portions of a domain name -// -// * http://en.wikipedia.org/wiki/Domain_name -// * http://en.wikipedia.org/wiki/Hostname -// -internals.validate = function (input) { - - // Before we can validate we need to take care of IDNs with unicode chars. - var ascii = Punycode.toASCII(input); - - if (ascii.length < 1) { - return 'DOMAIN_TOO_SHORT'; - } - if (ascii.length > 255) { - return 'DOMAIN_TOO_LONG'; - } +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); - // Check each part's length and allowed chars. - var labels = ascii.split('.'); - var label; - - for (var i = 0; i < labels.length; ++i) { - label = labels[i]; - if (!label.length) { - return 'LABEL_TOO_SHORT'; +exports = module.exports = function (bufOrEm, eventName) { + if (Buffer.isBuffer(bufOrEm)) { + return exports.parse(bufOrEm); } - if (label.length > 63) { - return 'LABEL_TOO_LONG'; + + var s = exports.stream(); + if (bufOrEm && bufOrEm.pipe) { + bufOrEm.pipe(s); } - if (label.charAt(0) === '-') { - return 'LABEL_STARTS_WITH_DASH'; + else if (bufOrEm) { + bufOrEm.on(eventName || 'data', function (buf) { + s.write(buf); + }); + + bufOrEm.on('end', function () { + s.end(); + }); } - if (label.charAt(label.length - 1) === '-') { - return 'LABEL_ENDS_WITH_DASH'; + 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(); } - if (!/^[a-z0-9\-]+$/.test(label)) { - return 'LABEL_INVALID_CHARS'; + + 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; }; +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; +}; -// -// Public API -// +// 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; +} +// 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; +} -// -// Parse domain. -// -exports.parse = function (input) { +// 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; +} - if (typeof input !== 'string') { - throw new TypeError('Domain name must be a string.'); - } +// 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; +} - // Force domain to lowercase. - var domain = input.slice(0).toLowerCase(); +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; +} - // Handle FQDN. - // TODO: Simply remove trailing dot? - if (domain.charAt(domain.length - 1) === '.') { - domain = domain.slice(0, domain.length - 1); - } - // Validate and sanitise input. - var error = internals.validate(domain); - if (error) { - return { - input: input, - error: { - message: exports.errorCodes[error], - code: error - } - }; - } +/***/ }), - var parsed = { - input: input, - tld: null, - sld: null, - domain: null, - subdomain: null, - listed: false - }; +/***/ 13755: +/***/ ((module) => { - var domainParts = domain.split('.'); +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; + } + } + + var vars = { + get : function (name) { + return getset(name); + }, + set : function (name, value) { + return getset(name, value); + }, + store : store || {}, + }; + return vars; +}; - // Non-Internet TLD - if (domainParts[domainParts.length - 1] === 'local') { - return parsed; - } - var handlePunycode = function () { +/***/ }), - if (!/xn--/.test(domain)) { - return parsed; - } - if (parsed.domain) { - parsed.domain = Punycode.toASCII(parsed.domain); - } - if (parsed.subdomain) { - parsed.subdomain = Punycode.toASCII(parsed.subdomain); - } - return parsed; - }; +/***/ 11174: +/***/ (function(module) { - var rule = internals.findRule(domain); +/** + * 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'; - // Unlisted tld. - if (!rule) { - if (domainParts.length < 2) { - return parsed; - } - parsed.tld = domainParts.pop(); - parsed.sld = domainParts.pop(); - parsed.domain = [parsed.sld, parsed.tld].join('.'); - if (domainParts.length) { - parsed.subdomain = domainParts.pop(); - } - return handlePunycode(); - } + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - // At this point we know the public suffix is listed. - parsed.listed = true; + function getCjsExportFromNamespace (n) { + return n && n['default'] || n; + } - var tldParts = rule.suffix.split('.'); - var privateParts = domainParts.slice(0, domainParts.length - tldParts.length); + 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 (rule.exception) { - privateParts.push(tldParts.shift()); - } + 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; + }; - parsed.tld = tldParts.join('.'); + var parser = { + load: load, + overwrite: overwrite + }; - if (!privateParts.length) { - return handlePunycode(); - } + var DLList; + + DLList = class DLList { + constructor(incr, decr) { + this.incr = incr; + this.decr = decr; + this._first = null; + this._last = null; + this.length = 0; + } + + 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; + } + + first() { + if (this._first != null) { + return this._first.value; + } + } + + getArray() { + var node, ref, results; + node = this._first; + results = []; + while (node != null) { + results.push((ref = node, node = node.next, ref.value)); + } + return results; + } + + 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; + } - if (rule.wildcard) { - tldParts.unshift(privateParts.pop()); - parsed.tld = tldParts.join('.'); - } + }; - if (!privateParts.length) { - return handlePunycode(); - } + var DLList_1 = DLList; + + var Events; + + 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 = {}; + } + }; + } + + _addListener(name, status, cb) { + var base; + if ((base = this._events)[name] == null) { + base[name] = []; + } + this._events[name].push({cb, status}); + return this.instance; + } + + listenerCount(name) { + if (this._events[name] != null) { + return this._events[name].length; + } else { + return 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; + } + } - parsed.sld = privateParts.pop(); - parsed.domain = [parsed.sld, parsed.tld].join('.'); + }; - if (privateParts.length) { - parsed.subdomain = privateParts.join('.'); - } + var Events_1 = Events; + + var DLList$1, Events$1, Queues; + + DLList$1 = DLList_1; + + Events$1 = Events_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); + } + + incr() { + if (this._length++ === 0) { + return this.Events.trigger("leftzero"); + } + } + + decr() { + if (--this._length === 0) { + return this.Events.trigger("zero"); + } + } + + push(job) { + return this._lists[job.options.priority].push(job); + } + + queued(priority) { + if (priority != null) { + return this._lists[priority].length; + } else { + return this._length; + } + } + + 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(); + } - return handlePunycode(); -}; + }; + var Queues_1 = Queues; + + var BottleneckError; + + BottleneckError = class BottleneckError extends Error {}; + + var BottleneckError_1 = BottleneckError; + + var BottleneckError$1, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser$1; + + NUM_PRIORITIES = 10; + + DEFAULT_PRIORITY = 5; + + parser$1 = parser; + + BottleneckError$1 = BottleneckError_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; + } + + _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; + } + } + + _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`); + } + } + + doReceive() { + this._states.start(this.options.id); + return this.Events.trigger("received", {args: this.args, options: this.options}); + } + + 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}); + } + + 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}); + } + + 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); + } + } + + 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); + } + + 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); + } + } + } + + doDone(eventInfo) { + this._assertStatus("EXECUTING"); + this._states.next(this.options.id); + return this.Events.trigger("done", eventInfo); + } -// -// Get domain. -// -exports.get = function (domain) { + }; - if (!domain) { - return null; - } - return exports.parse(domain).domain || null; -}; + var Job_1 = Job; + + var BottleneckError$2, LocalDatastore, parser$2; + + 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(); + } + + _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); + } + } + + async __publish__(message) { + await this.yieldLoop(); + return this.instance.Events.trigger("message", message.toString()); + } + + async __disconnect__(flush) { + await this.yieldLoop(); + clearInterval(this.heartbeat); + return this.Promise.resolve(); + } + + yieldLoop(t = 0) { + return new this.Promise(function(resolve, reject) { + return setTimeout(resolve, t); + }); + } + + computePenalty() { + var ref; + return (ref = this.storeOptions.penalty) != null ? ref : (15 * this.storeOptions.minTime) || 5000; + } + + async __updateSettings__(options) { + await this.yieldLoop(); + parser$2.overwrite(options, options, this.storeOptions); + this._startHeartbeat(); + this.instance._drainAll(this.computeCapacity()); + return true; + } + + 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; + } + + async __groupCheck__(time) { + await this.yieldLoop(); + return (this._nextRequest + this.timeout) < time; + } + + 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; + } + + async __currentReservoir__() { + await this.yieldLoop(); + return this.storeOptions.reservoir; + } + + isBlocked(now) { + return this._unblockTime >= now; + } + + check(weight, now) { + return this.conditionsCheck(weight) && (this._nextRequest - now) <= 0; + } + + async __check__(weight) { + var now; + await this.yieldLoop(); + now = Date.now(); + return this.check(weight, now); + } + + 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 + }; + } + + async __free__(index, weight) { + await this.yieldLoop(); + this._running -= weight; + this._done += weight; + this.instance._drainAll(this.computeCapacity()); + return { + running: this._running + }; + } + }; -// -// Check whether domain belongs to a known public suffix. -// -exports.isValid = function (domain) { + var LocalDatastore_1 = LocalDatastore; + + var BottleneckError$3, States; + + BottleneckError$3 = BottleneckError_1; + + States = class States { + constructor(status1) { + this.status = status1; + this._jobs = {}; + this.counts = this.status.map(function() { + return 0; + }); + } + + 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; + } + + jobStatus(id) { + var ref; + return (ref = this.status[this._jobs[id]]) != null ? ref : null; + } + + 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); + } + } + + statusCounts() { + return this.counts.reduce(((acc, v, i) => { + acc[this.status[i]] = v; + return acc; + }), {}); + } - var parsed = exports.parse(domain); - return Boolean(parsed.domain && parsed.listed); -}; + }; + var States_1 = States; + + var DLList$2, Sync; + + DLList$2 = DLList_1; + + 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(); + } + + isEmpty() { + return this._queue.length === 0; + } + + 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(); + } + } + + 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; + } -/***/ }), + }; -/***/ 9612: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var Sync_1 = Sync; -const assert = __nccwpck_require__(9491) -const path = __nccwpck_require__(1017) -const fs = __nccwpck_require__(7147) -let glob = undefined -try { - glob = __nccwpck_require__(7004) -} catch (_err) { - // treat glob as optional. -} + var version = "2.19.5"; + var version$1 = { + version: version + }; -const defaultGlobOpts = { - nosort: true, - silent: true -} + var version$2 = /*#__PURE__*/Object.freeze({ + version: version, + default: version$1 + }); -// for EMFILE handling -let timeout = 0 + var require$$2 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); + + var require$$3 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); + + var require$$4 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); + + var Events$2, Group, IORedisConnection$1, RedisConnection$1, Scripts$1, parser$3; + + parser$3 = parser; + + Events$2 = Events_1; + + RedisConnection$1 = require$$2; + + 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})); + } + } + } + + 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; + } + + keys() { + return Object.keys(this.instances); + } + + 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; + } + + _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(); + } + } + + disconnect(flush = true) { + var ref; + if (!this.sharedConnection) { + return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; + } + } + + } + Group.prototype.defaults = { + timeout: 1000 * 60 * 5, + connection: null, + Promise: Promise, + id: "group-key" + }; + + return Group; + + }).call(commonjsGlobal); + + var Group_1 = Group; + + var Batcher, Events$3, parser$4; + + parser$4 = parser; + + Events$3 = Events_1; + + 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(); + } + + _resetPromise() { + return this._promise = new this.Promise((res, rej) => { + return this._resolve = res; + }); + } + + _flush() { + clearTimeout(this._timeout); + this._lastFlush = Date.now(); + this._resolve(); + this.Events.trigger("batch", this._arr); + this._arr = []; + return this._resetPromise(); + } + + 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; + } + + } + Batcher.prototype.defaults = { + maxTime: null, + maxSize: null, + Promise: Promise + }; + + return Batcher; + + }).call(commonjsGlobal); + + var Batcher_1 = Batcher; + + var require$$4$1 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); + + 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; + + DEFAULT_PRIORITY$1 = 5; + + parser$5 = parser; + + Queues$1 = Queues_1; + + Job$1 = Job_1; + + LocalDatastore$1 = LocalDatastore_1; + + RedisDatastore$1 = require$$4$1; + + Events$4 = Events_1; + + States$1 = States_1; + + Sync$1 = Sync_1; + + 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; + } + + clients() { + return this._store.clients; + } + + channel() { + return `b_${this.id}`; + } + + channel_client() { + return `b_${this.id}_${this._store.clientId}`; + } + + publish(message) { + return this._store.__publish__(message); + } + + disconnect(flush = true) { + return this._store.__disconnect__(flush); + } + + chain(_limiter) { + this._limiter = _limiter; + return this; + } + + queued(priority) { + return this._queues.queued(priority); + } + + clusterQueued() { + return this._store.__queued__(); + } + + empty() { + return this.queued() === 0 && this._submitLock.isEmpty(); + } + + running() { + return this._store.__running__(); + } + + done() { + return this._store.__done__(); + } + + jobStatus(id) { + return this._states.jobStatus(id); + } + + jobs(status) { + return this._states.statusJobs(status); + } + + counts() { + return this._states.statusCounts(); + } + + _randomIndex() { + return Math.random().toString(36).slice(2); + } + + 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 + }; + } + + _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); + } + }); + }); + } + + _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); + }); + } + + _dropAllQueued(message) { + return this._queues.shiftAll(function(job) { + return job.doDrop({message}); + }); + } + + 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; + } + + 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; + } + + _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); + } + } + + 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); + } + + 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; + } + + 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; + } + + async updateSettings(options = {}) { + await this._store.__updateSettings__(parser$5.overwrite(options, this.storeDefaults)); + parser$5.overwrite(options, this.instanceDefaults, this); + return this; + } + + currentReservoir() { + return this._store.__currentReservoir__(); + } + + incrementReservoir(incr = 0) { + return this._store.__incrementReservoir__(incr); + } + + } + Bottleneck.default = Bottleneck; + + Bottleneck.Events = Events$4; + + Bottleneck.version = Bottleneck.prototype.version = require$$8.version; + + Bottleneck.strategy = Bottleneck.prototype.strategy = { + LEAK: 1, + OVERFLOW: 2, + OVERFLOW_PRIORITY: 4, + BLOCK: 3 + }; + + Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = BottleneckError_1; + + Bottleneck.Group = Bottleneck.prototype.Group = Group_1; + + Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = require$$2; + + Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = require$$3; + + Bottleneck.Batcher = Bottleneck.prototype.Batcher = Batcher_1; + + Bottleneck.prototype.jobDefaults = { + priority: DEFAULT_PRIORITY$1, + weight: 1, + expiration: null, + id: "" + }; + + 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 + }; + + Bottleneck.prototype.stopDefaults = { + enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", + dropWaitingJobs: true, + dropErrorMessage: "This limiter has been stopped." + }; + + return Bottleneck; + + }).call(commonjsGlobal); + + var Bottleneck_1 = Bottleneck; + + var lib = Bottleneck_1; -const isWindows = (process.platform === "win32") + return lib; + +}))); -const defaults = options => { - const methods = [ - 'unlink', - 'chmod', - 'stat', - 'lstat', - 'rmdir', - 'readdir' - ] - methods.forEach(m => { - options[m] = options[m] || fs[m] - m = m + 'Sync' - options[m] = options[m] || fs[m] - }) - options.maxBusyTries = options.maxBusyTries || 3 - options.emfileWait = options.emfileWait || 1000 - if (options.glob === false) { - options.disableGlob = true - } - if (options.disableGlob !== true && glob === undefined) { - throw Error('glob dependency not found, set `options.disableGlob = true` if intentional') - } - options.disableGlob = options.disableGlob || false - options.glob = options.glob || defaultGlobOpts -} +/***/ }), -const rimraf = (p, options, cb) => { - if (typeof options === 'function') { - cb = options - options = {} - } +/***/ 33717: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - assert(p, 'rimraf: missing path') - assert.equal(typeof p, 'string', 'rimraf: path should be a string') - assert.equal(typeof cb, 'function', 'rimraf: callback function required') - assert(options, 'rimraf: invalid options argument provided') - assert.equal(typeof options, 'object', 'rimraf: options should be object') +var concatMap = __nccwpck_require__(86891); +var balanced = __nccwpck_require__(9417); - defaults(options) +module.exports = expandTop; - let busyTries = 0 - let errState = null - let n = 0 +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'; - const next = (er) => { - errState = errState || er - if (--n === 0) - cb(errState) - } +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} - const afterGlob = (er, results) => { - if (er) - return cb(er) +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} - n = results.length - if (n === 0) - return cb() +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} - results.forEach(p => { - const CB = (er) => { - if (er) { - if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && - busyTries < options.maxBusyTries) { - busyTries ++ - // try again, with the same exact callback as this one. - return setTimeout(() => rimraf_(p, options, CB), busyTries * 100) - } - // this one won't happen if graceful-fs is used. - if (er.code === "EMFILE" && timeout < options.emfileWait) { - return setTimeout(() => rimraf_(p, options, CB), timeout ++) - } +// 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 ['']; - // already gone - if (er.code === "ENOENT") er = null - } + var parts = []; + var m = balanced('{', '}', str); - timeout = 0 - next(er) - } - rimraf_(p, options, CB) - }) - } + if (!m) + return str.split(','); - if (options.disableGlob || !glob.hasMagic(p)) - return afterGlob(null, [p]) + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); - options.lstat(p, (er, stat) => { - if (!er) - return afterGlob(null, [p]) + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } - glob(p, options.glob, afterGlob) - }) + parts.push.apply(parts, p); + return parts; } -// Two possible strategies. -// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR -// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR -// -// Both result in an extra syscall when you guess wrong. However, there -// are likely far more normal files in the world than directories. This -// is based on the assumption that a the average number of files per -// directory is >= 1. -// -// If anyone ever complains about this, then I guess the strategy could -// be made configurable somehow. But until then, YAGNI. -const rimraf_ = (p, options, cb) => { - assert(p) - assert(options) - assert(typeof cb === 'function') - - // sunos lets the root user unlink directories, which is... weird. - // so we have to lstat here and make sure it's not a dir. - options.lstat(p, (er, st) => { - if (er && er.code === "ENOENT") - return cb(null) - - // Windows can EPERM on stat. Life is suffering. - if (er && er.code === "EPERM" && isWindows) - fixWinEPERM(p, options, er, cb) +function expandTop(str) { + if (!str) + return []; - if (st && st.isDirectory()) - return rmdir(p, options, er, cb) + // 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); + } - options.unlink(p, er => { - if (er) { - if (er.code === "ENOENT") - return cb(null) - if (er.code === "EPERM") - return (isWindows) - ? fixWinEPERM(p, options, er, cb) - : rmdir(p, options, er, cb) - if (er.code === "EISDIR") - return rmdir(p, options, er, cb) - } - return cb(er) - }) - }) + return expand(escapeBraces(str), true).map(unescapeBraces); } -const fixWinEPERM = (p, options, er, cb) => { - assert(p) - assert(options) - assert(typeof cb === 'function') - - options.chmod(p, 0o666, er2 => { - if (er2) - cb(er2.code === "ENOENT" ? null : er) - else - options.stat(p, (er3, stats) => { - if (er3) - cb(er3.code === "ENOENT" ? null : er) - else if (stats.isDirectory()) - rmdir(p, options, er, cb) - else - options.unlink(p, cb) - }) - }) +function identity(e) { + return e; } -const fixWinEPERMSync = (p, options, er) => { - assert(p) - assert(options) - - try { - options.chmodSync(p, 0o666) - } catch (er2) { - if (er2.code === "ENOENT") - return - else - throw er - } - - let stats - try { - stats = options.statSync(p) - } catch (er3) { - if (er3.code === "ENOENT") - return - else - throw er - } - - if (stats.isDirectory()) - rmdirSync(p, options, er) - else - options.unlinkSync(p) -} - -const rmdir = (p, options, originalEr, cb) => { - assert(p) - assert(options) - assert(typeof cb === 'function') - - // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) - // if we guessed wrong, and it's not a directory, then - // raise the original error. - options.rmdir(p, er => { - if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) - rmkids(p, options, cb) - else if (er && er.code === "ENOTDIR") - cb(originalEr) - else - cb(er) - }) +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); } -const rmkids = (p, options, cb) => { - assert(p) - assert(options) - assert(typeof cb === 'function') - - options.readdir(p, (er, files) => { - if (er) - return cb(er) - let n = files.length - if (n === 0) - return options.rmdir(p, cb) - let errState - files.forEach(f => { - rimraf(path.join(p, f), options, er => { - if (errState) - return - if (er) - return cb(errState = er) - if (--n === 0) - options.rmdir(p, cb) - }) - }) - }) +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; } -// this looks simpler, and is strictly *faster*, but will -// tie up the JavaScript thread and fail on excessively -// deep directory trees. -const rimrafSync = (p, options) => { - options = options || {} - defaults(options) +function expand(str, isTop) { + var expansions = []; - assert(p, 'rimraf: missing path') - assert.equal(typeof p, 'string', 'rimraf: path should be a string') - assert(options, 'rimraf: missing options') - assert.equal(typeof options, 'object', 'rimraf: options should be object') + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; - let results + 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]; + } - if (options.disableGlob || !glob.hasMagic(p)) { - results = [p] + var n; + if (isSequence) { + n = m.body.split(/\.\./); } else { - try { - options.lstatSync(p) - results = [p] - } catch (er) { - results = glob.sync(p, options.glob) + 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; + }); + } } } - if (!results.length) - return + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. - for (let i = 0; i < results.length; i++) { - const p = results[i] + // 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) + : ['']; - let st - try { - st = options.lstatSync(p) - } catch (er) { - if (er.code === "ENOENT") - return + var N; - // Windows can EPERM on stat. Life is suffering. - if (er.code === "EPERM" && isWindows) - fixWinEPERMSync(p, options, er) + 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); - try { - // sunos lets the root user unlink directories, which is... weird. - if (st && st.isDirectory()) - rmdirSync(p, options, null) - else - options.unlinkSync(p) - } catch (er) { - if (er.code === "ENOENT") - return - if (er.code === "EPERM") - return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) - if (er.code !== "EISDIR") - throw er + N = []; - rmdirSync(p, options, er) + 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) }); } -} -const rmdirSync = (p, options, originalEr) => { - assert(p) - assert(options) - - try { - options.rmdirSync(p) - } catch (er) { - if (er.code === "ENOENT") - return - if (er.code === "ENOTDIR") - throw originalEr - if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") - rmkidsSync(p, options) - } -} - -const rmkidsSync = (p, options) => { - assert(p) - assert(options) - options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options)) - - // We only end up here once we got ENOTEMPTY at least once, and - // at this point, we are guaranteed to have removed all the kids. - // So, we know that it won't be ENOENT or ENOTDIR or anything else. - // try really hard to delete stuff on windows, because it has a - // PROFOUNDLY annoying habit of not closing handles promptly when - // files are deleted, resulting in spurious ENOTEMPTY errors. - const retries = isWindows ? 100 : 1 - let i = 0 - do { - let threw = true - try { - const ret = options.rmdirSync(p, options) - threw = false - return ret - } finally { - if (++i < retries && threw) - continue + 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); } - } while (true) + } + + return expansions; } -module.exports = rimraf -rimraf.sync = rimrafSync /***/ }), -/***/ 3702: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 51590: +/***/ ((module) => { -;(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 +module.exports = Buffers; + +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); +} + +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; +}; + +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; +}; + +Buffers.prototype.copy = function (dst, dStart, start, end) { + return this.slice(start, end).copy(dst, dStart, 0, end - start); +}; + +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; +}; - // 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 +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 buffers = [ - 'comment', 'sgmlDecl', 'textNode', 'tagName', 'doctype', - 'procInstName', 'procInstBody', 'entity', 'attribName', - 'attribValue', 'cdata', 'script' - ] +Buffers.prototype.get = function get (i) { + var pos = this.pos(i); - sax.EVENTS = [ - 'text', - 'processinginstruction', - 'sgmldeclaration', - 'doctype', - 'comment', - 'opentagstart', - 'attribute', - 'opentag', - 'closetag', - 'opencdata', - 'cdata', - 'closecdata', - 'error', - 'end', - 'ready', - 'script', - 'opennamespace', - 'closenamespace' - ] + return this.buffers[pos.buf].get(pos.offset); +}; - function SAXParser (strict, opt) { - if (!(this instanceof SAXParser)) { - return new SAXParser(strict, opt) - } +Buffers.prototype.set = function set (i, b) { + var pos = this.pos(i); - 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 = [] + return this.buffers[pos.buf].set(pos.offset, b); +}; - // 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) +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'); } - // mostly just for error reporting - parser.trackPosition = parser.opt.position !== false - if (parser.trackPosition) { - parser.position = parser.line = parser.column = 0 + if (!needle.length) { + return 0; } - emit(parser, 'onready') - } - if (!Object.create) { - Object.create = function (o) { - function F () {} - F.prototype = o - var newf = new F() - return newf + if (!this.length) { + return -1; } - } - if (!Object.keys) { - Object.keys = function (o) { - var a = [] - for (var i in o) if (o.hasOwnProperty(i)) a.push(i) - return a + var i = 0, j = 0, match = 0, mstart, pos = 0; + + // 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; } - } - 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 + // for each character in virtual buffer + for (;;) { + while (j >= this.buffers[i].length) { + j = 0; + i++; - case 'cdata': - emitNode(parser, 'oncdata', parser.cdata) - parser.cdata = '' - break + if (i >= this.buffers.length) { + // search string not found + return -1; + } + } - case 'script': - emitNode(parser, 'onscript', parser.script) - parser.script = '' - break + var char = this.buffers[i][j]; - default: - error(parser, 'Max buffer length exceeded: ' + buffers[i]) + 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; } - } - 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 - } - function clearBuffers (parser) { - for (var i = 0, l = buffers.length; i < l; i++) { - parser[buffers[i]] = '' + j++; + pos++; } +}; + +Buffers.prototype.toBuffer = function() { + return this.slice(); +} + +Buffers.prototype.toString = function(encoding, start, end) { + return this.slice(start, end).toString(encoding); +} + + +/***/ }), + +/***/ 46533: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var Traverse = __nccwpck_require__(8588); +var EventEmitter = (__nccwpck_require__(82361).EventEmitter); + +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(); +}; + +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(); +}; + +Chainsaw.saw = function (builder, handlers) { + var saw = new EventEmitter; + saw.handlers = handlers; + saw.actions = []; + + saw.chain = function () { + var ch = Traverse(saw.handlers).map(function (node) { + if (this.isRoot) return node; + var ps = this.path; + + if (typeof node === 'function') { + this.update(function () { + saw.actions.push({ + path : ps, + args : [].slice.call(arguments) + }); + return ch; + }); + } + }); + + process.nextTick(function () { + saw.emit('begin'); + saw.next(); + }); + + return ch; + }; + + saw.pop = function () { + return saw.actions.shift(); + }; + + saw.next = function () { + var action = saw.pop(); + + 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); + } + }; + + saw.nest = function (cb) { + var args = [].slice.call(arguments, 1); + var autonext = true; + + if (typeof cb === 'boolean') { + var autonext = cb; + cb = args.shift(); + } + + var s = Chainsaw.saw(builder, {}); + var r = builder.call(s.handlers, s); + + if (r !== undefined) s.handlers = r; + + // If we are recording... + if ("undefined" !== typeof saw.step) { + // ... our children should, too + s.record(); + } + + cb.apply(s.chain(), args); + if (autonext !== false) s.on('end', saw.next); + }; + + saw.record = function () { + upgradeChainsaw(saw); + }; + + ['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."); + }; + }); + + return saw; +}; + +function upgradeChainsaw(saw) { + saw.step = 0; + + // override pop + saw.pop = function () { + return saw.actions[saw.step++]; + }; + + saw.trap = function (name, cb) { + var ps = Array.isArray(name) ? name : [name]; + saw.actions.push({ + path : ps, + step : saw.step, + cb : cb, + trap : true + }); + }; + + 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); + + if (i >= 0) saw.step += i; + else saw.step = saw.actions.length; + + var act = saw.actions[saw.step - 1]; + if (act && act.trap) { + // It's a trap! + saw.step = act.step; + act.cb(); + } + else saw.next(); + }; + + saw.jump = function (step) { + saw.step = step; + saw.next(); + }; +}; + + +/***/ }), + +/***/ 85443: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var util = __nccwpck_require__(73837); +var Stream = (__nccwpck_require__(12781).Stream); +var DelayedStream = __nccwpck_require__(18611); + +module.exports = CombinedStream; +function CombinedStream() { + this.writable = false; + this.readable = true; + this.dataSize = 0; + this.maxDataSize = 2 * 1024 * 1024; + this.pauseStreams = true; + + this._released = false; + this._streams = []; + this._currentStream = null; + this._insideLoop = false; + this._pendingNext = false; +} +util.inherits(CombinedStream, Stream); + +CombinedStream.create = function(options) { + var combinedStream = new this(); + + options = options || {}; + for (var option in options) { + combinedStream[option] = options[option]; } - function flushBuffers (parser) { - closeText(parser) - if (parser.cdata !== '') { - emitNode(parser, 'oncdata', parser.cdata) - parser.cdata = '' + return combinedStream; +}; + +CombinedStream.isStreamLike = function(stream) { + return (typeof stream !== 'function') + && (typeof stream !== 'string') + && (typeof stream !== 'boolean') + && (typeof stream !== 'number') + && (!Buffer.isBuffer(stream)); +}; + +CombinedStream.prototype.append = function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + + 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; } - if (parser.script !== '') { - emitNode(parser, 'onscript', parser.script) - parser.script = '' + + this._handleErrors(stream); + + if (this.pauseStreams) { + stream.pause(); } } - 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) } + this._streams.push(stream); + return this; +}; + +CombinedStream.prototype.pipe = function(dest, options) { + Stream.prototype.pipe.call(this, dest, options); + this.resume(); + return dest; +}; + +CombinedStream.prototype._getNext = function() { + this._currentStream = null; + + if (this._insideLoop) { + this._pendingNext = true; + return; // defer call } - var Stream + this._insideLoop = true; try { - Stream = (__nccwpck_require__(2781).Stream) - } catch (ex) { - Stream = function () {} + do { + this._pendingNext = false; + this._realGetNext(); + } while (this._pendingNext); + } finally { + this._insideLoop = false; } +}; - var streamWraps = sax.EVENTS.filter(function (ev) { - return ev !== 'error' && ev !== 'end' - }) +CombinedStream.prototype._realGetNext = function() { + var stream = this._streams.shift(); - function createStream (strict, opt) { - return new SAXStream(strict, opt) + + if (typeof stream == 'undefined') { + this.end(); + return; } - function SAXStream (strict, opt) { - if (!(this instanceof SAXStream)) { - return new SAXStream(strict, opt) + 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); } - Stream.apply(this) + this._pipeNext(stream); + }.bind(this)); +}; - this._parser = new SAXParser(strict, opt) - this.writable = true - this.readable = true +CombinedStream.prototype._pipeNext = function(stream) { + this._currentStream = stream; - var me = this + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('end', this._getNext.bind(this)); + stream.pipe(this, {end: false}); + return; + } - this._parser.onend = function () { - me.emit('end') - } + var value = stream; + this.write(value); + this._getNext(); +}; - this._parser.onerror = function (er) { - me.emit('error', er) +CombinedStream.prototype._handleErrors = function(stream) { + var self = this; + stream.on('error', function(err) { + self._emitError(err); + }); +}; - // if didn't throw, then means error was handled. - // go ahead and clear error, so we can write again. - me._parser.error = null - } +CombinedStream.prototype.write = function(data) { + this.emit('data', data); +}; - this._decoder = null +CombinedStream.prototype.pause = function() { + if (!this.pauseStreams) { + return; + } - 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 - }) - }) + 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(); } - SAXStream.prototype = Object.create(Stream.prototype, { - constructor: { - value: SAXStream - } - }) + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); + this.emit('resume'); +}; - SAXStream.prototype.write = function (data) { - if (typeof Buffer === 'function' && - typeof Buffer.isBuffer === 'function' && - Buffer.isBuffer(data)) { - if (!this._decoder) { - var SD = (__nccwpck_require__(1576).StringDecoder) - this._decoder = new SD('utf8') - } - data = this._decoder.write(data) - } +CombinedStream.prototype.end = function() { + this._reset(); + this.emit('end'); +}; - this._parser.write(data.toString()) - this.emit('data', data) - return true +CombinedStream.prototype.destroy = function() { + this._reset(); + this.emit('close'); +}; + +CombinedStream.prototype._reset = function() { + this.writable = false; + this._streams = []; + this._currentStream = null; +}; + +CombinedStream.prototype._checkDataSize = function() { + this._updateDataSize(); + if (this.dataSize <= this.maxDataSize) { + return; } - SAXStream.prototype.end = function (chunk) { - if (chunk && chunk.length) { - this.write(chunk) + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; + this._emitError(new Error(message)); +}; + +CombinedStream.prototype._updateDataSize = function() { + this.dataSize = 0; + + var self = this; + this._streams.forEach(function(stream) { + if (!stream.dataSize) { + return; } - this._parser.end() - return true + + self.dataSize += stream.dataSize; + }); + + if (this._currentStream && this._currentStream.dataSize) { + this.dataSize += this._currentStream.dataSize; } +}; - 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) - } - } +CombinedStream.prototype._emitError = function(err) { + this._reset(); + this.emit('error', err); +}; - return Stream.prototype.on.call(me, ev, handler) + +/***/ }), + +/***/ 92240: +/***/ ((module) => { + +/** + * 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() {}; + +ArchiveEntry.prototype.getName = function() {}; + +ArchiveEntry.prototype.getSize = function() {}; + +ArchiveEntry.prototype.getLastModifiedDate = function() {}; + +ArchiveEntry.prototype.isDirectory = function() {}; + +/***/ }), + +/***/ 36728: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * 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 isStream = __nccwpck_require__(41554); +var Transform = (__nccwpck_require__(45193).Transform); + +var ArchiveEntry = __nccwpck_require__(92240); +var util = __nccwpck_require__(95208); + +var ArchiveOutputStream = module.exports = function(options) { + if (!(this instanceof ArchiveOutputStream)) { + return new ArchiveOutputStream(options); } - // 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 } + Transform.call(this, options); - // 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]/ + this.offset = 0; + this._archive = { + finish: false, + finished: false, + processing: false + }; +}; - 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-]/ +inherits(ArchiveOutputStream, Transform); - 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-]/ +ArchiveOutputStream.prototype._appendBuffer = function(zae, source, callback) { + // scaffold only +}; - function isWhitespace (c) { - return c === ' ' || c === '\n' || c === '\r' || c === '\t' +ArchiveOutputStream.prototype._appendStream = function(zae, source, callback) { + // scaffold only +}; + +ArchiveOutputStream.prototype._emitErrorCallback = function(err) { + if (err) { + this.emit('error', err); } +}; - function isQuote (c) { - return c === '"' || c === '\'' +ArchiveOutputStream.prototype._finish = function(ae) { + // scaffold only +}; + +ArchiveOutputStream.prototype._normalizeEntry = function(ae) { + // scaffold only +}; + +ArchiveOutputStream.prototype._transform = function(chunk, encoding, callback) { + callback(null, chunk); +}; + +ArchiveOutputStream.prototype.entry = function(ae, source, callback) { + source = source || null; + + if (typeof callback !== 'function') { + callback = this._emitErrorCallback.bind(this); } - function isAttribEnd (c) { - return c === '>' || isWhitespace(c) + if (!(ae instanceof ArchiveEntry)) { + callback(new Error('not a valid instance of ArchiveEntry')); + return; } - function isMatch (regex, c) { - return regex.test(c) + if (this._archive.finish || this._archive.finished) { + callback(new Error('unacceptable entry after finish')); + return; } - function notMatch (regex, c) { - return !isMatch(regex, c) + if (this._archive.processing) { + callback(new Error('already processing an entry')); + return; } - 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++, //