/******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 5116: /***/ (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.saveCache = exports.restoreCache = exports.isFeatureAvailable = exports.ReserveCacheError = exports.ValidationError = void 0; const core = __importStar(__nccwpck_require__(7484)); const path = __importStar(__nccwpck_require__(6928)); const utils = __importStar(__nccwpck_require__(8299)); const cacheHttpClient = __importStar(__nccwpck_require__(3171)); const cacheTwirpClient = __importStar(__nccwpck_require__(6819)); const config_1 = __nccwpck_require__(7606); const tar_1 = __nccwpck_require__(5321); const constants_1 = __nccwpck_require__(8287); 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. Lookup is done with prefix matching. * @param restoreKeys an optional ordered list of keys to use for restoring the cache if no cache hit occurred for primaryKey * @param downloadOptions cache download options * @param enableCrossOsArchive an optional boolean enabled to restore on windows any cache created on any platform * @returns string returns the key for the cache hit, otherwise returns undefined */ function restoreCache(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { return __awaiter(this, void 0, void 0, function* () { const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); core.debug(`Cache service version: ${cacheServiceVersion}`); checkPaths(paths); switch (cacheServiceVersion) { case 'v2': return yield restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); case 'v1': default: return yield restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); } }); } exports.restoreCache = restoreCache; /** * Restores cache using the legacy Cache Service * * @param paths a list of file paths to restore from the cache * @param primaryKey an explicit key for restoring the cache. Lookup is done with prefix matching. * @param restoreKeys an optional ordered list of keys to use for restoring the cache if no cache hit occurred for primaryKey * @param options cache download options * @param enableCrossOsArchive an optional boolean enabled to restore on Windows any cache created on any platform * @returns string returns the key for the cache hit, otherwise returns undefined */ function restoreCacheV1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { return __awaiter(this, void 0, void 0, function* () { 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(); let archivePath = ''; try { // path are needed to compute version const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, { compressionMethod, enableCrossOsArchive }); if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) { // Cache not found return undefined; } if (options === null || options === void 0 ? void 0 : options.lookupOnly) { core.info('Lookup only - skipping download'); return cacheEntry.cacheKey; } archivePath = path.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); core.debug(`Archive Path: ${archivePath}`); // Download the cache from the cache entry yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options); if (core.isDebug()) { yield (0, tar_1.listTar)(archivePath, compressionMethod); } const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); core.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); yield (0, tar_1.extractTar)(archivePath, compressionMethod); core.info('Cache restored successfully'); return cacheEntry.cacheKey; } catch (error) { const typedError = error; if (typedError.name === ValidationError.name) { throw error; } else { // Supress all non-validation cache related errors because caching should be optional core.warning(`Failed to restore: ${error.message}`); } } finally { // Try to delete the archive to save space try { yield utils.unlinkFile(archivePath); } catch (error) { core.debug(`Failed to delete archive: ${error}`); } } return undefined; }); } /** * Restores cache using Cache Service v2 * * @param paths a list of file paths to restore from the cache * @param primaryKey an explicit key for restoring the cache. Lookup is done with prefix matching * @param restoreKeys an optional ordered list of keys to use for restoring the cache if no cache hit occurred for primaryKey * @param downloadOptions cache download options * @param enableCrossOsArchive an optional boolean enabled to restore on windows any cache created on any platform * @returns string returns the key for the cache hit, otherwise returns undefined */ function restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { return __awaiter(this, void 0, void 0, function* () { // Override UploadOptions to force the use of Azure options = Object.assign(Object.assign({}, options), { useAzureSdk: true }); 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); } let archivePath = ''; try { const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); const compressionMethod = yield utils.getCompressionMethod(); const request = { key: primaryKey, restoreKeys, version: utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive) }; const response = yield twirpClient.GetCacheEntryDownloadURL(request); if (!response.ok) { core.debug(`Cache not found for version ${request.version} of keys: ${keys.join(', ')}`); return undefined; } core.info(`Cache hit for: ${request.key}`); if (options === null || options === void 0 ? void 0 : options.lookupOnly) { core.info('Lookup only - skipping download'); return response.matchedKey; } archivePath = path.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); core.debug(`Archive path: ${archivePath}`); core.debug(`Starting download of archive to: ${archivePath}`); yield cacheHttpClient.downloadCache(response.signedDownloadUrl, archivePath, options); const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); core.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); if (core.isDebug()) { yield (0, tar_1.listTar)(archivePath, compressionMethod); } yield (0, tar_1.extractTar)(archivePath, compressionMethod); core.info('Cache restored successfully'); return response.matchedKey; } catch (error) { const typedError = error; if (typedError.name === ValidationError.name) { throw error; } else { // Supress all non-validation cache related errors because caching should be optional core.warning(`Failed to restore: ${error.message}`); } } finally { try { if (archivePath) { yield utils.unlinkFile(archivePath); } } catch (error) { core.debug(`Failed to delete archive: ${error}`); } } return undefined; }); } /** * 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 enableCrossOsArchive an optional boolean enabled to save cache on windows which could be restored on any platform * @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, enableCrossOsArchive = false) { return __awaiter(this, void 0, void 0, function* () { const cacheServiceVersion = (0, config_1.getCacheServiceVersion)(); core.debug(`Cache service version: ${cacheServiceVersion}`); checkPaths(paths); checkKey(key); switch (cacheServiceVersion) { case 'v2': return yield saveCacheV2(paths, key, options, enableCrossOsArchive); case 'v1': default: return yield saveCacheV1(paths, key, options, enableCrossOsArchive); } }); } exports.saveCache = saveCache; /** * Save cache using the legacy Cache Service * * @param paths * @param key * @param options * @param enableCrossOsArchive * @returns */ function saveCacheV1(paths, key, options, enableCrossOsArchive = false) { var _a, _b, _c, _d, _e; return __awaiter(this, void 0, void 0, function* () { const compressionMethod = yield utils.getCompressionMethod(); let cacheId = -1; 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 (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); if (core.isDebug()) { yield (0, 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 && !(0, config_1.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, enableCrossOsArchive, 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); } catch (error) { const typedError = error; if (typedError.name === ValidationError.name) { throw error; } else if (typedError.name === ReserveCacheError.name) { core.info(`Failed to save: ${typedError.message}`); } else { core.warning(`Failed to save: ${typedError.message}`); } } 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; }); } /** * Save cache using Cache Service v2 * * @param paths a list of file paths to restore from the cache * @param key an explicit key for restoring the cache * @param options cache upload options * @param enableCrossOsArchive an optional boolean enabled to save cache on windows which could be restored on any platform * @returns */ function saveCacheV2(paths, key, options, enableCrossOsArchive = false) { return __awaiter(this, void 0, void 0, function* () { // Override UploadOptions to force the use of Azure // ...options goes first because we want to override the default values // set in UploadOptions with these specific figures options = Object.assign(Object.assign({}, options), { uploadChunkSize: 64 * 1024 * 1024, uploadConcurrency: 8, useAzureSdk: true }); const compressionMethod = yield utils.getCompressionMethod(); const twirpClient = cacheTwirpClient.internalCacheTwirpClient(); let cacheId = -1; 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 (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); if (core.isDebug()) { yield (0, tar_1.listTar)(archivePath, compressionMethod); } 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 > constants_1.CacheFileSizeLimit && !(0, config_1.isGhes)()) { throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`); } // Set the archive size in the options, will be used to display the upload progress options.archiveSizeBytes = archiveFileSize; core.debug('Reserving Cache'); const version = utils.getCacheVersion(paths, compressionMethod, enableCrossOsArchive); const request = { key, version }; let signedUploadUrl; try { const response = yield twirpClient.CreateCacheEntry(request); if (!response.ok) { throw new Error('Response was not ok'); } signedUploadUrl = response.signedUploadUrl; } catch (error) { core.debug(`Failed to reserve cache: ${error}`); throw new ReserveCacheError(`Unable to reserve cache with key ${key}, another job may be creating this cache.`); } core.debug(`Attempting to upload cache located at: ${archivePath}`); yield cacheHttpClient.saveCache(cacheId, archivePath, signedUploadUrl, options); const finalizeRequest = { key, version, sizeBytes: `${archiveFileSize}` }; const finalizeResponse = yield twirpClient.FinalizeCacheEntryUpload(finalizeRequest); core.debug(`FinalizeCacheEntryUploadResponse: ${finalizeResponse.ok}`); if (!finalizeResponse.ok) { throw new Error(`Unable to finalize cache with key ${key}, another job may be finalizing this cache.`); } cacheId = parseInt(finalizeResponse.entryId); } catch (error) { const typedError = error; if (typedError.name === ValidationError.name) { throw error; } else if (typedError.name === ReserveCacheError.name) { core.info(`Failed to save: ${typedError.message}`); } else { core.warning(`Failed to save: ${typedError.message}`); } } 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; }); } //# sourceMappingURL=cache.js.map /***/ }), /***/ 3156: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CacheService = exports.GetCacheEntryDownloadURLResponse = exports.GetCacheEntryDownloadURLRequest = exports.FinalizeCacheEntryUploadResponse = exports.FinalizeCacheEntryUploadRequest = exports.CreateCacheEntryResponse = exports.CreateCacheEntryRequest = 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/cache.proto" (package "github.actions.results.api.v1", syntax proto3) // tslint:disable const runtime_rpc_1 = __nccwpck_require__(4420); const runtime_1 = __nccwpck_require__(8886); const runtime_2 = __nccwpck_require__(8886); const runtime_3 = __nccwpck_require__(8886); const runtime_4 = __nccwpck_require__(8886); const runtime_5 = __nccwpck_require__(8886); const cachemetadata_1 = __nccwpck_require__(9444); // @generated message type with reflection information, may provide speed optimized methods class CreateCacheEntryRequest$Type extends runtime_5.MessageType { constructor() { super("github.actions.results.api.v1.CreateCacheEntryRequest", [ { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, { no: 2, name: "key", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 3, name: "version", kind: "scalar", T: 9 /*ScalarType.STRING*/ } ]); } create(value) { const message = { key: "", version: "" }; 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 /* github.actions.results.entities.v1.CacheMetadata metadata */ 1: message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); break; case /* string key */ 2: message.key = reader.string(); break; case /* string version */ 3: message.version = 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) { /* github.actions.results.entities.v1.CacheMetadata metadata = 1; */ if (message.metadata) cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); /* string key = 2; */ if (message.key !== "") writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); /* string version = 3; */ if (message.version !== "") writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.version); 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.CreateCacheEntryRequest */ exports.CreateCacheEntryRequest = new CreateCacheEntryRequest$Type(); // @generated message type with reflection information, may provide speed optimized methods class CreateCacheEntryResponse$Type extends runtime_5.MessageType { constructor() { super("github.actions.results.api.v1.CreateCacheEntryResponse", [ { 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; } 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; } } /** * @generated MessageType for protobuf message github.actions.results.api.v1.CreateCacheEntryResponse */ exports.CreateCacheEntryResponse = new CreateCacheEntryResponse$Type(); // @generated message type with reflection information, may provide speed optimized methods class FinalizeCacheEntryUploadRequest$Type extends runtime_5.MessageType { constructor() { super("github.actions.results.api.v1.FinalizeCacheEntryUploadRequest", [ { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, { no: 2, name: "key", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 3, name: "size_bytes", kind: "scalar", T: 3 /*ScalarType.INT64*/ }, { no: 4, name: "version", kind: "scalar", T: 9 /*ScalarType.STRING*/ } ]); } create(value) { const message = { key: "", sizeBytes: "0", version: "" }; 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 /* github.actions.results.entities.v1.CacheMetadata metadata */ 1: message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); break; case /* string key */ 2: message.key = reader.string(); break; case /* int64 size_bytes */ 3: message.sizeBytes = reader.int64().toString(); break; case /* string version */ 4: message.version = 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) { /* github.actions.results.entities.v1.CacheMetadata metadata = 1; */ if (message.metadata) cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); /* string key = 2; */ if (message.key !== "") writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); /* int64 size_bytes = 3; */ if (message.sizeBytes !== "0") writer.tag(3, runtime_1.WireType.Varint).int64(message.sizeBytes); /* string version = 4; */ if (message.version !== "") writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); 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.FinalizeCacheEntryUploadRequest */ exports.FinalizeCacheEntryUploadRequest = new FinalizeCacheEntryUploadRequest$Type(); // @generated message type with reflection information, may provide speed optimized methods class FinalizeCacheEntryUploadResponse$Type extends runtime_5.MessageType { constructor() { super("github.actions.results.api.v1.FinalizeCacheEntryUploadResponse", [ { no: 1, name: "ok", kind: "scalar", T: 8 /*ScalarType.BOOL*/ }, { no: 2, name: "entry_id", kind: "scalar", T: 3 /*ScalarType.INT64*/ } ]); } create(value) { const message = { ok: false, entryId: "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 entry_id */ 2: message.entryId = 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 entry_id = 2; */ if (message.entryId !== "0") writer.tag(2, runtime_1.WireType.Varint).int64(message.entryId); 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.FinalizeCacheEntryUploadResponse */ exports.FinalizeCacheEntryUploadResponse = new FinalizeCacheEntryUploadResponse$Type(); // @generated message type with reflection information, may provide speed optimized methods class GetCacheEntryDownloadURLRequest$Type extends runtime_5.MessageType { constructor() { super("github.actions.results.api.v1.GetCacheEntryDownloadURLRequest", [ { no: 1, name: "metadata", kind: "message", T: () => cachemetadata_1.CacheMetadata }, { no: 2, name: "key", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 3, name: "restore_keys", kind: "scalar", repeat: 2 /*RepeatType.UNPACKED*/, T: 9 /*ScalarType.STRING*/ }, { no: 4, name: "version", kind: "scalar", T: 9 /*ScalarType.STRING*/ } ]); } create(value) { const message = { key: "", restoreKeys: [], version: "" }; 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 /* github.actions.results.entities.v1.CacheMetadata metadata */ 1: message.metadata = cachemetadata_1.CacheMetadata.internalBinaryRead(reader, reader.uint32(), options, message.metadata); break; case /* string key */ 2: message.key = reader.string(); break; case /* repeated string restore_keys */ 3: message.restoreKeys.push(reader.string()); break; case /* string version */ 4: message.version = 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) { /* github.actions.results.entities.v1.CacheMetadata metadata = 1; */ if (message.metadata) cachemetadata_1.CacheMetadata.internalBinaryWrite(message.metadata, writer.tag(1, runtime_1.WireType.LengthDelimited).fork(), options).join(); /* string key = 2; */ if (message.key !== "") writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.key); /* repeated string restore_keys = 3; */ for (let i = 0; i < message.restoreKeys.length; i++) writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.restoreKeys[i]); /* string version = 4; */ if (message.version !== "") writer.tag(4, runtime_1.WireType.LengthDelimited).string(message.version); 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.GetCacheEntryDownloadURLRequest */ exports.GetCacheEntryDownloadURLRequest = new GetCacheEntryDownloadURLRequest$Type(); // @generated message type with reflection information, may provide speed optimized methods class GetCacheEntryDownloadURLResponse$Type extends runtime_5.MessageType { constructor() { super("github.actions.results.api.v1.GetCacheEntryDownloadURLResponse", [ { no: 1, name: "ok", kind: "scalar", T: 8 /*ScalarType.BOOL*/ }, { no: 2, name: "signed_download_url", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 3, name: "matched_key", kind: "scalar", T: 9 /*ScalarType.STRING*/ } ]); } create(value) { const message = { ok: false, signedDownloadUrl: "", matchedKey: "" }; 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_download_url */ 2: message.signedDownloadUrl = reader.string(); break; case /* string matched_key */ 3: message.matchedKey = reader.string(); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? runtime_2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message, writer, options) { /* bool ok = 1; */ if (message.ok !== false) writer.tag(1, runtime_1.WireType.Varint).bool(message.ok); /* string signed_download_url = 2; */ if (message.signedDownloadUrl !== "") writer.tag(2, runtime_1.WireType.LengthDelimited).string(message.signedDownloadUrl); /* string matched_key = 3; */ if (message.matchedKey !== "") writer.tag(3, runtime_1.WireType.LengthDelimited).string(message.matchedKey); 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.GetCacheEntryDownloadURLResponse */ exports.GetCacheEntryDownloadURLResponse = new GetCacheEntryDownloadURLResponse$Type(); /** * @generated ServiceType for protobuf service github.actions.results.api.v1.CacheService */ exports.CacheService = new runtime_rpc_1.ServiceType("github.actions.results.api.v1.CacheService", [ { name: "CreateCacheEntry", options: {}, I: exports.CreateCacheEntryRequest, O: exports.CreateCacheEntryResponse }, { name: "FinalizeCacheEntryUpload", options: {}, I: exports.FinalizeCacheEntryUploadRequest, O: exports.FinalizeCacheEntryUploadResponse }, { name: "GetCacheEntryDownloadURL", options: {}, I: exports.GetCacheEntryDownloadURLRequest, O: exports.GetCacheEntryDownloadURLResponse } ]); //# sourceMappingURL=cache.js.map /***/ }), /***/ 1486: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CacheServiceClientProtobuf = exports.CacheServiceClientJSON = void 0; const cache_1 = __nccwpck_require__(3156); class CacheServiceClientJSON { constructor(rpc) { this.rpc = rpc; this.CreateCacheEntry.bind(this); this.FinalizeCacheEntryUpload.bind(this); this.GetCacheEntryDownloadURL.bind(this); } CreateCacheEntry(request) { const data = cache_1.CreateCacheEntryRequest.toJson(request, { useProtoFieldName: true, emitDefaultValues: false, }); const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/json", data); return promise.then((data) => cache_1.CreateCacheEntryResponse.fromJson(data, { ignoreUnknownFields: true, })); } FinalizeCacheEntryUpload(request) { const data = cache_1.FinalizeCacheEntryUploadRequest.toJson(request, { useProtoFieldName: true, emitDefaultValues: false, }); const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/json", data); return promise.then((data) => cache_1.FinalizeCacheEntryUploadResponse.fromJson(data, { ignoreUnknownFields: true, })); } GetCacheEntryDownloadURL(request) { const data = cache_1.GetCacheEntryDownloadURLRequest.toJson(request, { useProtoFieldName: true, emitDefaultValues: false, }); const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/json", data); return promise.then((data) => cache_1.GetCacheEntryDownloadURLResponse.fromJson(data, { ignoreUnknownFields: true, })); } } exports.CacheServiceClientJSON = CacheServiceClientJSON; class CacheServiceClientProtobuf { constructor(rpc) { this.rpc = rpc; this.CreateCacheEntry.bind(this); this.FinalizeCacheEntryUpload.bind(this); this.GetCacheEntryDownloadURL.bind(this); } CreateCacheEntry(request) { const data = cache_1.CreateCacheEntryRequest.toBinary(request); const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "CreateCacheEntry", "application/protobuf", data); return promise.then((data) => cache_1.CreateCacheEntryResponse.fromBinary(data)); } FinalizeCacheEntryUpload(request) { const data = cache_1.FinalizeCacheEntryUploadRequest.toBinary(request); const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "FinalizeCacheEntryUpload", "application/protobuf", data); return promise.then((data) => cache_1.FinalizeCacheEntryUploadResponse.fromBinary(data)); } GetCacheEntryDownloadURL(request) { const data = cache_1.GetCacheEntryDownloadURLRequest.toBinary(request); const promise = this.rpc.request("github.actions.results.api.v1.CacheService", "GetCacheEntryDownloadURL", "application/protobuf", data); return promise.then((data) => cache_1.GetCacheEntryDownloadURLResponse.fromBinary(data)); } } exports.CacheServiceClientProtobuf = CacheServiceClientProtobuf; //# sourceMappingURL=cache.twirp-client.js.map /***/ }), /***/ 9444: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CacheMetadata = void 0; const runtime_1 = __nccwpck_require__(8886); const runtime_2 = __nccwpck_require__(8886); const runtime_3 = __nccwpck_require__(8886); const runtime_4 = __nccwpck_require__(8886); const runtime_5 = __nccwpck_require__(8886); const cachescope_1 = __nccwpck_require__(9425); // @generated message type with reflection information, may provide speed optimized methods class CacheMetadata$Type extends runtime_5.MessageType { constructor() { super("github.actions.results.entities.v1.CacheMetadata", [ { no: 1, name: "repository_id", kind: "scalar", T: 3 /*ScalarType.INT64*/ }, { no: 2, name: "scope", kind: "message", repeat: 1 /*RepeatType.PACKED*/, T: () => cachescope_1.CacheScope } ]); } create(value) { const message = { repositoryId: "0", scope: [] }; 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 repository_id */ 1: message.repositoryId = reader.int64().toString(); break; case /* repeated github.actions.results.entities.v1.CacheScope scope */ 2: message.scope.push(cachescope_1.CacheScope.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) { /* int64 repository_id = 1; */ if (message.repositoryId !== "0") writer.tag(1, runtime_1.WireType.Varint).int64(message.repositoryId); /* repeated github.actions.results.entities.v1.CacheScope scope = 2; */ for (let i = 0; i < message.scope.length; i++) cachescope_1.CacheScope.internalBinaryWrite(message.scope[i], writer.tag(2, 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.entities.v1.CacheMetadata */ exports.CacheMetadata = new CacheMetadata$Type(); //# sourceMappingURL=cachemetadata.js.map /***/ }), /***/ 9425: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CacheScope = void 0; const runtime_1 = __nccwpck_require__(8886); const runtime_2 = __nccwpck_require__(8886); const runtime_3 = __nccwpck_require__(8886); const runtime_4 = __nccwpck_require__(8886); const runtime_5 = __nccwpck_require__(8886); // @generated message type with reflection information, may provide speed optimized methods class CacheScope$Type extends runtime_5.MessageType { constructor() { super("github.actions.results.entities.v1.CacheScope", [ { no: 1, name: "scope", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 2, name: "permission", kind: "scalar", T: 3 /*ScalarType.INT64*/ } ]); } create(value) { const message = { scope: "", permission: "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 scope */ 1: message.scope = reader.string(); break; case /* int64 permission */ 2: message.permission = 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) { /* string scope = 1; */ if (message.scope !== "") writer.tag(1, runtime_1.WireType.LengthDelimited).string(message.scope); /* int64 permission = 2; */ if (message.permission !== "0") writer.tag(2, runtime_1.WireType.Varint).int64(message.permission); 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.entities.v1.CacheScope */ exports.CacheScope = new CacheScope$Type(); //# sourceMappingURL=cachescope.js.map /***/ }), /***/ 3171: /***/ (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.saveCache = exports.reserveCache = exports.downloadCache = exports.getCacheEntry = void 0; const core = __importStar(__nccwpck_require__(7484)); const http_client_1 = __nccwpck_require__(4844); const auth_1 = __nccwpck_require__(4552); const fs = __importStar(__nccwpck_require__(9896)); const url_1 = __nccwpck_require__(7016); const utils = __importStar(__nccwpck_require__(8299)); const uploadUtils_1 = __nccwpck_require__(5268); const downloadUtils_1 = __nccwpck_require__(5067); const options_1 = __nccwpck_require__(8356); const requestUtils_1 = __nccwpck_require__(2846); const config_1 = __nccwpck_require__(7606); const user_agent_1 = __nccwpck_require__(1899); function getCacheApiUrl(resource) { const baseUrl = (0, config_1.getCacheServiceURL)(); 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 requestOptions; } function createHttpClient() { const token = process.env['ACTIONS_RUNTIME_TOKEN'] || ''; const bearerCredentialHandler = new auth_1.BearerCredentialHandler(token); return new http_client_1.HttpClient((0, user_agent_1.getUserAgentString)(), [bearerCredentialHandler], getRequestOptions()); } function getCacheEntry(keys, paths, options) { return __awaiter(this, void 0, void 0, function* () { const httpClient = createHttpClient(); const version = utils.getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod, options === null || options === void 0 ? void 0 : options.enableCrossOsArchive); const resource = `cache?keys=${encodeURIComponent(keys.join(','))}&version=${version}`; const response = yield (0, requestUtils_1.retryTypedResponse)('getCacheEntry', () => __awaiter(this, void 0, void 0, function* () { return httpClient.getJson(getCacheApiUrl(resource)); })); // Cache not found if (response.statusCode === 204) { // List cache for primary key only if cache miss occurs if (core.isDebug()) { yield printCachesListForDiagnostics(keys[0], httpClient, version); } return null; } if (!(0, 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) { // Cache achiveLocation not found. This should never happen, and hence bail out. throw new Error('Cache not found.'); } core.setSecret(cacheDownloadUrl); core.debug(`Cache Result:`); core.debug(JSON.stringify(cacheResult)); return cacheResult; }); } exports.getCacheEntry = getCacheEntry; function printCachesListForDiagnostics(key, httpClient, version) { return __awaiter(this, void 0, void 0, function* () { const resource = `caches?key=${encodeURIComponent(key)}`; const response = yield (0, requestUtils_1.retryTypedResponse)('listCache', () => __awaiter(this, void 0, void 0, function* () { return httpClient.getJson(getCacheApiUrl(resource)); })); if (response.statusCode === 200) { const cacheListResult = response.result; const totalCount = cacheListResult === null || cacheListResult === void 0 ? void 0 : cacheListResult.totalCount; if (totalCount && totalCount > 0) { core.debug(`No matching cache found for cache key '${key}', version '${version} and scope ${process.env['GITHUB_REF']}. There exist one or more cache(s) with similar key but they have different version or scope. See more info on cache matching here: https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows#matching-a-cache-key \nOther caches with similar key:`); for (const cacheEntry of (cacheListResult === null || cacheListResult === void 0 ? void 0 : cacheListResult.artifactCaches) || []) { core.debug(`Cache Key: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.cacheKey}, Cache Version: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.cacheVersion}, Cache Scope: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.scope}, Cache Created: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.creationTime}`); } } } }); } function downloadCache(archiveLocation, archivePath, options) { return __awaiter(this, void 0, void 0, function* () { const archiveUrl = new url_1.URL(archiveLocation); const downloadOptions = (0, options_1.getDownloadOptions)(options); if (archiveUrl.hostname.endsWith('.blob.core.windows.net')) { if (downloadOptions.useAzureSdk) { // Use Azure storage SDK to download caches hosted on Azure to improve speed and reliability. yield (0, downloadUtils_1.downloadCacheStorageSDK)(archiveLocation, archivePath, downloadOptions); } else if (downloadOptions.concurrentBlobDownloads) { // Use concurrent implementation with HttpClient to work around blob SDK issue yield (0, downloadUtils_1.downloadCacheHttpClientConcurrent)(archiveLocation, archivePath, downloadOptions); } else { // Otherwise, download using the Actions http-client. yield (0, downloadUtils_1.downloadCacheHttpClient)(archiveLocation, archivePath); } } else { yield (0, downloadUtils_1.downloadCacheHttpClient)(archiveLocation, archivePath); } }); } exports.downloadCache = downloadCache; // Reserve Cache function reserveCache(key, paths, options) { return __awaiter(this, void 0, void 0, function* () { const httpClient = createHttpClient(); const version = utils.getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod, options === null || options === void 0 ? void 0 : options.enableCrossOsArchive); const reserveCacheRequest = { key, version, cacheSize: options === null || options === void 0 ? void 0 : options.cacheSize }; const response = yield (0, requestUtils_1.retryTypedResponse)('reserveCache', () => __awaiter(this, void 0, void 0, function* () { return httpClient.postJson(getCacheApiUrl('caches'), reserveCacheRequest); })); return response; }); } 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* () { 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 (0, requestUtils_1.retryHttpClientResponse)(`uploadChunk (start: ${start}, end: ${end})`, () => __awaiter(this, void 0, void 0, function* () { return httpClient.sendStream('PATCH', resourceUrl, openStream(), additionalHeaders); })); if (!(0, requestUtils_1.isSuccessStatusCode)(uploadChunkResponse.message.statusCode)) { throw new Error(`Cache service responded with ${uploadChunkResponse.message.statusCode} during upload chunk.`); } }); } 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 = (0, 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; }); } function commitCache(httpClient, cacheId, filesize) { return __awaiter(this, void 0, void 0, function* () { const commitCacheRequest = { size: filesize }; return yield (0, requestUtils_1.retryTypedResponse)('commitCache', () => __awaiter(this, void 0, void 0, function* () { return httpClient.postJson(getCacheApiUrl(`caches/${cacheId.toString()}`), commitCacheRequest); })); }); } function saveCache(cacheId, archivePath, signedUploadURL, options) { return __awaiter(this, void 0, void 0, function* () { const uploadOptions = (0, options_1.getUploadOptions)(options); if (uploadOptions.useAzureSdk) { // Use Azure storage SDK to upload caches directly to Azure if (!signedUploadURL) { throw new Error('Azure Storage SDK can only be used when a signed URL is provided.'); } yield (0, uploadUtils_1.uploadCacheArchiveSDK)(signedUploadURL, archivePath, options); } else { 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 (!(0, requestUtils_1.isSuccessStatusCode)(commitCacheResponse.statusCode)) { throw new Error(`Cache service responded with ${commitCacheResponse.statusCode} during commit cache.`); } core.info('Cache saved successfully'); } }); } exports.saveCache = saveCache; //# sourceMappingURL=cacheHttpClient.js.map /***/ }), /***/ 8299: /***/ (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()); }); }; 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.getRuntimeToken = exports.getCacheVersion = exports.assertDefined = exports.getGnuTarPathOnWindows = exports.getCacheFileName = exports.getCompressionMethod = exports.unlinkFile = exports.resolvePaths = exports.getArchiveFileSizeInBytes = exports.createTempDirectory = void 0; const core = __importStar(__nccwpck_require__(7484)); const exec = __importStar(__nccwpck_require__(5236)); const glob = __importStar(__nccwpck_require__(7206)); const io = __importStar(__nccwpck_require__(4994)); const crypto = __importStar(__nccwpck_require__(6982)); const fs = __importStar(__nccwpck_require__(9896)); const path = __importStar(__nccwpck_require__(6928)); const semver = __importStar(__nccwpck_require__(9318)); const util = __importStar(__nccwpck_require__(9023)); const constants_1 = __nccwpck_require__(8287); const versionSalt = '1.0'; // 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, crypto.randomUUID()); yield io.mkdirP(dest); return dest; }); } exports.createTempDirectory = createTempDirectory; function getArchiveFileSizeInBytes(filePath) { return fs.statSync(filePath).size; } exports.getArchiveFileSizeInBytes = getArchiveFileSizeInBytes; function resolvePaths(patterns) { var _a, e_1, _b, _c; var _d; return __awaiter(this, void 0, void 0, function* () { const paths = []; const workspace = (_d = process.env['GITHUB_WORKSPACE']) !== null && _d !== void 0 ? _d : process.cwd(); const globber = yield glob.create(patterns.join('\n'), { implicitDescendants: false }); try { for (var _e = true, _f = __asyncValues(globber.globGenerator()), _g; _g = yield _f.next(), _a = _g.done, !_a; _e = true) { _c = _g.value; _e = false; const file = _c; 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. if (relativeFile === '') { // path.relative returns empty string if workspace and file are equal paths.push('.'); } else { paths.push(`${relativeFile}`); } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (!_e && !_a && (_b = _f.return)) yield _b.call(_f); } 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, additionalArgs = []) { return __awaiter(this, void 0, void 0, function* () { let versionOutput = ''; additionalArgs.push('--version'); core.debug(`Checking ${app} ${additionalArgs.join(' ')}`); try { yield exec.exec(`${app}`, additionalArgs, { ignoreReturnCode: true, silent: true, listeners: { stdout: (data) => (versionOutput += data.toString()), stderr: (data) => (versionOutput += data.toString()) } }); } catch (err) { core.debug(err.message); } 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* () { const versionOutput = yield getVersion('zstd', ['--quiet']); const version = semver.clean(versionOutput); core.debug(`zstd version: ${version}`); if (versionOutput === '') { return constants_1.CompressionMethod.Gzip; } else { return constants_1.CompressionMethod.ZstdWithoutLong; } }); } exports.getCompressionMethod = getCompressionMethod; function getCacheFileName(compressionMethod) { return compressionMethod === constants_1.CompressionMethod.Gzip ? constants_1.CacheFilename.Gzip : constants_1.CacheFilename.Zstd; } exports.getCacheFileName = getCacheFileName; function getGnuTarPathOnWindows() { return __awaiter(this, void 0, void 0, function* () { if (fs.existsSync(constants_1.GnuTarPathOnWindows)) { return constants_1.GnuTarPathOnWindows; } const versionOutput = yield getVersion('tar'); return versionOutput.toLowerCase().includes('gnu tar') ? io.which('tar') : ''; }); } exports.getGnuTarPathOnWindows = getGnuTarPathOnWindows; function assertDefined(name, value) { if (value === undefined) { throw Error(`Expected ${name} but value was undefiend`); } return value; } exports.assertDefined = assertDefined; function getCacheVersion(paths, compressionMethod, enableCrossOsArchive = false) { // don't pass changes upstream const components = paths.slice(); // Add compression method to cache version to restore // compressed cache as per compression method if (compressionMethod) { components.push(compressionMethod); } // Only check for windows platforms if enableCrossOsArchive is false if (process.platform === 'win32' && !enableCrossOsArchive) { components.push('windows-only'); } // 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 getRuntimeToken() { const token = process.env['ACTIONS_RUNTIME_TOKEN']; if (!token) { throw new Error('Unable to get the ACTIONS_RUNTIME_TOKEN env variable'); } return token; } exports.getRuntimeToken = getRuntimeToken; //# sourceMappingURL=cacheUtils.js.map /***/ }), /***/ 7606: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getCacheServiceURL = exports.getCacheServiceVersion = exports.isGhes = void 0; 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'); const isLocalHost = hostname.endsWith('.LOCALHOST'); return !isGitHubHost && !isGheHost && !isLocalHost; } exports.isGhes = isGhes; function getCacheServiceVersion() { // Cache service v2 is not supported on GHES. We will default to // cache service v1 even if the feature flag was enabled by user. if (isGhes()) return 'v1'; return process.env['ACTIONS_CACHE_SERVICE_V2'] ? 'v2' : 'v1'; } exports.getCacheServiceVersion = getCacheServiceVersion; function getCacheServiceURL() { const version = getCacheServiceVersion(); // Based on the version of the cache service, we will determine which // URL to use. switch (version) { case 'v1': return (process.env['ACTIONS_CACHE_URL'] || process.env['ACTIONS_RESULTS_URL'] || ''); case 'v2': return process.env['ACTIONS_RESULTS_URL'] || ''; default: throw new Error(`Unsupported cache service version: ${version}`); } } exports.getCacheServiceURL = getCacheServiceURL; //# sourceMappingURL=config.js.map /***/ }), /***/ 8287: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CacheFileSizeLimit = exports.ManifestFilename = exports.TarFilename = exports.SystemTarPathOnWindows = exports.GnuTarPathOnWindows = exports.SocketTimeout = exports.DefaultRetryDelay = exports.DefaultRetryAttempts = exports.ArchiveToolType = exports.CompressionMethod = exports.CacheFilename = void 0; var CacheFilename; (function (CacheFilename) { CacheFilename["Gzip"] = "cache.tgz"; CacheFilename["Zstd"] = "cache.tzst"; })(CacheFilename || (exports.CacheFilename = 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 = CompressionMethod = {})); var ArchiveToolType; (function (ArchiveToolType) { ArchiveToolType["GNU"] = "gnu"; ArchiveToolType["BSD"] = "bsd"; })(ArchiveToolType || (exports.ArchiveToolType = ArchiveToolType = {})); // 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; // The default path of GNUtar on hosted Windows runners exports.GnuTarPathOnWindows = `${process.env['PROGRAMFILES']}\\Git\\usr\\bin\\tar.exe`; // The default path of BSDtar on hosted Windows runners exports.SystemTarPathOnWindows = `${process.env['SYSTEMDRIVE']}\\Windows\\System32\\tar.exe`; exports.TarFilename = 'cache.tar'; exports.ManifestFilename = 'manifest.txt'; exports.CacheFileSizeLimit = 10 * Math.pow(1024, 3); // 10GiB per repository //# sourceMappingURL=constants.js.map /***/ }), /***/ 5067: /***/ (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.downloadCacheStorageSDK = exports.downloadCacheHttpClientConcurrent = exports.downloadCacheHttpClient = exports.DownloadProgress = void 0; const core = __importStar(__nccwpck_require__(7484)); const http_client_1 = __nccwpck_require__(4844); const storage_blob_1 = __nccwpck_require__(1012); const buffer = __importStar(__nccwpck_require__(181)); const fs = __importStar(__nccwpck_require__(9896)); const stream = __importStar(__nccwpck_require__(2203)); const util = __importStar(__nccwpck_require__(9023)); const utils = __importStar(__nccwpck_require__(8299)); const constants_1 = __nccwpck_require__(8287); const requestUtils_1 = __nccwpck_require__(2846); const abort_controller_1 = __nccwpck_require__(8110); /** * Pipes the body of a HTTP response to a stream * * @param response the HTTP response * @param output the writable stream */ 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(); } /** * 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; } 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; } } /** * Returns a function used to handle TransferProgressEvents. */ onProgress() { return (progress) => { this.setReceivedBytes(progress.loadedBytes); }; } /** * 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(); } } exports.DownloadProgress = DownloadProgress; /** * 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 */ 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 (0, 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}`); } } else { core.debug('Unable to validate download, no Content-Length header'); } }); } exports.downloadCacheHttpClient = downloadCacheHttpClient; /** * Download the cache using the Actions toolkit http-client concurrently * * @param archiveLocation the URL for the cache * @param archivePath the local path where the cache is saved */ function downloadCacheHttpClientConcurrent(archiveLocation, archivePath, options) { var _a; return __awaiter(this, void 0, void 0, function* () { const archiveDescriptor = yield fs.promises.open(archivePath, 'w'); const httpClient = new http_client_1.HttpClient('actions/cache', undefined, { socketTimeout: options.timeoutInMs, keepAlive: true }); try { const res = yield (0, requestUtils_1.retryHttpClientResponse)('downloadCacheMetadata', () => __awaiter(this, void 0, void 0, function* () { return yield httpClient.request('HEAD', archiveLocation, null, {}); })); const lengthHeader = res.message.headers['content-length']; if (lengthHeader === undefined || lengthHeader === null) { throw new Error('Content-Length not found on blob response'); } const length = parseInt(lengthHeader); if (Number.isNaN(length)) { throw new Error(`Could not interpret Content-Length: ${length}`); } const downloads = []; const blockSize = 4 * 1024 * 1024; for (let offset = 0; offset < length; offset += blockSize) { const count = Math.min(blockSize, length - offset); downloads.push({ offset, promiseGetter: () => __awaiter(this, void 0, void 0, function* () { return yield downloadSegmentRetry(httpClient, archiveLocation, offset, count); }) }); } // reverse to use .pop instead of .shift downloads.reverse(); let actives = 0; let bytesDownloaded = 0; const progress = new DownloadProgress(length); progress.startDisplayTimer(); const progressFn = progress.onProgress(); const activeDownloads = []; let nextDownload; const waitAndWrite = () => __awaiter(this, void 0, void 0, function* () { const segment = yield Promise.race(Object.values(activeDownloads)); yield archiveDescriptor.write(segment.buffer, 0, segment.count, segment.offset); actives--; delete activeDownloads[segment.offset]; bytesDownloaded += segment.count; progressFn({ loadedBytes: bytesDownloaded }); }); while ((nextDownload = downloads.pop())) { activeDownloads[nextDownload.offset] = nextDownload.promiseGetter(); actives++; if (actives >= ((_a = options.downloadConcurrency) !== null && _a !== void 0 ? _a : 10)) { yield waitAndWrite(); } } while (actives > 0) { yield waitAndWrite(); } } finally { httpClient.dispose(); yield archiveDescriptor.close(); } }); } exports.downloadCacheHttpClientConcurrent = downloadCacheHttpClientConcurrent; function downloadSegmentRetry(httpClient, archiveLocation, offset, count) { return __awaiter(this, void 0, void 0, function* () { const retries = 5; let failures = 0; while (true) { try { const timeout = 30000; const result = yield promiseWithTimeout(timeout, downloadSegment(httpClient, archiveLocation, offset, count)); if (typeof result === 'string') { throw new Error('downloadSegmentRetry failed due to timeout'); } return result; } catch (err) { if (failures >= retries) { throw err; } failures++; } } }); } function downloadSegment(httpClient, archiveLocation, offset, count) { return __awaiter(this, void 0, void 0, function* () { const partRes = yield (0, requestUtils_1.retryHttpClientResponse)('downloadCachePart', () => __awaiter(this, void 0, void 0, function* () { return yield httpClient.get(archiveLocation, { Range: `bytes=${offset}-${offset + count - 1}` }); })); if (!partRes.readBodyBuffer) { throw new Error('Expected HttpClientResponse to implement readBodyBuffer'); } return { offset, count, buffer: yield partRes.readBodyBuffer() }; }); } /** * 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; 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 } }); 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. // Updated segment size to 128MB = 134217728 bytes, to complete a segment faster and fail fast const maxSegmentSize = Math.min(134217728, buffer.constants.MAX_LENGTH); const downloadProgress = new DownloadProgress(contentLength); const fd = fs.openSync(archivePath, 'w'); try { downloadProgress.startDisplayTimer(); const controller = new abort_controller_1.AbortController(); const abortSignal = controller.signal; while (!downloadProgress.isDone()) { const segmentStart = downloadProgress.segmentOffset + downloadProgress.segmentSize; const segmentSize = Math.min(maxSegmentSize, contentLength - segmentStart); downloadProgress.nextSegment(segmentSize); const result = yield promiseWithTimeout(options.segmentTimeoutInMs || 3600000, client.downloadToBuffer(segmentStart, segmentSize, { abortSignal, concurrency: options.downloadConcurrency, onProgress: downloadProgress.onProgress() })); if (result === 'timeout') { controller.abort(); throw new Error('Aborting cache download as the download time exceeded the timeout.'); } else if (Buffer.isBuffer(result)) { fs.writeFileSync(fd, result); } } } finally { downloadProgress.stopDisplayTimer(); fs.closeSync(fd); } } }); } exports.downloadCacheStorageSDK = downloadCacheStorageSDK; const promiseWithTimeout = (timeoutMs, promise) => __awaiter(void 0, void 0, void 0, function* () { let timeoutHandle; const timeoutPromise = new Promise(resolve => { timeoutHandle = setTimeout(() => resolve('timeout'), timeoutMs); }); return Promise.race([promise, timeoutPromise]).then(result => { clearTimeout(timeoutHandle); return result; }); }); //# sourceMappingURL=downloadUtils.js.map /***/ }), /***/ 2846: /***/ (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.retryHttpClientResponse = exports.retryTypedResponse = exports.retry = exports.isRetryableStatusCode = exports.isServerErrorStatusCode = exports.isSuccessStatusCode = void 0; const core = __importStar(__nccwpck_require__(7484)); const http_client_1 = __nccwpck_require__(4844); const constants_1 = __nccwpck_require__(8287); function isSuccessStatusCode(statusCode) { if (!statusCode) { return false; } return statusCode >= 200 && statusCode < 300; } exports.isSuccessStatusCode = isSuccessStatusCode; function isServerErrorStatusCode(statusCode) { if (!statusCode) { return true; } 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)); }); } 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 /***/ }), /***/ 6819: /***/ (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.internalCacheTwirpClient = void 0; const core_1 = __nccwpck_require__(7484); const user_agent_1 = __nccwpck_require__(1899); const errors_1 = __nccwpck_require__(263); const config_1 = __nccwpck_require__(7606); const cacheUtils_1 = __nccwpck_require__(8299); const auth_1 = __nccwpck_require__(4552); const http_client_1 = __nccwpck_require__(4844); const cache_twirp_client_1 = __nccwpck_require__(1486); const util_1 = __nccwpck_require__(7564); /** * This class is a wrapper around the CacheServiceClientJSON class generated by Twirp. * * It adds retry logic to the request method, which is not present in the generated client. * * This class is used to interact with cache service v2. */ class CacheServiceClient { constructor(userAgent, maxAttempts, baseRetryIntervalMilliseconds, retryMultiplier) { this.maxAttempts = 5; this.baseRetryIntervalMilliseconds = 3000; this.retryMultiplier = 1.5; const token = (0, cacheUtils_1.getRuntimeToken)(); this.baseUrl = (0, config_1.getCacheServiceURL)(); 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, util_1.maskSecretUrls)(body); (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 internalCacheTwirpClient(options) { const client = new CacheServiceClient((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 cache_twirp_client_1.CacheServiceClientJSON(client); } exports.internalCacheTwirpClient = internalCacheTwirpClient; //# sourceMappingURL=cacheTwirpClient.js.map /***/ }), /***/ 263: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UsageError = exports.NetworkError = exports.GHESNotSupportedError = exports.CacheNotFoundError = exports.InvalidResponseError = exports.FilesNotFoundError = void 0; class FilesNotFoundError extends Error { constructor(files = []) { let message = 'No files were found to upload'; if (files.length > 0) { message += `: ${files.join(', ')}`; } super(message); this.files = files; this.name = 'FilesNotFoundError'; } } exports.FilesNotFoundError = FilesNotFoundError; class InvalidResponseError extends Error { constructor(message) { super(message); this.name = 'InvalidResponseError'; } } exports.InvalidResponseError = InvalidResponseError; class CacheNotFoundError extends Error { constructor(message = 'Cache not found') { super(message); this.name = 'CacheNotFoundError'; } } exports.CacheNotFoundError = CacheNotFoundError; class GHESNotSupportedError extends Error { constructor(message = '@actions/cache v4.1.4+, actions/cache/save@v4+ and actions/cache/restore@v4+ are not currently supported on GHES.') { super(message); this.name = 'GHESNotSupportedError'; } } 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'; } } 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 = `Cache storage quota has been hit. Unable to upload any new cache entries. Usage is recalculated every 6-12 hours.\nMore info on storage limits: https://docs.github.com/en/billing/managing-billing-for-github-actions/about-billing-for-github-actions#calculating-minute-and-storage-spending`; super(message); this.name = 'UsageError'; } } exports.UsageError = UsageError; UsageError.isUsageErrorMessage = (msg) => { if (!msg) return false; return msg.includes('insufficient usage'); }; //# sourceMappingURL=errors.js.map /***/ }), /***/ 1899: /***/ ((__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__(4012); /** * 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/cache-${packageJson.version}`; } exports.getUserAgentString = getUserAgentString; //# sourceMappingURL=user-agent.js.map /***/ }), /***/ 7564: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.maskSecretUrls = exports.maskSigUrl = void 0; const core_1 = __nccwpck_require__(7484); /** * Masks the `sig` parameter in a URL and sets it as a secret. * * @param url - The URL containing the signature parameter to mask * @remarks * This function attempts to parse the provided URL and identify the 'sig' query parameter. * If found, it registers both the raw and URL-encoded signature values as secrets using * the Actions `setSecret` API, which prevents them from being displayed in logs. * * The function handles errors gracefully if URL parsing fails, logging them as debug messages. * * @example * ```typescript * // Mask a signature in an Azure SAS token URL * maskSigUrl('https://example.blob.core.windows.net/container/file.txt?sig=abc123&se=2023-01-01'); * ``` */ function maskSigUrl(url) { if (!url) return; try { const parsedUrl = new URL(url); const signature = parsedUrl.searchParams.get('sig'); if (signature) { (0, core_1.setSecret)(signature); (0, core_1.setSecret)(encodeURIComponent(signature)); } } catch (error) { (0, core_1.debug)(`Failed to parse URL: ${url} ${error instanceof Error ? error.message : String(error)}`); } } exports.maskSigUrl = maskSigUrl; /** * Masks sensitive information in URLs containing signature parameters. * Currently supports masking 'sig' parameters in the 'signed_upload_url' * and 'signed_download_url' properties of the provided object. * * @param body - The object should contain a signature * @remarks * This function extracts URLs from the object properties and calls maskSigUrl * on each one to redact sensitive signature information. The function doesn't * modify the original object; it only marks the signatures as secrets for * logging purposes. * * @example * ```typescript * const responseBody = { * signed_upload_url: 'https://blob.core.windows.net/?sig=abc123', * signed_download_url: 'https://blob.core/windows.net/?sig=def456' * }; * maskSecretUrls(responseBody); * ``` */ function maskSecretUrls(body) { if (typeof body !== 'object' || body === null) { (0, core_1.debug)('body is not an object or is null'); return; } if ('signed_upload_url' in body && typeof body.signed_upload_url === 'string') { maskSigUrl(body.signed_upload_url); } if ('signed_download_url' in body && typeof body.signed_download_url === 'string') { maskSigUrl(body.signed_download_url); } } exports.maskSecretUrls = maskSecretUrls; //# sourceMappingURL=util.js.map /***/ }), /***/ 5321: /***/ (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.createTar = exports.extractTar = exports.listTar = void 0; const exec_1 = __nccwpck_require__(5236); const io = __importStar(__nccwpck_require__(4994)); const fs_1 = __nccwpck_require__(9896); const path = __importStar(__nccwpck_require__(6928)); const utils = __importStar(__nccwpck_require__(8299)); const constants_1 = __nccwpck_require__(8287); const IS_WINDOWS = process.platform === 'win32'; // Returns tar path and type: BSD or GNU function getTarPath() { return __awaiter(this, void 0, void 0, function* () { switch (process.platform) { case 'win32': { const gnuTar = yield utils.getGnuTarPathOnWindows(); const systemTar = constants_1.SystemTarPathOnWindows; if (gnuTar) { // Use GNUtar as default on windows return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; } else if ((0, fs_1.existsSync)(systemTar)) { return { path: systemTar, type: constants_1.ArchiveToolType.BSD }; } 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 return { path: gnuTar, type: constants_1.ArchiveToolType.GNU }; } else { return { path: yield io.which('tar', true), type: constants_1.ArchiveToolType.BSD }; } } default: break; } // Default assumption is GNU tar is present in path return { path: yield io.which('tar', true), type: constants_1.ArchiveToolType.GNU }; }); } // Return arguments for tar as per tarPath, compressionMethod, method type and os function getTarArgs(tarPath, compressionMethod, type, archivePath = '') { return __awaiter(this, void 0, void 0, function* () { const args = [`"${tarPath.path}"`]; const cacheFileName = utils.getCacheFileName(compressionMethod); const tarFile = 'cache.tar'; const workingDirectory = getWorkingDirectory(); // Speficic args for BSD tar on windows for workaround const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; // Method specific args switch (type) { case 'create': args.push('--posix', '-cf', BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), '--exclude', BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), '-P', '-C', workingDirectory.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), '--files-from', constants_1.ManifestFilename); break; case 'extract': args.push('-xf', BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), '-P', '-C', workingDirectory.replace(new RegExp(`\\${path.sep}`, 'g'), '/')); break; case 'list': args.push('-tf', BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), '-P'); break; } // Platform specific args if (tarPath.type === constants_1.ArchiveToolType.GNU) { switch (process.platform) { case 'win32': args.push('--force-local'); break; case 'darwin': args.push('--delay-directory-restore'); break; } } return args; }); } // Returns commands to run tar and compression program function getCommands(compressionMethod, type, archivePath = '') { return __awaiter(this, void 0, void 0, function* () { let args; const tarPath = yield getTarPath(); const tarArgs = yield getTarArgs(tarPath, compressionMethod, type, archivePath); const compressionArgs = type !== 'create' ? yield getDecompressionProgram(tarPath, compressionMethod, archivePath) : yield getCompressionProgram(tarPath, compressionMethod); const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; if (BSD_TAR_ZSTD && type !== 'create') { args = [[...compressionArgs].join(' '), [...tarArgs].join(' ')]; } else { args = [[...tarArgs].join(' '), [...compressionArgs].join(' ')]; } if (BSD_TAR_ZSTD) { return args; } return [args.join(' ')]; }); } function getWorkingDirectory() { var _a; return (_a = process.env['GITHUB_WORKSPACE']) !== null && _a !== void 0 ? _a : process.cwd(); } // Common function for extractTar and listTar to get the compression method function getDecompressionProgram(tarPath, compressionMethod, archivePath) { return __awaiter(this, void 0, void 0, function* () { // -d: Decompress. // unzstd is equivalent to 'zstd -d' // --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. const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; switch (compressionMethod) { case constants_1.CompressionMethod.Zstd: return BSD_TAR_ZSTD ? [ 'zstd -d --long=30 --force -o', constants_1.TarFilename, archivePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/') ] : [ '--use-compress-program', IS_WINDOWS ? '"zstd -d --long=30"' : 'unzstd --long=30' ]; case constants_1.CompressionMethod.ZstdWithoutLong: return BSD_TAR_ZSTD ? [ 'zstd -d --force -o', constants_1.TarFilename, archivePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/') ] : ['--use-compress-program', IS_WINDOWS ? '"zstd -d"' : 'unzstd']; default: return ['-z']; } }); } // Used for creating the archive // -T#: Compress using # working thread. If # is 0, attempt to detect and use the number of physical CPU cores. // zstdmt is equivalent to 'zstd -T0' // --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(tarPath, compressionMethod) { return __awaiter(this, void 0, void 0, function* () { const cacheFileName = utils.getCacheFileName(compressionMethod); const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; switch (compressionMethod) { case constants_1.CompressionMethod.Zstd: return BSD_TAR_ZSTD ? [ 'zstd -T0 --long=30 --force -o', cacheFileName.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), constants_1.TarFilename ] : [ '--use-compress-program', IS_WINDOWS ? '"zstd -T0 --long=30"' : 'zstdmt --long=30' ]; case constants_1.CompressionMethod.ZstdWithoutLong: return BSD_TAR_ZSTD ? [ 'zstd -T0 --force -o', cacheFileName.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), constants_1.TarFilename ] : ['--use-compress-program', IS_WINDOWS ? '"zstd -T0"' : 'zstdmt']; default: return ['-z']; } }); } // Executes all commands as separate processes function execCommands(commands, cwd) { return __awaiter(this, void 0, void 0, function* () { for (const command of commands) { try { yield (0, exec_1.exec)(command, undefined, { cwd, env: Object.assign(Object.assign({}, process.env), { MSYS: 'winsymlinks:nativestrict' }) }); } catch (error) { throw new Error(`${command.split(' ')[0]} failed with error: ${error === null || error === void 0 ? void 0 : error.message}`); } } }); } // List the contents of a tar function listTar(archivePath, compressionMethod) { return __awaiter(this, void 0, void 0, function* () { const commands = yield getCommands(compressionMethod, 'list', archivePath); yield execCommands(commands); }); } exports.listTar = listTar; // Extract a tar 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); const commands = yield getCommands(compressionMethod, 'extract', archivePath); yield execCommands(commands); }); } exports.extractTar = extractTar; // Create a tar function createTar(archiveFolder, sourceDirectories, compressionMethod) { return __awaiter(this, void 0, void 0, function* () { // Write source directories to manifest.txt to avoid command length limits (0, fs_1.writeFileSync)(path.join(archiveFolder, constants_1.ManifestFilename), sourceDirectories.join('\n')); const commands = yield getCommands(compressionMethod, 'create'); yield execCommands(commands, archiveFolder); }); } exports.createTar = createTar; //# sourceMappingURL=tar.js.map /***/ }), /***/ 5268: /***/ (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.uploadCacheArchiveSDK = exports.UploadProgress = void 0; const core = __importStar(__nccwpck_require__(7484)); const storage_blob_1 = __nccwpck_require__(1012); const errors_1 = __nccwpck_require__(263); /** * Class for tracking the upload state and displaying stats. */ class UploadProgress { constructor(contentLength) { this.contentLength = contentLength; this.sentBytes = 0; this.displayedComplete = false; this.startTime = Date.now(); } /** * Sets the number of bytes sent * * @param sentBytes the number of bytes sent */ setSentBytes(sentBytes) { this.sentBytes = sentBytes; } /** * Returns the total number of bytes transferred. */ getTransferredBytes() { return this.sentBytes; } /** * Returns true if the upload is complete. */ isDone() { return this.getTransferredBytes() === this.contentLength; } /** * Prints the current upload stats. Once the upload completes, this will print one * last line and then stop. */ display() { if (this.displayedComplete) { return; } const transferredBytes = this.sentBytes; const percentage = (100 * (transferredBytes / this.contentLength)).toFixed(1); const elapsedTime = Date.now() - this.startTime; const uploadSpeed = (transferredBytes / (1024 * 1024) / (elapsedTime / 1000)).toFixed(1); core.info(`Sent ${transferredBytes} of ${this.contentLength} (${percentage}%), ${uploadSpeed} MBs/sec`); if (this.isDone()) { this.displayedComplete = true; } } /** * Returns a function used to handle TransferProgressEvents. */ onProgress() { return (progress) => { this.setSentBytes(progress.loadedBytes); }; } /** * 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 upload * 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(); } } exports.UploadProgress = UploadProgress; /** * Uploads a cache archive directly to Azure Blob Storage using the Azure SDK. * This function will display progress information to the console. Concurrency of the * upload is determined by the calling functions. * * @param signedUploadURL * @param archivePath * @param options * @returns */ function uploadCacheArchiveSDK(signedUploadURL, archivePath, options) { var _a; return __awaiter(this, void 0, void 0, function* () { const blobClient = new storage_blob_1.BlobClient(signedUploadURL); const blockBlobClient = blobClient.getBlockBlobClient(); const uploadProgress = new UploadProgress((_a = options === null || options === void 0 ? void 0 : options.archiveSizeBytes) !== null && _a !== void 0 ? _a : 0); // Specify data transfer options const uploadOptions = { blockSize: options === null || options === void 0 ? void 0 : options.uploadChunkSize, concurrency: options === null || options === void 0 ? void 0 : options.uploadConcurrency, maxSingleShotSize: 128 * 1024 * 1024, onProgress: uploadProgress.onProgress() }; try { uploadProgress.startDisplayTimer(); core.debug(`BlobClient: ${blobClient.name}:${blobClient.accountName}:${blobClient.containerName}`); const response = yield blockBlobClient.uploadFile(archivePath, uploadOptions); // TODO: better management of non-retryable errors if (response._response.status >= 400) { throw new errors_1.InvalidResponseError(`uploadCacheArchiveSDK: upload failed with status code ${response._response.status}`); } return response; } catch (error) { core.warning(`uploadCacheArchiveSDK: internal error uploading cache archive: ${error.message}`); throw error; } finally { uploadProgress.stopDisplayTimer(); } }); } exports.uploadCacheArchiveSDK = uploadCacheArchiveSDK; //# sourceMappingURL=uploadUtils.js.map /***/ }), /***/ 8356: /***/ (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.getDownloadOptions = exports.getUploadOptions = void 0; const core = __importStar(__nccwpck_require__(7484)); /** * Returns a copy of the upload options with defaults filled in. * * @param copy the original upload options */ function getUploadOptions(copy) { // Defaults if not overriden const result = { useAzureSdk: false, uploadConcurrency: 4, uploadChunkSize: 32 * 1024 * 1024 }; if (copy) { if (typeof copy.useAzureSdk === 'boolean') { result.useAzureSdk = copy.useAzureSdk; } if (typeof copy.uploadConcurrency === 'number') { result.uploadConcurrency = copy.uploadConcurrency; } if (typeof copy.uploadChunkSize === 'number') { result.uploadChunkSize = copy.uploadChunkSize; } } /** * Add env var overrides */ // Cap the uploadConcurrency at 32 result.uploadConcurrency = !isNaN(Number(process.env['CACHE_UPLOAD_CONCURRENCY'])) ? Math.min(32, Number(process.env['CACHE_UPLOAD_CONCURRENCY'])) : result.uploadConcurrency; // Cap the uploadChunkSize at 128MiB result.uploadChunkSize = !isNaN(Number(process.env['CACHE_UPLOAD_CHUNK_SIZE'])) ? Math.min(128 * 1024 * 1024, Number(process.env['CACHE_UPLOAD_CHUNK_SIZE']) * 1024 * 1024) : result.uploadChunkSize; core.debug(`Use Azure SDK: ${result.useAzureSdk}`); core.debug(`Upload concurrency: ${result.uploadConcurrency}`); core.debug(`Upload chunk size: ${result.uploadChunkSize}`); return result; } 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: false, concurrentBlobDownloads: true, downloadConcurrency: 8, timeoutInMs: 30000, segmentTimeoutInMs: 600000, lookupOnly: false }; if (copy) { if (typeof copy.useAzureSdk === 'boolean') { result.useAzureSdk = copy.useAzureSdk; } if (typeof copy.concurrentBlobDownloads === 'boolean') { result.concurrentBlobDownloads = copy.concurrentBlobDownloads; } if (typeof copy.downloadConcurrency === 'number') { result.downloadConcurrency = copy.downloadConcurrency; } if (typeof copy.timeoutInMs === 'number') { result.timeoutInMs = copy.timeoutInMs; } if (typeof copy.segmentTimeoutInMs === 'number') { result.segmentTimeoutInMs = copy.segmentTimeoutInMs; } if (typeof copy.lookupOnly === 'boolean') { result.lookupOnly = copy.lookupOnly; } } const segmentDownloadTimeoutMins = process.env['SEGMENT_DOWNLOAD_TIMEOUT_MINS']; if (segmentDownloadTimeoutMins && !isNaN(Number(segmentDownloadTimeoutMins)) && isFinite(Number(segmentDownloadTimeoutMins))) { result.segmentTimeoutInMs = Number(segmentDownloadTimeoutMins) * 60 * 1000; } core.debug(`Use Azure SDK: ${result.useAzureSdk}`); core.debug(`Download concurrency: ${result.downloadConcurrency}`); core.debug(`Request timeout (ms): ${result.timeoutInMs}`); core.debug(`Cache segment download timeout mins env var: ${process.env['SEGMENT_DOWNLOAD_TIMEOUT_MINS']}`); core.debug(`Segment download timeout (ms): ${result.segmentTimeoutInMs}`); core.debug(`Lookup only: ${result.lookupOnly}`); return result; } exports.getDownloadOptions = getDownloadOptions; //# sourceMappingURL=options.js.map /***/ }), /***/ 4914: /***/ (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.issue = exports.issueCommand = void 0; const os = __importStar(__nccwpck_require__(857)); const utils_1 = __nccwpck_require__(302); /** * 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 (0, utils_1.toCommandValue)(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A'); } function escapeProperty(s) { return (0, 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 /***/ }), /***/ 7484: /***/ (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.platform = exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = exports.markdownSummary = exports.summary = 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__(4914); const file_command_1 = __nccwpck_require__(4753); const utils_1 = __nccwpck_require__(302); const os = __importStar(__nccwpck_require__(857)); const path = __importStar(__nccwpck_require__(6928)); const oidc_utils_1 = __nccwpck_require__(5306); /** * The code to exit an action */ var ExitCode; (function (ExitCode) { /** * A code indicating that the action was successful */ ExitCode[ExitCode["Success"] = 0] = "Success"; /** * A code indicating that the action was a failure */ ExitCode[ExitCode["Failure"] = 1] = "Failure"; })(ExitCode || (exports.ExitCode = 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 = (0, utils_1.toCommandValue)(val); process.env[name] = convertedVal; const filePath = process.env['GITHUB_ENV'] || ''; if (filePath) { return (0, file_command_1.issueFileCommand)('ENV', (0, file_command_1.prepareKeyValueMessage)(name, val)); } (0, 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) { (0, 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) { (0, file_command_1.issueFileCommand)('PATH', inputPath); } else { (0, command_1.issueCommand)('add-path', {}, inputPath); } process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; } exports.addPath = addPath; /** * Gets the value of an input. * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. * Returns an empty string if the value is not defined. * * @param name name of the input to get * @param options optional. See InputOptions. * @returns string */ function getInput(name, options) { const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; if (options && options.required && !val) { throw new Error(`Input required and not supplied: ${name}`); } if (options && options.trimWhitespace === false) { return val; } return val.trim(); } exports.getInput = getInput; /** * Gets the values of an multiline input. Each value is also trimmed. * * @param name name of the input to get * @param options optional. See InputOptions. * @returns string[] * */ function getMultilineInput(name, options) { const inputs = getInput(name, options) .split('\n') .filter(x => x !== ''); if (options && options.trimWhitespace === false) { return inputs; } return inputs.map(input => input.trim()); } exports.getMultilineInput = getMultilineInput; /** * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. * Support boolean input list: `true | True | TRUE | false | False | FALSE` . * The return value is also in boolean type. * ref: https://yaml.org/spec/1.2/spec.html#id2804923 * * @param name name of the input to get * @param options optional. See InputOptions. * @returns boolean */ function getBooleanInput(name, options) { const trueValue = ['true', 'True', 'TRUE']; const falseValue = ['false', 'False', 'FALSE']; const val = getInput(name, options); if (trueValue.includes(val)) return true; if (falseValue.includes(val)) return false; throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); } exports.getBooleanInput = getBooleanInput; /** * Sets the value of an output. * * @param name name of the output to set * @param value value to store. Non-string values will be converted to a string via JSON.stringify */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function setOutput(name, value) { const filePath = process.env['GITHUB_OUTPUT'] || ''; if (filePath) { return (0, file_command_1.issueFileCommand)('OUTPUT', (0, file_command_1.prepareKeyValueMessage)(name, value)); } process.stdout.write(os.EOL); (0, command_1.issueCommand)('set-output', { name }, (0, utils_1.toCommandValue)(value)); } exports.setOutput = setOutput; /** * Enables or disables the echoing of commands into stdout for the rest of the step. * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. * */ function setCommandEcho(enabled) { (0, 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) { (0, 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 = {}) { (0, command_1.issueCommand)('error', (0, 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 = {}) { (0, command_1.issueCommand)('warning', (0, 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 = {}) { (0, command_1.issueCommand)('notice', (0, 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) { (0, command_1.issue)('group', name); } exports.startGroup = startGroup; /** * End an output group. */ function endGroup() { (0, 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 (0, file_command_1.issueFileCommand)('STATE', (0, file_command_1.prepareKeyValueMessage)(name, value)); } (0, command_1.issueCommand)('save-state', { name }, (0, 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__(1847); Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); /** * @deprecated use core.summary */ var summary_2 = __nccwpck_require__(1847); Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); /** * Path exports */ var path_utils_1 = __nccwpck_require__(1976); 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; } })); /** * Platform utilities exports */ exports.platform = __importStar(__nccwpck_require__(8968)); //# sourceMappingURL=core.js.map /***/ }), /***/ 4753: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // For internal use, subject to change. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (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.prepareKeyValueMessage = exports.issueFileCommand = void 0; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ const crypto = __importStar(__nccwpck_require__(6982)); const fs = __importStar(__nccwpck_require__(9896)); const os = __importStar(__nccwpck_require__(857)); const utils_1 = __nccwpck_require__(302); 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, `${(0, utils_1.toCommandValue)(message)}${os.EOL}`, { encoding: 'utf8' }); } exports.issueFileCommand = issueFileCommand; function prepareKeyValueMessage(key, value) { const delimiter = `ghadelimiter_${crypto.randomUUID()}`; const convertedValue = (0, 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 /***/ }), /***/ 5306: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.OidcClient = void 0; const http_client_1 = __nccwpck_require__(4844); const auth_1 = __nccwpck_require__(4552); const core_1 = __nccwpck_require__(7484); 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.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}`; } (0, core_1.debug)(`ID token url is ${id_token_url}`); const id_token = yield OidcClient.getCall(id_token_url); (0, core_1.setSecret)(id_token); return id_token; } catch (error) { throw new Error(`Error message: ${error.message}`); } }); } } exports.OidcClient = OidcClient; //# sourceMappingURL=oidc-utils.js.map /***/ }), /***/ 1976: /***/ (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.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; const path = __importStar(__nccwpck_require__(6928)); /** * toPosixPath converts the given path to the posix form. On Windows, \\ will be * replaced with /. * * @param pth. Path to transform. * @return string Posix path. */ function toPosixPath(pth) { return pth.replace(/[\\]/g, '/'); } exports.toPosixPath = toPosixPath; /** * toWin32Path converts the given path to the win32 form. On Linux, / will be * replaced with \\. * * @param pth. Path to transform. * @return string Win32 path. */ function toWin32Path(pth) { return pth.replace(/[/]/g, '\\'); } exports.toWin32Path = toWin32Path; /** * toPlatformPath converts the given path to a platform-specific path. It does * this by replacing instances of / and \ with the platform-specific path * separator. * * @param pth The path to platformize. * @return string The platform-specific path. */ function toPlatformPath(pth) { return pth.replace(/[/\\]/g, path.sep); } exports.toPlatformPath = toPlatformPath; //# sourceMappingURL=path-utils.js.map /***/ }), /***/ 8968: /***/ (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()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getDetails = exports.isLinux = exports.isMacOS = exports.isWindows = exports.arch = exports.platform = void 0; const os_1 = __importDefault(__nccwpck_require__(857)); const exec = __importStar(__nccwpck_require__(5236)); const getWindowsInfo = () => __awaiter(void 0, void 0, void 0, function* () { const { stdout: version } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', undefined, { silent: true }); const { stdout: name } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Caption"', undefined, { silent: true }); return { name: name.trim(), version: version.trim() }; }); const getMacOsInfo = () => __awaiter(void 0, void 0, void 0, function* () { var _a, _b, _c, _d; const { stdout } = yield exec.getExecOutput('sw_vers', undefined, { silent: true }); const version = (_b = (_a = stdout.match(/ProductVersion:\s*(.+)/)) === null || _a === void 0 ? void 0 : _a[1]) !== null && _b !== void 0 ? _b : ''; const name = (_d = (_c = stdout.match(/ProductName:\s*(.+)/)) === null || _c === void 0 ? void 0 : _c[1]) !== null && _d !== void 0 ? _d : ''; return { name, version }; }); const getLinuxInfo = () => __awaiter(void 0, void 0, void 0, function* () { const { stdout } = yield exec.getExecOutput('lsb_release', ['-i', '-r', '-s'], { silent: true }); const [name, version] = stdout.trim().split('\n'); return { name, version }; }); exports.platform = os_1.default.platform(); exports.arch = os_1.default.arch(); exports.isWindows = exports.platform === 'win32'; exports.isMacOS = exports.platform === 'darwin'; exports.isLinux = exports.platform === 'linux'; function getDetails() { return __awaiter(this, void 0, void 0, function* () { return Object.assign(Object.assign({}, (yield (exports.isWindows ? getWindowsInfo() : exports.isMacOS ? getMacOsInfo() : getLinuxInfo()))), { platform: exports.platform, arch: exports.arch, isWindows: exports.isWindows, isMacOS: exports.isMacOS, isLinux: exports.isLinux }); }); } exports.getDetails = getDetails; //# sourceMappingURL=platform.js.map /***/ }), /***/ 1847: /***/ (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__(857); const fs_1 = __nccwpck_require__(9896); 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(); } /** * 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 /***/ }), /***/ 302: /***/ ((__unused_webpack_module, exports) => { "use strict"; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toCommandProperties = exports.toCommandValue = void 0; /** * Sanitizes an input into a string so it can be passed into issueCommand safely * @param input input to sanitize into a string */ function toCommandValue(input) { if (input === null || input === undefined) { return ''; } else if (typeof input === 'string' || input instanceof String) { return input; } return JSON.stringify(input); } exports.toCommandValue = toCommandValue; /** * * @param annotationProperties * @returns The command properties to send with the actual annotation command * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646 */ function toCommandProperties(annotationProperties) { if (!Object.keys(annotationProperties).length) { return {}; } 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 /***/ }), /***/ 5236: /***/ (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.getExecOutput = exports.exec = void 0; const string_decoder_1 = __nccwpck_require__(3193); const tr = __importStar(__nccwpck_require__(6665)); /** * Exec a command. * Output will be streamed to the live console. * Returns promise with return code * * @param commandLine command to execute (can include additional args). Must be correctly escaped. * @param args optional arguments for tool. Escaping is handled by the lib. * @param options optional exec options. See ExecOptions * @returns Promise exit code */ function exec(commandLine, args, options) { return __awaiter(this, void 0, void 0, function* () { const commandArgs = tr.argStringToArray(commandLine); if (commandArgs.length === 0) { throw new Error(`Parameter 'commandLine' cannot be null or empty.`); } // Path to tool to execute should be first arg const toolPath = commandArgs[0]; args = commandArgs.slice(1).concat(args || []); const runner = new tr.ToolRunner(toolPath, args, options); return runner.exec(); }); } exports.exec = exec; /** * Exec a command and get the output. * Output will be streamed to the live console. * Returns promise with the exit code and collected stdout and stderr * * @param commandLine command to execute (can include additional args). Must be correctly escaped. * @param args optional arguments for tool. Escaping is handled by the lib. * @param options optional exec options. See ExecOptions * @returns Promise exit code, stdout, and stderr */ function getExecOutput(commandLine, args, options) { var _a, _b; return __awaiter(this, void 0, void 0, function* () { let stdout = ''; let stderr = ''; //Using string decoder covers the case where a mult-byte character is split const stdoutDecoder = new string_decoder_1.StringDecoder('utf8'); const stderrDecoder = new string_decoder_1.StringDecoder('utf8'); const originalStdoutListener = (_a = options === null || options === void 0 ? void 0 : options.listeners) === null || _a === void 0 ? void 0 : _a.stdout; const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr; const stdErrListener = (data) => { stderr += stderrDecoder.write(data); if (originalStdErrListener) { originalStdErrListener(data); } }; const stdOutListener = (data) => { stdout += stdoutDecoder.write(data); if (originalStdoutListener) { originalStdoutListener(data); } }; const listeners = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.listeners), { stdout: stdOutListener, stderr: stdErrListener }); const exitCode = yield exec(commandLine, args, Object.assign(Object.assign({}, options), { listeners })); //flush any remaining characters stdout += stdoutDecoder.end(); stderr += stderrDecoder.end(); return { exitCode, stdout, stderr }; }); } exports.getExecOutput = getExecOutput; //# sourceMappingURL=exec.js.map /***/ }), /***/ 6665: /***/ (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.argStringToArray = exports.ToolRunner = void 0; const os = __importStar(__nccwpck_require__(857)); const events = __importStar(__nccwpck_require__(4434)); const child = __importStar(__nccwpck_require__(5317)); const path = __importStar(__nccwpck_require__(6928)); const io = __importStar(__nccwpck_require__(4994)); const ioUtil = __importStar(__nccwpck_require__(5207)); const timers_1 = __nccwpck_require__(3557); /* eslint-disable @typescript-eslint/unbound-method */ const IS_WINDOWS = process.platform === 'win32'; /* * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way. */ class ToolRunner extends events.EventEmitter { constructor(toolPath, args, options) { super(); if (!toolPath) { throw new Error("Parameter 'toolPath' cannot be null or empty."); } this.toolPath = toolPath; this.args = args || []; this.options = options || {}; } _debug(message) { if (this.options.listeners && this.options.listeners.debug) { this.options.listeners.debug(message); } } _getCommandString(options, noPrefix) { const toolPath = this._getSpawnFileName(); const args = this._getSpawnArgs(options); let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool if (IS_WINDOWS) { // Windows + cmd file if (this._isCmdFile()) { cmd += toolPath; for (const a of args) { cmd += ` ${a}`; } } // Windows + verbatim else if (options.windowsVerbatimArguments) { cmd += `"${toolPath}"`; for (const a of args) { cmd += ` ${a}`; } } // Windows (regular) else { cmd += this._windowsQuoteCmdArg(toolPath); for (const a of args) { cmd += ` ${this._windowsQuoteCmdArg(a)}`; } } } else { // OSX/Linux - this can likely be improved with some form of quoting. // creating processes on Unix is fundamentally different than Windows. // on Unix, execvp() takes an arg array. cmd += toolPath; for (const a of args) { cmd += ` ${a}`; } } return cmd; } _processLineBuffer(data, strBuffer, onLine) { try { let s = strBuffer + data.toString(); let n = s.indexOf(os.EOL); while (n > -1) { const line = s.substring(0, n); onLine(line); // the rest of the string ... s = s.substring(n + os.EOL.length); n = s.indexOf(os.EOL); } return s; } catch (err) { // streaming lines to console is best effort. Don't fail a build. this._debug(`error processing line. Failed with error ${err}`); return ''; } } _getSpawnFileName() { if (IS_WINDOWS) { if (this._isCmdFile()) { return process.env['COMSPEC'] || 'cmd.exe'; } } return this.toolPath; } _getSpawnArgs(options) { if (IS_WINDOWS) { if (this._isCmdFile()) { let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`; for (const a of this.args) { argline += ' '; argline += options.windowsVerbatimArguments ? a : this._windowsQuoteCmdArg(a); } argline += '"'; return [argline]; } } return this.args; } _endsWith(str, end) { return str.endsWith(end); } _isCmdFile() { const upperToolPath = this.toolPath.toUpperCase(); return (this._endsWith(upperToolPath, '.CMD') || this._endsWith(upperToolPath, '.BAT')); } _windowsQuoteCmdArg(arg) { // for .exe, apply the normal quoting rules that libuv applies if (!this._isCmdFile()) { return this._uvQuoteCmdArg(arg); } // otherwise apply quoting rules specific to the cmd.exe command line parser. // the libuv rules are generic and are not designed specifically for cmd.exe // command line parser. // // for a detailed description of the cmd.exe command line parser, refer to // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912 // need quotes for empty arg if (!arg) { return '""'; } // determine whether the arg needs to be quoted const cmdSpecialChars = [ ' ', '\t', '&', '(', ')', '[', ']', '{', '}', '^', '=', ';', '!', "'", '+', ',', '`', '~', '|', '<', '>', '"' ]; let needsQuotes = false; for (const char of arg) { if (cmdSpecialChars.some(x => x === char)) { needsQuotes = true; break; } } // short-circuit if quotes not needed if (!needsQuotes) { return arg; } // the following quoting rules are very similar to the rules that by libuv applies. // // 1) wrap the string in quotes // // 2) double-up quotes - i.e. " => "" // // this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately // doesn't work well with a cmd.exe command line. // // note, replacing " with "" also works well if the arg is passed to a downstream .NET console app. // for example, the command line: // foo.exe "myarg:""my val""" // is parsed by a .NET console app into an arg array: // [ "myarg:\"my val\"" ] // which is the same end result when applying libuv quoting rules. although the actual // command line from libuv quoting rules would look like: // foo.exe "myarg:\"my val\"" // // 3) double-up slashes that precede a quote, // e.g. hello \world => "hello \world" // hello\"world => "hello\\""world" // hello\\"world => "hello\\\\""world" // hello world\ => "hello world\\" // // technically this is not required for a cmd.exe command line, or the batch argument parser. // the reasons for including this as a .cmd quoting rule are: // // a) this is optimized for the scenario where the argument is passed from the .cmd file to an // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule. // // b) it's what we've been doing previously (by deferring to node default behavior) and we // haven't heard any complaints about that aspect. // // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be // escaped when used on the command line directly - even though within a .cmd file % can be escaped // by using %%. // // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing. // // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args // to an external program. // // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file. // % can be escaped within a .cmd file. let reverse = '"'; let quoteHit = true; for (let i = arg.length; i > 0; i--) { // walk the string in reverse reverse += arg[i - 1]; if (quoteHit && arg[i - 1] === '\\') { reverse += '\\'; // double the slash } else if (arg[i - 1] === '"') { quoteHit = true; reverse += '"'; // double the quote } else { quoteHit = false; } } reverse += '"'; return reverse .split('') .reverse() .join(''); } _uvQuoteCmdArg(arg) { // Tool runner wraps child_process.spawn() and needs to apply the same quoting as // Node in certain cases where the undocumented spawn option windowsVerbatimArguments // is used. // // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV, // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details), // pasting copyright notice from Node within this function: // // Copyright Joyent, Inc. and other Node contributors. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. if (!arg) { // Need double quotation for empty argument return '""'; } if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) { // No quotation needed return arg; } if (!arg.includes('"') && !arg.includes('\\')) { // No embedded double quotes or backslashes, so I can just wrap // quote marks around the whole thing. return `"${arg}"`; } // Expected input/output: // input : hello"world // output: "hello\"world" // input : hello""world // output: "hello\"\"world" // input : hello\world // output: hello\world // input : hello\\world // output: hello\\world // input : hello\"world // output: "hello\\\"world" // input : hello\\"world // output: "hello\\\\\"world" // input : hello world\ // output: "hello world\\" - note the comment in libuv actually reads "hello world\" // but it appears the comment is wrong, it should be "hello world\\" let reverse = '"'; let quoteHit = true; for (let i = arg.length; i > 0; i--) { // walk the string in reverse reverse += arg[i - 1]; if (quoteHit && arg[i - 1] === '\\') { reverse += '\\'; } else if (arg[i - 1] === '"') { quoteHit = true; reverse += '\\'; } else { quoteHit = false; } } reverse += '"'; return reverse .split('') .reverse() .join(''); } _cloneExecOptions(options) { options = options || {}; const result = { cwd: options.cwd || process.cwd(), env: options.env || process.env, silent: options.silent || false, windowsVerbatimArguments: options.windowsVerbatimArguments || false, failOnStdErr: options.failOnStdErr || false, ignoreReturnCode: options.ignoreReturnCode || false, delay: options.delay || 10000 }; result.outStream = options.outStream || process.stdout; result.errStream = options.errStream || process.stderr; return result; } _getSpawnOptions(options, toolPath) { options = options || {}; const result = {}; result.cwd = options.cwd; result.env = options.env; result['windowsVerbatimArguments'] = options.windowsVerbatimArguments || this._isCmdFile(); if (options.windowsVerbatimArguments) { result.argv0 = `"${toolPath}"`; } return result; } /** * Exec a tool. * Output will be streamed to the live console. * Returns promise with return code * * @param tool path to tool to exec * @param options optional exec options. See ExecOptions * @returns number */ exec() { return __awaiter(this, void 0, void 0, function* () { // root the tool path if it is unrooted and contains relative pathing if (!ioUtil.isRooted(this.toolPath) && (this.toolPath.includes('/') || (IS_WINDOWS && this.toolPath.includes('\\')))) { // prefer options.cwd if it is specified, however options.cwd may also need to be rooted this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); } // if the tool is only a file name, then resolve it from the PATH // otherwise verify it exists (add extension on Windows if necessary) this.toolPath = yield io.which(this.toolPath, true); return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { this._debug(`exec tool: ${this.toolPath}`); this._debug('arguments:'); for (const arg of this.args) { this._debug(` ${arg}`); } const optionsNonNull = this._cloneExecOptions(this.options); if (!optionsNonNull.silent && optionsNonNull.outStream) { optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL); } const state = new ExecState(optionsNonNull, this.toolPath); state.on('debug', (message) => { this._debug(message); }); if (this.options.cwd && !(yield ioUtil.exists(this.options.cwd))) { return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`)); } const fileName = this._getSpawnFileName(); const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); let stdbuffer = ''; if (cp.stdout) { cp.stdout.on('data', (data) => { if (this.options.listeners && this.options.listeners.stdout) { this.options.listeners.stdout(data); } if (!optionsNonNull.silent && optionsNonNull.outStream) { optionsNonNull.outStream.write(data); } stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => { if (this.options.listeners && this.options.listeners.stdline) { this.options.listeners.stdline(line); } }); }); } let errbuffer = ''; if (cp.stderr) { cp.stderr.on('data', (data) => { state.processStderr = true; if (this.options.listeners && this.options.listeners.stderr) { this.options.listeners.stderr(data); } if (!optionsNonNull.silent && optionsNonNull.errStream && optionsNonNull.outStream) { const s = optionsNonNull.failOnStdErr ? optionsNonNull.errStream : optionsNonNull.outStream; s.write(data); } errbuffer = this._processLineBuffer(data, errbuffer, (line) => { if (this.options.listeners && this.options.listeners.errline) { this.options.listeners.errline(line); } }); }); } cp.on('error', (err) => { state.processError = err.message; state.processExited = true; state.processClosed = true; state.CheckComplete(); }); cp.on('exit', (code) => { state.processExitCode = code; state.processExited = true; this._debug(`Exit code ${code} received from tool '${this.toolPath}'`); state.CheckComplete(); }); cp.on('close', (code) => { state.processExitCode = code; state.processExited = true; state.processClosed = true; this._debug(`STDIO streams have closed for tool '${this.toolPath}'`); state.CheckComplete(); }); state.on('done', (error, exitCode) => { if (stdbuffer.length > 0) { this.emit('stdline', stdbuffer); } if (errbuffer.length > 0) { this.emit('errline', errbuffer); } cp.removeAllListeners(); if (error) { reject(error); } else { resolve(exitCode); } }); if (this.options.input) { if (!cp.stdin) { throw new Error('child process missing stdin'); } cp.stdin.end(this.options.input); } })); }); } } exports.ToolRunner = ToolRunner; /** * Convert an arg string to an array of args. Handles escaping * * @param argString string of arguments * @returns string[] array of arguments */ function argStringToArray(argString) { const args = []; let inQuotes = false; let escaped = false; let arg = ''; function append(c) { // we only escape double quotes. if (escaped && c !== '"') { arg += '\\'; } arg += c; escaped = false; } for (let i = 0; i < argString.length; i++) { const c = argString.charAt(i); if (c === '"') { if (!escaped) { inQuotes = !inQuotes; } else { append(c); } continue; } if (c === '\\' && escaped) { append(c); continue; } if (c === '\\' && inQuotes) { escaped = true; continue; } if (c === ' ' && !inQuotes) { if (arg.length > 0) { args.push(arg); arg = ''; } continue; } append(c); } if (arg.length > 0) { args.push(arg.trim()); } return args; } exports.argStringToArray = argStringToArray; class ExecState extends events.EventEmitter { constructor(options, toolPath) { super(); this.processClosed = false; // tracks whether the process has exited and stdio is closed this.processError = ''; this.processExitCode = 0; this.processExited = false; // tracks whether the process has exited this.processStderr = false; // tracks whether stderr was written to this.delay = 10000; // 10 seconds this.done = false; this.timeout = null; if (!toolPath) { throw new Error('toolPath must not be empty'); } this.options = options; this.toolPath = toolPath; if (options.delay) { this.delay = options.delay; } } CheckComplete() { if (this.done) { return; } if (this.processClosed) { this._setResult(); } else if (this.processExited) { this.timeout = timers_1.setTimeout(ExecState.HandleTimeout, this.delay, this); } } _debug(message) { this.emit('debug', message); } _setResult() { // determine whether there is an error let error; if (this.processExited) { if (this.processError) { error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`); } else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) { error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`); } else if (this.processStderr && this.options.failOnStdErr) { error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`); } } // clear the timeout if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; } this.done = true; this.emit('done', error, this.processExitCode); } static HandleTimeout(state) { if (state.done) { return; } if (!state.processClosed && state.processExited) { const message = `The STDIO streams did not close within ${state.delay / 1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`; state._debug(message); } state._setResult(); } } //# sourceMappingURL=toolrunner.js.map /***/ }), /***/ 7206: /***/ (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.create = void 0; const internal_globber_1 = __nccwpck_require__(103); /** * Constructs a globber * * @param patterns Patterns separated by newlines * @param options Glob options */ function create(patterns, options) { return __awaiter(this, void 0, void 0, function* () { return yield internal_globber_1.DefaultGlobber.create(patterns, options); }); } exports.create = create; //# sourceMappingURL=glob.js.map /***/ }), /***/ 8164: /***/ (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.getOptions = void 0; const core = __importStar(__nccwpck_require__(7484)); /** * Returns a copy with defaults filled in. */ function getOptions(copy) { const result = { followSymbolicLinks: true, implicitDescendants: true, omitBrokenSymbolicLinks: true }; if (copy) { if (typeof copy.followSymbolicLinks === 'boolean') { result.followSymbolicLinks = copy.followSymbolicLinks; core.debug(`followSymbolicLinks '${result.followSymbolicLinks}'`); } if (typeof copy.implicitDescendants === 'boolean') { result.implicitDescendants = copy.implicitDescendants; core.debug(`implicitDescendants '${result.implicitDescendants}'`); } if (typeof copy.omitBrokenSymbolicLinks === 'boolean') { result.omitBrokenSymbolicLinks = copy.omitBrokenSymbolicLinks; core.debug(`omitBrokenSymbolicLinks '${result.omitBrokenSymbolicLinks}'`); } } return result; } exports.getOptions = getOptions; //# sourceMappingURL=internal-glob-options-helper.js.map /***/ }), /***/ 103: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __asyncValues = (this && this.__asyncValues) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } }; var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DefaultGlobber = void 0; const core = __importStar(__nccwpck_require__(7484)); const fs = __importStar(__nccwpck_require__(9896)); const globOptionsHelper = __importStar(__nccwpck_require__(8164)); const path = __importStar(__nccwpck_require__(6928)); const patternHelper = __importStar(__nccwpck_require__(8891)); const internal_match_kind_1 = __nccwpck_require__(2644); const internal_pattern_1 = __nccwpck_require__(5370); const internal_search_state_1 = __nccwpck_require__(9890); const IS_WINDOWS = process.platform === 'win32'; class DefaultGlobber { constructor(options) { this.patterns = []; this.searchPaths = []; this.options = globOptionsHelper.getOptions(options); } getSearchPaths() { // Return a copy return this.searchPaths.slice(); } glob() { var e_1, _a; return __awaiter(this, void 0, void 0, function* () { const result = []; try { for (var _b = __asyncValues(this.globGenerator()), _c; _c = yield _b.next(), !_c.done;) { const itemPath = _c.value; result.push(itemPath); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b); } finally { if (e_1) throw e_1.error; } } return result; }); } globGenerator() { return __asyncGenerator(this, arguments, function* globGenerator_1() { // Fill in defaults options const options = globOptionsHelper.getOptions(this.options); // Implicit descendants? const patterns = []; for (const pattern of this.patterns) { patterns.push(pattern); if (options.implicitDescendants && (pattern.trailingSeparator || pattern.segments[pattern.segments.length - 1] !== '**')) { patterns.push(new internal_pattern_1.Pattern(pattern.negate, true, pattern.segments.concat('**'))); } } // Push the search paths const stack = []; for (const searchPath of patternHelper.getSearchPaths(patterns)) { core.debug(`Search path '${searchPath}'`); // Exists? try { // Intentionally using lstat. Detection for broken symlink // will be performed later (if following symlinks). yield __await(fs.promises.lstat(searchPath)); } catch (err) { if (err.code === 'ENOENT') { continue; } throw err; } stack.unshift(new internal_search_state_1.SearchState(searchPath, 1)); } // Search const traversalChain = []; // used to detect cycles while (stack.length) { // Pop const item = stack.pop(); // Match? const match = patternHelper.match(patterns, item.path); const partialMatch = !!match || patternHelper.partialMatch(patterns, item.path); if (!match && !partialMatch) { continue; } // Stat const stats = yield __await(DefaultGlobber.stat(item, options, traversalChain) // Broken symlink, or symlink cycle detected, or no longer exists ); // Broken symlink, or symlink cycle detected, or no longer exists if (!stats) { continue; } // Directory if (stats.isDirectory()) { // Matched if (match & internal_match_kind_1.MatchKind.Directory) { yield yield __await(item.path); } // Descend? else if (!partialMatch) { continue; } // Push the child items in reverse const childLevel = item.level + 1; const childItems = (yield __await(fs.promises.readdir(item.path))).map(x => new internal_search_state_1.SearchState(path.join(item.path, x), childLevel)); stack.push(...childItems.reverse()); } // File else if (match & internal_match_kind_1.MatchKind.File) { yield yield __await(item.path); } } }); } /** * Constructs a DefaultGlobber */ static create(patterns, options) { return __awaiter(this, void 0, void 0, function* () { const result = new DefaultGlobber(options); if (IS_WINDOWS) { patterns = patterns.replace(/\r\n/g, '\n'); patterns = patterns.replace(/\r/g, '\n'); } const lines = patterns.split('\n').map(x => x.trim()); for (const line of lines) { // Empty or comment if (!line || line.startsWith('#')) { continue; } // Pattern else { result.patterns.push(new internal_pattern_1.Pattern(line)); } } result.searchPaths.push(...patternHelper.getSearchPaths(result.patterns)); return result; }); } static stat(item, options, traversalChain) { return __awaiter(this, void 0, void 0, function* () { // Note: // `stat` returns info about the target of a symlink (or symlink chain) // `lstat` returns info about a symlink itself let stats; if (options.followSymbolicLinks) { try { // Use `stat` (following symlinks) stats = yield fs.promises.stat(item.path); } catch (err) { if (err.code === 'ENOENT') { if (options.omitBrokenSymbolicLinks) { core.debug(`Broken symlink '${item.path}'`); return undefined; } throw new Error(`No information found for the path '${item.path}'. This may indicate a broken symbolic link.`); } throw err; } } else { // Use `lstat` (not following symlinks) stats = yield fs.promises.lstat(item.path); } // Note, isDirectory() returns false for the lstat of a symlink if (stats.isDirectory() && options.followSymbolicLinks) { // Get the realpath const realPath = yield fs.promises.realpath(item.path); // Fixup the traversal chain to match the item level while (traversalChain.length >= item.level) { traversalChain.pop(); } // Test for a cycle if (traversalChain.some((x) => x === realPath)) { core.debug(`Symlink cycle detected for path '${item.path}' and realpath '${realPath}'`); return undefined; } // Update the traversal chain traversalChain.push(realPath); } return stats; }); } } exports.DefaultGlobber = DefaultGlobber; //# sourceMappingURL=internal-globber.js.map /***/ }), /***/ 2644: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MatchKind = void 0; /** * Indicates whether a pattern matches a path */ var MatchKind; (function (MatchKind) { /** Not matched */ MatchKind[MatchKind["None"] = 0] = "None"; /** Matched if the path is a directory */ MatchKind[MatchKind["Directory"] = 1] = "Directory"; /** Matched if the path is a regular file */ MatchKind[MatchKind["File"] = 2] = "File"; /** Matched */ MatchKind[MatchKind["All"] = 3] = "All"; })(MatchKind = exports.MatchKind || (exports.MatchKind = {})); //# sourceMappingURL=internal-match-kind.js.map /***/ }), /***/ 4138: /***/ (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 __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": 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__(6928)); const assert_1 = __importDefault(__nccwpck_require__(2613)); const IS_WINDOWS = process.platform === 'win32'; /** * Similar to path.dirname except normalizes the path separators and slightly better handling for Windows UNC paths. * * For example, on Linux/macOS: * - `/ => /` * - `/hello => /` * * For example, on Windows: * - `C:\ => C:\` * - `C:\hello => C:\` * - `C: => C:` * - `C:hello => C:` * - `\ => \` * - `\hello => \` * - `\\hello => \\hello` * - `\\hello\world => \\hello\world` */ function dirname(p) { // Normalize slashes and trim unnecessary trailing slash p = safeTrimTrailingSeparator(p); // Windows UNC root, e.g. \\hello or \\hello\world if (IS_WINDOWS && /^\\\\[^\\]+(\\[^\\]+)?$/.test(p)) { return p; } // Get dirname let result = path.dirname(p); // Trim trailing slash for Windows UNC root, e.g. \\hello\world\ if (IS_WINDOWS && /^\\\\[^\\]+\\[^\\]+\\$/.test(result)) { result = safeTrimTrailingSeparator(result); } return result; } exports.dirname = dirname; /** * Roots the path if not already rooted. On Windows, relative roots like `\` * or `C:` are expanded based on the current working directory. */ function ensureAbsoluteRoot(root, itemPath) { assert_1.default(root, `ensureAbsoluteRoot parameter 'root' must not be empty`); assert_1.default(itemPath, `ensureAbsoluteRoot parameter 'itemPath' must not be empty`); // Already rooted if (hasAbsoluteRoot(itemPath)) { return itemPath; } // Windows if (IS_WINDOWS) { // Check for itemPath like C: or C:foo if (itemPath.match(/^[A-Z]:[^\\/]|^[A-Z]:$/i)) { let cwd = process.cwd(); assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); // Drive letter matches cwd? Expand to cwd if (itemPath[0].toUpperCase() === cwd[0].toUpperCase()) { // Drive only, e.g. C: if (itemPath.length === 2) { // Preserve specified drive letter case (upper or lower) return `${itemPath[0]}:\\${cwd.substr(3)}`; } // Drive + path, e.g. C:foo else { if (!cwd.endsWith('\\')) { cwd += '\\'; } // Preserve specified drive letter case (upper or lower) return `${itemPath[0]}:\\${cwd.substr(3)}${itemPath.substr(2)}`; } } // Different drive else { return `${itemPath[0]}:\\${itemPath.substr(2)}`; } } // Check for itemPath like \ or \foo else if (normalizeSeparators(itemPath).match(/^\\$|^\\[^\\]/)) { const cwd = process.cwd(); assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); return `${cwd[0]}:\\${itemPath.substr(1)}`; } } assert_1.default(hasAbsoluteRoot(root), `ensureAbsoluteRoot parameter 'root' must have an absolute root`); // Otherwise ensure root ends with a separator if (root.endsWith('/') || (IS_WINDOWS && root.endsWith('\\'))) { // Intentionally empty } else { // Append separator root += path.sep; } return root + itemPath; } exports.ensureAbsoluteRoot = ensureAbsoluteRoot; /** * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like: * `\\hello\share` and `C:\hello` (and using alternate separator). */ function hasAbsoluteRoot(itemPath) { assert_1.default(itemPath, `hasAbsoluteRoot parameter 'itemPath' must not be empty`); // Normalize separators itemPath = normalizeSeparators(itemPath); // Windows if (IS_WINDOWS) { // E.g. \\hello\share or C:\hello return itemPath.startsWith('\\\\') || /^[A-Z]:\\/i.test(itemPath); } // E.g. /hello return itemPath.startsWith('/'); } exports.hasAbsoluteRoot = hasAbsoluteRoot; /** * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like: * `\`, `\hello`, `\\hello\share`, `C:`, and `C:\hello` (and using alternate separator). */ function hasRoot(itemPath) { assert_1.default(itemPath, `isRooted parameter 'itemPath' must not be empty`); // Normalize separators itemPath = normalizeSeparators(itemPath); // Windows if (IS_WINDOWS) { // E.g. \ or \hello or \\hello // E.g. C: or C:\hello return itemPath.startsWith('\\') || /^[A-Z]:/i.test(itemPath); } // E.g. /hello return itemPath.startsWith('/'); } exports.hasRoot = hasRoot; /** * Removes redundant slashes and converts `/` to `\` on Windows */ function normalizeSeparators(p) { p = p || ''; // Windows if (IS_WINDOWS) { // Convert slashes on Windows p = p.replace(/\//g, '\\'); // Remove redundant slashes const isUnc = /^\\\\+[^\\]/.test(p); // e.g. \\hello return (isUnc ? '\\' : '') + p.replace(/\\\\+/g, '\\'); // preserve leading \\ for UNC } // Remove redundant slashes return p.replace(/\/\/+/g, '/'); } exports.normalizeSeparators = normalizeSeparators; /** * Normalizes the path separators and trims the trailing separator (when safe). * For example, `/foo/ => /foo` but `/ => /` */ function safeTrimTrailingSeparator(p) { // Short-circuit if empty if (!p) { return ''; } // Normalize separators p = normalizeSeparators(p); // No trailing slash if (!p.endsWith(path.sep)) { return p; } // Check '/' on Linux/macOS and '\' on Windows if (p === path.sep) { return p; } // On Windows check if drive root. E.g. C:\ if (IS_WINDOWS && /^[A-Z]:\\$/i.test(p)) { return p; } // Otherwise trim trailing slash return p.substr(0, p.length - 1); } exports.safeTrimTrailingSeparator = safeTrimTrailingSeparator; //# sourceMappingURL=internal-path-helper.js.map /***/ }), /***/ 6617: /***/ (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 __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Path = void 0; const path = __importStar(__nccwpck_require__(6928)); const pathHelper = __importStar(__nccwpck_require__(4138)); const assert_1 = __importDefault(__nccwpck_require__(2613)); const IS_WINDOWS = process.platform === 'win32'; /** * Helper class for parsing paths into segments */ class Path { /** * Constructs a Path * @param itemPath Path or array of segments */ constructor(itemPath) { this.segments = []; // String if (typeof itemPath === 'string') { assert_1.default(itemPath, `Parameter 'itemPath' must not be empty`); // Normalize slashes and trim unnecessary trailing slash itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); // Not rooted if (!pathHelper.hasRoot(itemPath)) { this.segments = itemPath.split(path.sep); } // Rooted else { // Add all segments, while not at the root let remaining = itemPath; let dir = pathHelper.dirname(remaining); while (dir !== remaining) { // Add the segment const basename = path.basename(remaining); this.segments.unshift(basename); // Truncate the last segment remaining = dir; dir = pathHelper.dirname(remaining); } // Remainder is the root this.segments.unshift(remaining); } } // Array else { // Must not be empty assert_1.default(itemPath.length > 0, `Parameter 'itemPath' must not be an empty array`); // Each segment for (let i = 0; i < itemPath.length; i++) { let segment = itemPath[i]; // Must not be empty assert_1.default(segment, `Parameter 'itemPath' must not contain any empty segments`); // Normalize slashes segment = pathHelper.normalizeSeparators(itemPath[i]); // Root segment if (i === 0 && pathHelper.hasRoot(segment)) { segment = pathHelper.safeTrimTrailingSeparator(segment); assert_1.default(segment === pathHelper.dirname(segment), `Parameter 'itemPath' root segment contains information for multiple segments`); this.segments.push(segment); } // All other segments else { // Must not contain slash assert_1.default(!segment.includes(path.sep), `Parameter 'itemPath' contains unexpected path separators`); this.segments.push(segment); } } } } /** * Converts the path to it's string representation */ toString() { // First segment let result = this.segments[0]; // All others let skipSlash = result.endsWith(path.sep) || (IS_WINDOWS && /^[A-Z]:$/i.test(result)); for (let i = 1; i < this.segments.length; i++) { if (skipSlash) { skipSlash = false; } else { result += path.sep; } result += this.segments[i]; } return result; } } exports.Path = Path; //# sourceMappingURL=internal-path.js.map /***/ }), /***/ 8891: /***/ (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.partialMatch = exports.match = exports.getSearchPaths = void 0; const pathHelper = __importStar(__nccwpck_require__(4138)); const internal_match_kind_1 = __nccwpck_require__(2644); const IS_WINDOWS = process.platform === 'win32'; /** * Given an array of patterns, returns an array of paths to search. * Duplicates and paths under other included paths are filtered out. */ function getSearchPaths(patterns) { // Ignore negate patterns patterns = patterns.filter(x => !x.negate); // Create a map of all search paths const searchPathMap = {}; for (const pattern of patterns) { const key = IS_WINDOWS ? pattern.searchPath.toUpperCase() : pattern.searchPath; searchPathMap[key] = 'candidate'; } const result = []; for (const pattern of patterns) { // Check if already included const key = IS_WINDOWS ? pattern.searchPath.toUpperCase() : pattern.searchPath; if (searchPathMap[key] === 'included') { continue; } // Check for an ancestor search path let foundAncestor = false; let tempKey = key; let parent = pathHelper.dirname(tempKey); while (parent !== tempKey) { if (searchPathMap[parent]) { foundAncestor = true; break; } tempKey = parent; parent = pathHelper.dirname(tempKey); } // Include the search pattern in the result if (!foundAncestor) { result.push(pattern.searchPath); searchPathMap[key] = 'included'; } } return result; } exports.getSearchPaths = getSearchPaths; /** * Matches the patterns against the path */ function match(patterns, itemPath) { let result = internal_match_kind_1.MatchKind.None; for (const pattern of patterns) { if (pattern.negate) { result &= ~pattern.match(itemPath); } else { result |= pattern.match(itemPath); } } return result; } exports.match = match; /** * Checks whether to descend further into the directory */ function partialMatch(patterns, itemPath) { return patterns.some(x => !x.negate && x.partialMatch(itemPath)); } exports.partialMatch = partialMatch; //# sourceMappingURL=internal-pattern-helper.js.map /***/ }), /***/ 5370: /***/ (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 __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Pattern = void 0; const os = __importStar(__nccwpck_require__(857)); const path = __importStar(__nccwpck_require__(6928)); const pathHelper = __importStar(__nccwpck_require__(4138)); const assert_1 = __importDefault(__nccwpck_require__(2613)); const minimatch_1 = __nccwpck_require__(3772); const internal_match_kind_1 = __nccwpck_require__(2644); const internal_path_1 = __nccwpck_require__(6617); const IS_WINDOWS = process.platform === 'win32'; class Pattern { constructor(patternOrNegate, isImplicitPattern = false, segments, homedir) { /** * Indicates whether matches should be excluded from the result set */ this.negate = false; // Pattern overload let pattern; if (typeof patternOrNegate === 'string') { pattern = patternOrNegate.trim(); } // Segments overload else { // Convert to pattern segments = segments || []; assert_1.default(segments.length, `Parameter 'segments' must not empty`); const root = Pattern.getLiteral(segments[0]); assert_1.default(root && pathHelper.hasAbsoluteRoot(root), `Parameter 'segments' first element must be a root path`); pattern = new internal_path_1.Path(segments).toString().trim(); if (patternOrNegate) { pattern = `!${pattern}`; } } // Negate while (pattern.startsWith('!')) { this.negate = !this.negate; pattern = pattern.substr(1).trim(); } // Normalize slashes and ensures absolute root pattern = Pattern.fixupPattern(pattern, homedir); // Segments this.segments = new internal_path_1.Path(pattern).segments; // Trailing slash indicates the pattern should only match directories, not regular files this.trailingSeparator = pathHelper .normalizeSeparators(pattern) .endsWith(path.sep); pattern = pathHelper.safeTrimTrailingSeparator(pattern); // Search path (literal path prior to the first glob segment) let foundGlob = false; const searchSegments = this.segments .map(x => Pattern.getLiteral(x)) .filter(x => !foundGlob && !(foundGlob = x === '')); this.searchPath = new internal_path_1.Path(searchSegments).toString(); // Root RegExp (required when determining partial match) this.rootRegExp = new RegExp(Pattern.regExpEscape(searchSegments[0]), IS_WINDOWS ? 'i' : ''); this.isImplicitPattern = isImplicitPattern; // Create minimatch const minimatchOptions = { dot: true, nobrace: true, nocase: IS_WINDOWS, nocomment: true, noext: true, nonegate: true }; pattern = IS_WINDOWS ? pattern.replace(/\\/g, '/') : pattern; this.minimatch = new minimatch_1.Minimatch(pattern, minimatchOptions); } /** * Matches the pattern against the specified path */ match(itemPath) { // Last segment is globstar? if (this.segments[this.segments.length - 1] === '**') { // Normalize slashes itemPath = pathHelper.normalizeSeparators(itemPath); // Append a trailing slash. Otherwise Minimatch will not match the directory immediately // preceding the globstar. For example, given the pattern `/foo/**`, Minimatch returns // false for `/foo` but returns true for `/foo/`. Append a trailing slash to handle that quirk. if (!itemPath.endsWith(path.sep) && this.isImplicitPattern === false) { // Note, this is safe because the constructor ensures the pattern has an absolute root. // For example, formats like C: and C:foo on Windows are resolved to an absolute root. itemPath = `${itemPath}${path.sep}`; } } else { // Normalize slashes and trim unnecessary trailing slash itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); } // Match if (this.minimatch.match(itemPath)) { return this.trailingSeparator ? internal_match_kind_1.MatchKind.Directory : internal_match_kind_1.MatchKind.All; } return internal_match_kind_1.MatchKind.None; } /** * Indicates whether the pattern may match descendants of the specified path */ partialMatch(itemPath) { // Normalize slashes and trim unnecessary trailing slash itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); // matchOne does not handle root path correctly if (pathHelper.dirname(itemPath) === itemPath) { return this.rootRegExp.test(itemPath); } return this.minimatch.matchOne(itemPath.split(IS_WINDOWS ? /\\+/ : /\/+/), this.minimatch.set[0], true); } /** * Escapes glob patterns within a path */ static globEscape(s) { return (IS_WINDOWS ? s : s.replace(/\\/g, '\\\\')) // escape '\' on Linux/macOS .replace(/(\[)(?=[^/]+\])/g, '[[]') // escape '[' when ']' follows within the path segment .replace(/\?/g, '[?]') // escape '?' .replace(/\*/g, '[*]'); // escape '*' } /** * Normalizes slashes and ensures absolute root */ static fixupPattern(pattern, homedir) { // Empty assert_1.default(pattern, 'pattern cannot be empty'); // Must not contain `.` segment, unless first segment // Must not contain `..` segment const literalSegments = new internal_path_1.Path(pattern).segments.map(x => Pattern.getLiteral(x)); assert_1.default(literalSegments.every((x, i) => (x !== '.' || i === 0) && x !== '..'), `Invalid pattern '${pattern}'. Relative pathing '.' and '..' is not allowed.`); // Must not contain globs in root, e.g. Windows UNC path \\foo\b*r assert_1.default(!pathHelper.hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`); // Normalize slashes pattern = pathHelper.normalizeSeparators(pattern); // Replace leading `.` segment if (pattern === '.' || pattern.startsWith(`.${path.sep}`)) { pattern = Pattern.globEscape(process.cwd()) + pattern.substr(1); } // Replace leading `~` segment else if (pattern === '~' || pattern.startsWith(`~${path.sep}`)) { homedir = homedir || os.homedir(); assert_1.default(homedir, 'Unable to determine HOME directory'); assert_1.default(pathHelper.hasAbsoluteRoot(homedir), `Expected HOME directory to be a rooted path. Actual '${homedir}'`); pattern = Pattern.globEscape(homedir) + pattern.substr(1); } // Replace relative drive root, e.g. pattern is C: or C:foo else if (IS_WINDOWS && (pattern.match(/^[A-Z]:$/i) || pattern.match(/^[A-Z]:[^\\]/i))) { let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', pattern.substr(0, 2)); if (pattern.length > 2 && !root.endsWith('\\')) { root += '\\'; } pattern = Pattern.globEscape(root) + pattern.substr(2); } // Replace relative root, e.g. pattern is \ or \foo else if (IS_WINDOWS && (pattern === '\\' || pattern.match(/^\\[^\\]/))) { let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', '\\'); if (!root.endsWith('\\')) { root += '\\'; } pattern = Pattern.globEscape(root) + pattern.substr(1); } // Otherwise ensure absolute root else { pattern = pathHelper.ensureAbsoluteRoot(Pattern.globEscape(process.cwd()), pattern); } return pathHelper.normalizeSeparators(pattern); } /** * Attempts to unescape a pattern segment to create a literal path segment. * Otherwise returns empty string. */ static getLiteral(segment) { let literal = ''; for (let i = 0; i < segment.length; i++) { const c = segment[i]; // Escape if (c === '\\' && !IS_WINDOWS && i + 1 < segment.length) { literal += segment[++i]; continue; } // Wildcard else if (c === '*' || c === '?') { return ''; } // Character set else if (c === '[' && i + 1 < segment.length) { let set = ''; let closed = -1; for (let i2 = i + 1; i2 < segment.length; i2++) { const c2 = segment[i2]; // Escape if (c2 === '\\' && !IS_WINDOWS && i2 + 1 < segment.length) { set += segment[++i2]; continue; } // Closed else if (c2 === ']') { closed = i2; break; } // Otherwise else { set += c2; } } // Closed? if (closed >= 0) { // Cannot convert if (set.length > 1) { return ''; } // Convert to literal if (set) { literal += set; i = closed; continue; } } // Otherwise fall thru } // Append literal += c; } return literal; } /** * Escapes regexp special characters * https://javascript.info/regexp-escaping */ static regExpEscape(s) { return s.replace(/[[\\^$.|?*+()]/g, '\\$&'); } } exports.Pattern = Pattern; //# sourceMappingURL=internal-pattern.js.map /***/ }), /***/ 9890: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SearchState = void 0; class SearchState { constructor(path, level) { this.path = path; this.level = level; } } exports.SearchState = SearchState; //# sourceMappingURL=internal-search-state.js.map /***/ }), /***/ 4552: /***/ (function(__unused_webpack_module, exports) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0; class BasicCredentialHandler { constructor(username, password) { this.username = username; this.password = password; } prepareRequest(options) { if (!options.headers) { throw Error('The request has no headers'); } options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; } // This handler cannot handle 401 canHandleAuthentication() { return false; } handleAuthentication() { return __awaiter(this, void 0, void 0, function* () { throw new Error('not implemented'); }); } } exports.BasicCredentialHandler = BasicCredentialHandler; class BearerCredentialHandler { constructor(token) { this.token = token; } // currently implements pre-authorization // TODO: support preAuth = false where it hooks on 401 prepareRequest(options) { if (!options.headers) { throw Error('The request has no headers'); } options.headers['Authorization'] = `Bearer ${this.token}`; } // This handler cannot handle 401 canHandleAuthentication() { return false; } handleAuthentication() { return __awaiter(this, void 0, void 0, function* () { throw new Error('not implemented'); }); } } exports.BearerCredentialHandler = BearerCredentialHandler; class PersonalAccessTokenCredentialHandler { constructor(token) { this.token = token; } // currently implements pre-authorization // TODO: support preAuth = false where it hooks on 401 prepareRequest(options) { if (!options.headers) { throw Error('The request has no headers'); } options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`; } // This handler cannot handle 401 canHandleAuthentication() { return false; } handleAuthentication() { return __awaiter(this, void 0, void 0, function* () { throw new Error('not implemented'); }); } } exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; //# sourceMappingURL=auth.js.map /***/ }), /***/ 4844: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; /* 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]; } }); }) : (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.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; const http = __importStar(__nccwpck_require__(8611)); const https = __importStar(__nccwpck_require__(5692)); const pm = __importStar(__nccwpck_require__(4988)); const tunnel = __importStar(__nccwpck_require__(770)); var HttpCodes; (function (HttpCodes) { HttpCodes[HttpCodes["OK"] = 200] = "OK"; HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; })(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); var Headers; (function (Headers) { Headers["Accept"] = "accept"; Headers["ContentType"] = "content-type"; })(Headers = exports.Headers || (exports.Headers = {})); var MediaTypes; (function (MediaTypes) { MediaTypes["ApplicationJson"] = "application/json"; })(MediaTypes = exports.MediaTypes || (exports.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 */ function getProxyUrl(serverUrl) { const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); return proxyUrl ? proxyUrl.href : ''; } exports.getProxyUrl = getProxyUrl; const HttpRedirectCodes = [ HttpCodes.MovedPermanently, HttpCodes.ResourceMoved, HttpCodes.SeeOther, HttpCodes.TemporaryRedirect, HttpCodes.PermanentRedirect ]; const HttpResponseRetryCodes = [ HttpCodes.BadGateway, HttpCodes.ServiceUnavailable, HttpCodes.GatewayTimeout ]; const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; const ExponentialBackoffCeiling = 10; const ExponentialBackoffTimeSlice = 5; class HttpClientError extends Error { constructor(message, statusCode) { super(message); this.name = 'HttpClientError'; this.statusCode = statusCode; Object.setPrototypeOf(this, HttpClientError.prototype); } } exports.HttpClientError = HttpClientError; class HttpClientResponse { constructor(message) { this.message = message; } readBody() { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { let output = Buffer.alloc(0); this.message.on('data', (chunk) => { output = Buffer.concat([output, chunk]); }); this.message.on('end', () => { resolve(output.toString()); }); })); }); } 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) { const parsedUrl = new URL(requestUrl); return parsedUrl.protocol === 'https:'; } exports.isHttps = isHttps; class HttpClient { constructor(userAgent, handlers, requestOptions) { this._ignoreSslError = false; this._allowRedirects = true; this._allowRedirectDowngrade = false; this._maxRedirects = 50; this._allowRetries = false; this._maxRetries = 1; this._keepAlive = false; this._disposed = false; this.userAgent = userAgent; this.handlers = handlers || []; this.requestOptions = requestOptions; if (requestOptions) { if (requestOptions.ignoreSslError != null) { this._ignoreSslError = requestOptions.ignoreSslError; } this._socketTimeout = requestOptions.socketTimeout; if (requestOptions.allowRedirects != null) { this._allowRedirects = requestOptions.allowRedirects; } if (requestOptions.allowRedirectDowngrade != null) { this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; } if (requestOptions.maxRedirects != null) { this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); } if (requestOptions.keepAlive != null) { this._keepAlive = requestOptions.keepAlive; } if (requestOptions.allowRetries != null) { this._allowRetries = requestOptions.allowRetries; } if (requestOptions.maxRetries != null) { this._maxRetries = requestOptions.maxRetries; } } } options(requestUrl, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); }); } get(requestUrl, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('GET', requestUrl, null, additionalHeaders || {}); }); } del(requestUrl, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('DELETE', requestUrl, null, additionalHeaders || {}); }); } post(requestUrl, data, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('POST', requestUrl, data, additionalHeaders || {}); }); } patch(requestUrl, data, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('PATCH', requestUrl, data, additionalHeaders || {}); }); } put(requestUrl, data, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('PUT', requestUrl, data, additionalHeaders || {}); }); } head(requestUrl, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('HEAD', requestUrl, null, additionalHeaders || {}); }); } sendStream(verb, requestUrl, stream, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request(verb, requestUrl, stream, additionalHeaders); }); } /** * Gets a typed object from an endpoint * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise */ getJson(requestUrl, additionalHeaders = {}) { return __awaiter(this, void 0, void 0, function* () { additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); const res = yield this.get(requestUrl, additionalHeaders); return this._processResponse(res, this.requestOptions); }); } postJson(requestUrl, obj, additionalHeaders = {}) { return __awaiter(this, void 0, void 0, function* () { const data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); const res = yield this.post(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); }); } putJson(requestUrl, obj, additionalHeaders = {}) { return __awaiter(this, void 0, void 0, function* () { const data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); const res = yield this.put(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); }); } patchJson(requestUrl, obj, additionalHeaders = {}) { return __awaiter(this, void 0, void 0, function* () { const data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); const res = yield this.patch(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); }); } /** * Makes a raw http request. * All other methods such as get, post, patch, and request ultimately call this. * Prefer get, del, post and patch */ request(verb, requestUrl, data, headers) { return __awaiter(this, void 0, void 0, function* () { if (this._disposed) { throw new Error('Client has already been disposed.'); } const parsedUrl = new URL(requestUrl); let info = this._prepareRequest(verb, parsedUrl, headers); // Only perform retries on reads since writes may not be idempotent. const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; let numTries = 0; let response; do { response = yield this.requestRaw(info, data); // Check if it's an authentication challenge if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { let authenticationHandler; for (const handler of this.handlers) { if (handler.canHandleAuthentication(response)) { authenticationHandler = handler; break; } } if (authenticationHandler) { return authenticationHandler.handleAuthentication(this, info, data); } else { // We have received an unauthorized response but have no handlers to handle it. // Let the response return to the caller. return response; } } let redirectsRemaining = this._maxRedirects; while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { const redirectUrl = response.message.headers['location']; if (!redirectUrl) { // if there's no location to redirect to, we won't break; } const parsedRedirectUrl = new URL(redirectUrl); if (parsedUrl.protocol === 'https:' && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); } // we need to finish reading the response before reassigning response // which will leak the open socket. yield response.readBody(); // strip authorization header if redirected to a different hostname if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { for (const header in headers) { // header names are case insensitive if (header.toLowerCase() === 'authorization') { delete headers[header]; } } } // let's make the request with the new redirectUrl info = this._prepareRequest(verb, parsedRedirectUrl, headers); response = yield this.requestRaw(info, data); redirectsRemaining--; } if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { // If not a retry code, return immediately instead of retrying return response; } numTries += 1; if (numTries < maxTries) { yield response.readBody(); yield this._performExponentialBackoff(numTries); } } while (numTries < maxTries); return response; }); } /** * Needs to be called if keepAlive is set to true in request options. */ dispose() { if (this._agent) { this._agent.destroy(); } this._disposed = true; } /** * Raw request. * @param info * @param data */ requestRaw(info, data) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => { function callbackForResult(err, res) { if (err) { reject(err); } else if (!res) { // If `err` is not passed, then `res` must be passed. reject(new Error('Unknown error')); } else { resolve(res); } } this.requestRawWithCallback(info, data, callbackForResult); }); }); } /** * Raw request with callback. * @param info * @param data * @param onResult */ requestRawWithCallback(info, data, onResult) { if (typeof data === 'string') { if (!info.options.headers) { info.options.headers = {}; } info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); } let callbackCalled = false; function handleResult(err, res) { if (!callbackCalled) { callbackCalled = true; onResult(err, res); } } const req = info.httpModule.request(info.options, (msg) => { const res = new HttpClientResponse(msg); handleResult(undefined, res); }); let socket; req.on('socket', sock => { socket = sock; }); // If we ever get disconnected, we want the socket to timeout eventually req.setTimeout(this._socketTimeout || 3 * 60000, () => { if (socket) { socket.end(); } handleResult(new Error(`Request timeout: ${info.options.path}`)); }); req.on('error', function (err) { // err has statusCode property // res should have headers handleResult(err); }); if (data && typeof data === 'string') { req.write(data, 'utf8'); } if (data && typeof data !== 'string') { data.on('close', function () { req.end(); }); data.pipe(req); } else { req.end(); } } /** * Gets an http agent. This function is useful when you need an http agent that handles * routing through a proxy server - depending upon the url and proxy environment variables. * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ getAgent(serverUrl) { const parsedUrl = new URL(serverUrl); return this._getAgent(parsedUrl); } _prepareRequest(method, requestUrl, headers) { const info = {}; info.parsedUrl = requestUrl; const usingSsl = info.parsedUrl.protocol === 'https:'; info.httpModule = usingSsl ? https : http; const defaultPort = usingSsl ? 443 : 80; info.options = {}; info.options.host = info.parsedUrl.hostname; info.options.port = info.parsedUrl.port ? parseInt(info.parsedUrl.port) : defaultPort; info.options.path = (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); info.options.method = method; info.options.headers = this._mergeHeaders(headers); if (this.userAgent != null) { info.options.headers['user-agent'] = this.userAgent; } info.options.agent = this._getAgent(info.parsedUrl); // gives handlers an opportunity to participate if (this.handlers) { for (const handler of this.handlers) { handler.prepareRequest(info.options); } } return info; } _mergeHeaders(headers) { if (this.requestOptions && this.requestOptions.headers) { return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } return lowercaseKeys(headers || {}); } _getExistingOrDefaultHeader(additionalHeaders, header, _default) { let clientHeader; if (this.requestOptions && this.requestOptions.headers) { clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; } return additionalHeaders[header] || clientHeader || _default; } _getAgent(parsedUrl) { let agent; const proxyUrl = pm.getProxyUrl(parsedUrl); const useProxy = proxyUrl && proxyUrl.hostname; if (this._keepAlive && useProxy) { agent = this._proxyAgent; } if (this._keepAlive && !useProxy) { agent = this._agent; } // if agent is already assigned use that agent. if (agent) { return agent; } const usingSsl = parsedUrl.protocol === 'https:'; let maxSockets = 100; if (this.requestOptions) { maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; } // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis. if (proxyUrl && proxyUrl.hostname) { const agentOptions = { maxSockets, keepAlive: this._keepAlive, proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && { proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` })), { host: proxyUrl.hostname, port: proxyUrl.port }) }; let tunnelAgent; const overHttps = proxyUrl.protocol === 'https:'; if (usingSsl) { tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; } else { tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } 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) { 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 // we have to cast it to any and change it directly agent.options = Object.assign(agent.options || {}, { rejectUnauthorized: false }); } return agent; } _performExponentialBackoff(retryNumber) { return __awaiter(this, void 0, void 0, function* () { retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); return new Promise(resolve => setTimeout(() => resolve(), ms)); }); } _processResponse(res, options) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { const statusCode = res.message.statusCode || 0; const response = { statusCode, result: null, headers: {} }; // not found leads to null obj returned if (statusCode === HttpCodes.NotFound) { resolve(response); } // get the result from the body function dateTimeDeserializer(key, value) { if (typeof value === 'string') { const a = new Date(value); if (!isNaN(a.valueOf())) { return a; } } return value; } let obj; let contents; try { contents = yield res.readBody(); if (contents && contents.length > 0) { if (options && options.deserializeDates) { obj = JSON.parse(contents, dateTimeDeserializer); } else { obj = JSON.parse(contents); } response.result = obj; } response.headers = res.message.headers; } catch (err) { // Invalid resource (contents not json); leaving result obj null } // note that 3xx redirects are handled by the http layer. if (statusCode > 299) { let msg; // if exception/error in body, attempt to get better error if (obj && obj.message) { msg = obj.message; } else if (contents && contents.length > 0) { // it may be the case that the exception is in the body message as string msg = contents; } else { msg = `Failed request: (${statusCode})`; } const err = new HttpClientError(msg, statusCode); err.result = response.result; reject(err); } else { resolve(response); } })); }); } } exports.HttpClient = HttpClient; const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); //# sourceMappingURL=index.js.map /***/ }), /***/ 4988: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.checkBypass = exports.getProxyUrl = void 0; function getProxyUrl(reqUrl) { const usingSsl = reqUrl.protocol === 'https:'; if (checkBypass(reqUrl)) { return undefined; } const proxyVar = (() => { if (usingSsl) { return process.env['https_proxy'] || process.env['HTTPS_PROXY']; } else { return process.env['http_proxy'] || process.env['HTTP_PROXY']; } })(); if (proxyVar) { try { return new URL(proxyVar); } catch (_a) { if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) return new URL(`http://${proxyVar}`); } } else { return undefined; } } exports.getProxyUrl = getProxyUrl; 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; } // Determine the request port let reqPort; if (reqUrl.port) { reqPort = Number(reqUrl.port); } else if (reqUrl.protocol === 'http:') { reqPort = 80; } else if (reqUrl.protocol === 'https:') { reqPort = 443; } // Format the request hostname and hostname with port const upperReqHosts = [reqUrl.hostname.toUpperCase()]; if (typeof reqPort === 'number') { upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } // Compare request host against noproxy for (const upperNoProxyItem of noProxy .split(',') .map(x => x.trim().toUpperCase()) .filter(x => x)) { 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 /***/ }), /***/ 5207: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var _a; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getCmdPath = exports.tryGetExecutablePath = exports.isRooted = exports.isDirectory = exports.exists = exports.READONLY = exports.UV_FS_O_EXLOCK = exports.IS_WINDOWS = exports.unlink = exports.symlink = exports.stat = exports.rmdir = exports.rm = exports.rename = exports.readlink = exports.readdir = exports.open = exports.mkdir = exports.lstat = exports.copyFile = exports.chmod = void 0; const fs = __importStar(__nccwpck_require__(9896)); const path = __importStar(__nccwpck_require__(6928)); _a = fs.promises // export const {open} = 'fs' , exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.open = _a.open, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rm = _a.rm, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; // export const {open} = 'fs' exports.IS_WINDOWS = process.platform === 'win32'; // See https://github.com/nodejs/node/blob/d0153aee367422d0858105abec186da4dff0a0c5/deps/uv/include/uv/win.h#L691 exports.UV_FS_O_EXLOCK = 0x10000000; exports.READONLY = fs.constants.O_RDONLY; function exists(fsPath) { return __awaiter(this, void 0, void 0, function* () { try { yield exports.stat(fsPath); } catch (err) { if (err.code === 'ENOENT') { return false; } throw err; } return true; }); } exports.exists = exists; function isDirectory(fsPath, useStat = false) { return __awaiter(this, void 0, void 0, function* () { const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath); return stats.isDirectory(); }); } exports.isDirectory = isDirectory; /** * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like: * \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases). */ function isRooted(p) { p = normalizeSeparators(p); if (!p) { throw new Error('isRooted() parameter "p" cannot be empty'); } if (exports.IS_WINDOWS) { return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello ); // e.g. C: or C:\hello } return p.startsWith('/'); } exports.isRooted = isRooted; /** * Best effort attempt to determine whether a file exists and is executable. * @param filePath file path to check * @param extensions additional file extensions to try * @return if file exists and is executable, returns the file path. otherwise empty string. */ function tryGetExecutablePath(filePath, extensions) { return __awaiter(this, void 0, void 0, function* () { let stats = undefined; try { // test file exists stats = yield exports.stat(filePath); } catch (err) { if (err.code !== 'ENOENT') { // eslint-disable-next-line no-console console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); } } if (stats && stats.isFile()) { if (exports.IS_WINDOWS) { // on Windows, test for valid extension const upperExt = path.extname(filePath).toUpperCase(); if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) { return filePath; } } else { if (isUnixExecutable(stats)) { return filePath; } } } // try each extension const originalFilePath = filePath; for (const extension of extensions) { filePath = originalFilePath + extension; stats = undefined; try { stats = yield exports.stat(filePath); } catch (err) { if (err.code !== 'ENOENT') { // eslint-disable-next-line no-console console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); } } if (stats && stats.isFile()) { if (exports.IS_WINDOWS) { // preserve the case of the actual file (since an extension was appended) try { const directory = path.dirname(filePath); const upperName = path.basename(filePath).toUpperCase(); for (const actualName of yield exports.readdir(directory)) { if (upperName === actualName.toUpperCase()) { filePath = path.join(directory, actualName); break; } } } catch (err) { // eslint-disable-next-line no-console console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`); } return filePath; } else { if (isUnixExecutable(stats)) { return filePath; } } } } return ''; }); } exports.tryGetExecutablePath = tryGetExecutablePath; function normalizeSeparators(p) { p = p || ''; if (exports.IS_WINDOWS) { // convert slashes on Windows p = p.replace(/\//g, '\\'); // remove redundant slashes return p.replace(/\\\\+/g, '\\'); } // remove redundant slashes return p.replace(/\/\/+/g, '/'); } // on Mac/Linux, test the execute bit // R W X R W X R W X // 256 128 64 32 16 8 4 2 1 function isUnixExecutable(stats) { return ((stats.mode & 1) > 0 || ((stats.mode & 8) > 0 && stats.gid === process.getgid()) || ((stats.mode & 64) > 0 && stats.uid === process.getuid())); } // Get the path of cmd.exe in windows function getCmdPath() { var _a; return (_a = process.env['COMSPEC']) !== null && _a !== void 0 ? _a : `cmd.exe`; } exports.getCmdPath = getCmdPath; //# sourceMappingURL=io-util.js.map /***/ }), /***/ 4994: /***/ (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.findInPath = exports.which = exports.mkdirP = exports.rmRF = exports.mv = exports.cp = void 0; const assert_1 = __nccwpck_require__(2613); const path = __importStar(__nccwpck_require__(6928)); const ioUtil = __importStar(__nccwpck_require__(5207)); /** * Copies a file or folder. * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js * * @param source source path * @param dest destination path * @param options optional. See CopyOptions. */ function cp(source, dest, options = {}) { return __awaiter(this, void 0, void 0, function* () { const { force, recursive, copySourceDirectory } = readCopyOptions(options); const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null; // Dest is an existing file, but not forcing if (destStat && destStat.isFile() && !force) { return; } // If dest is an existing directory, should copy inside. const newDest = destStat && destStat.isDirectory() && copySourceDirectory ? path.join(dest, path.basename(source)) : dest; if (!(yield ioUtil.exists(source))) { throw new Error(`no such file or directory: ${source}`); } const sourceStat = yield ioUtil.stat(source); if (sourceStat.isDirectory()) { if (!recursive) { throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`); } else { yield cpDirRecursive(source, newDest, 0, force); } } else { if (path.relative(source, newDest) === '') { // a file cannot be copied to itself throw new Error(`'${newDest}' and '${source}' are the same file`); } yield copyFile(source, newDest, force); } }); } exports.cp = cp; /** * Moves a path. * * @param source source path * @param dest destination path * @param options optional. See MoveOptions. */ function mv(source, dest, options = {}) { return __awaiter(this, void 0, void 0, function* () { if (yield ioUtil.exists(dest)) { let destExists = true; if (yield ioUtil.isDirectory(dest)) { // If dest is directory copy src into dest dest = path.join(dest, path.basename(source)); destExists = yield ioUtil.exists(dest); } if (destExists) { if (options.force == null || options.force) { yield rmRF(dest); } else { throw new Error('Destination already exists'); } } } yield mkdirP(path.dirname(dest)); yield ioUtil.rename(source, dest); }); } exports.mv = mv; /** * Remove a path recursively with force * * @param inputPath path to remove */ function rmRF(inputPath) { return __awaiter(this, void 0, void 0, function* () { if (ioUtil.IS_WINDOWS) { // Check for invalid characters // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file if (/[*"<>|]/.test(inputPath)) { throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows'); } } try { // note if path does not exist, error is silent yield ioUtil.rm(inputPath, { force: true, maxRetries: 3, recursive: true, retryDelay: 300 }); } catch (err) { throw new Error(`File was unable to be removed ${err}`); } }); } exports.rmRF = rmRF; /** * Make a directory. Creates the full path with folders in between * Will throw if it fails * * @param fsPath path to create * @returns Promise */ function mkdirP(fsPath) { return __awaiter(this, void 0, void 0, function* () { assert_1.ok(fsPath, 'a path argument must be provided'); yield ioUtil.mkdir(fsPath, { recursive: true }); }); } exports.mkdirP = mkdirP; /** * Returns path of a tool had the tool actually been invoked. Resolves via paths. * If you check and the tool does not exist, it will throw. * * @param tool name of the tool * @param check whether to check if tool exists * @returns Promise path to tool */ function which(tool, check) { return __awaiter(this, void 0, void 0, function* () { if (!tool) { throw new Error("parameter 'tool' is required"); } // recursive when check=true if (check) { const result = yield which(tool, false); if (!result) { if (ioUtil.IS_WINDOWS) { throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`); } else { throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`); } } return result; } const matches = yield findInPath(tool); if (matches && matches.length > 0) { return matches[0]; } return ''; }); } exports.which = which; /** * Returns a list of all occurrences of the given tool on the system path. * * @returns Promise the paths of the tool */ function findInPath(tool) { return __awaiter(this, void 0, void 0, function* () { if (!tool) { throw new Error("parameter 'tool' is required"); } // build the list of extensions to try const extensions = []; if (ioUtil.IS_WINDOWS && process.env['PATHEXT']) { for (const extension of process.env['PATHEXT'].split(path.delimiter)) { if (extension) { extensions.push(extension); } } } // if it's rooted, return it if exists. otherwise return empty. if (ioUtil.isRooted(tool)) { const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions); if (filePath) { return [filePath]; } return []; } // if any path separators, return empty if (tool.includes(path.sep)) { return []; } // build the list of directories // // Note, technically "where" checks the current directory on Windows. From a toolkit perspective, // it feels like we should not do this. Checking the current directory seems like more of a use // case of a shell, and the which() function exposed by the toolkit should strive for consistency // across platforms. const directories = []; if (process.env.PATH) { for (const p of process.env.PATH.split(path.delimiter)) { if (p) { directories.push(p); } } } // find all matches const matches = []; for (const directory of directories) { const filePath = yield ioUtil.tryGetExecutablePath(path.join(directory, tool), extensions); if (filePath) { matches.push(filePath); } } return matches; }); } exports.findInPath = findInPath; function readCopyOptions(options) { const force = options.force == null ? true : options.force; const recursive = Boolean(options.recursive); const copySourceDirectory = options.copySourceDirectory == null ? true : Boolean(options.copySourceDirectory); return { force, recursive, copySourceDirectory }; } function cpDirRecursive(sourceDir, destDir, currentDepth, force) { return __awaiter(this, void 0, void 0, function* () { // Ensure there is not a run away recursive copy if (currentDepth >= 255) return; currentDepth++; yield mkdirP(destDir); const files = yield ioUtil.readdir(sourceDir); for (const fileName of files) { const srcFile = `${sourceDir}/${fileName}`; const destFile = `${destDir}/${fileName}`; const srcFileStat = yield ioUtil.lstat(srcFile); if (srcFileStat.isDirectory()) { // Recurse yield cpDirRecursive(srcFile, destFile, currentDepth, force); } else { yield copyFile(srcFile, destFile, force); } } // Change the mode for the newly created directory yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode); }); } // Buffered file copy function copyFile(srcFile, destFile, force) { return __awaiter(this, void 0, void 0, function* () { if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) { // unlink/re-link it try { yield ioUtil.lstat(destFile); yield ioUtil.unlink(destFile); } catch (e) { // Try to override file permission if (e.code === 'EPERM') { yield ioUtil.chmod(destFile, '0666'); yield ioUtil.unlink(destFile); } // other errors = it doesn't exist, no work to do } // Copy over symlink const symlinkFull = yield ioUtil.readlink(srcFile); yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null); } else if (!(yield ioUtil.exists(destFile)) || force) { yield ioUtil.copyFile(srcFile, destFile); } }); } //# sourceMappingURL=io.js.map /***/ }), /***/ 8110: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /// const listenersMap = new WeakMap(); const abortedMap = new WeakMap(); /** * An aborter instance implements AbortSignal interface, can abort HTTP requests. * * - Call AbortSignal.none to create a new AbortSignal instance that cannot be cancelled. * Use `AbortSignal.none` when you are required to pass a cancellation token but the operation * cannot or will not ever be cancelled. * * @example * Abort without timeout * ```ts * await doAsyncWork(AbortSignal.none); * ``` */ class AbortSignal { constructor() { /** * onabort event listener. */ this.onabort = null; listenersMap.set(this, []); abortedMap.set(this, false); } /** * Status of whether aborted or not. * * @readonly */ get aborted() { if (!abortedMap.has(this)) { throw new TypeError("Expected `this` to be an instance of AbortSignal."); } return abortedMap.get(this); } /** * Creates a new AbortSignal instance that will never be aborted. * * @readonly */ static get none() { return new AbortSignal(); } /** * Added new "abort" event listener, only support "abort" event. * * @param _type - Only support "abort" event * @param listener - The listener to be added */ addEventListener( // tslint:disable-next-line:variable-name _type, listener) { if (!listenersMap.has(this)) { throw new TypeError("Expected `this` to be an instance of AbortSignal."); } const listeners = listenersMap.get(this); listeners.push(listener); } /** * Remove "abort" event listener, only support "abort" event. * * @param _type - Only support "abort" event * @param listener - The listener to be removed */ removeEventListener( // tslint:disable-next-line:variable-name _type, listener) { if (!listenersMap.has(this)) { throw new TypeError("Expected `this` to be an instance of AbortSignal."); } const listeners = listenersMap.get(this); const index = listeners.indexOf(listener); if (index > -1) { listeners.splice(index, 1); } } /** * Dispatches a synthetic event to the AbortSignal. */ dispatchEvent(_event) { throw new Error("This is a stub dispatchEvent implementation that should not be used. It only exists for type-checking purposes."); } } /** * Helper to trigger an abort event immediately, the onabort and all abort event listeners will be triggered. * Will try to trigger abort event for all linked AbortSignal nodes. * * - If there is a timeout, the timer will be cancelled. * - If aborted is true, nothing will happen. * * @internal */ // eslint-disable-next-line @azure/azure-sdk/ts-use-interface-parameters function abortSignal(signal) { if (signal.aborted) { return; } if (signal.onabort) { signal.onabort.call(signal); } const listeners = listenersMap.get(signal); if (listeners) { // Create a copy of listeners so mutations to the array // (e.g. via removeListener calls) don't affect the listeners // we invoke. listeners.slice().forEach((listener) => { listener.call(signal, { type: "abort" }); }); } abortedMap.set(signal, true); } // Copyright (c) Microsoft Corporation. /** * This error is thrown when an asynchronous operation has been aborted. * Check for this error by testing the `name` that the name property of the * error matches `"AbortError"`. * * @example * ```ts * const controller = new AbortController(); * controller.abort(); * try { * doAsyncWork(controller.signal) * } catch (e) { * if (e.name === 'AbortError') { * // handle abort error here. * } * } * ``` */ class AbortError extends Error { constructor(message) { super(message); this.name = "AbortError"; } } /** * An AbortController provides an AbortSignal and the associated controls to signal * that an asynchronous operation should be aborted. * * @example * Abort an operation when another event fires * ```ts * const controller = new AbortController(); * const signal = controller.signal; * doAsyncWork(signal); * button.addEventListener('click', () => controller.abort()); * ``` * * @example * Share aborter cross multiple operations in 30s * ```ts * // Upload the same data to 2 different data centers at the same time, * // abort another when any of them is finished * const controller = AbortController.withTimeout(30 * 1000); * doAsyncWork(controller.signal).then(controller.abort); * doAsyncWork(controller.signal).then(controller.abort); *``` * * @example * Cascaded aborting * ```ts * // All operations can't take more than 30 seconds * const aborter = Aborter.timeout(30 * 1000); * * // Following 2 operations can't take more than 25 seconds * await doAsyncWork(aborter.withTimeout(25 * 1000)); * await doAsyncWork(aborter.withTimeout(25 * 1000)); * ``` */ class AbortController { // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types constructor(parentSignals) { this._signal = new AbortSignal(); if (!parentSignals) { return; } // coerce parentSignals into an array if (!Array.isArray(parentSignals)) { // eslint-disable-next-line prefer-rest-params parentSignals = arguments; } for (const parentSignal of parentSignals) { // if the parent signal has already had abort() called, // then call abort on this signal as well. if (parentSignal.aborted) { this.abort(); } else { // when the parent signal aborts, this signal should as well. parentSignal.addEventListener("abort", () => { this.abort(); }); } } } /** * The AbortSignal associated with this controller that will signal aborted * when the abort method is called on this controller. * * @readonly */ get signal() { return this._signal; } /** * Signal that any operations passed this controller's associated abort signal * to cancel any remaining work and throw an `AbortError`. */ abort() { abortSignal(this._signal); } /** * Creates a new AbortSignal instance that will abort after the provided ms. * @param ms - Elapsed time in milliseconds to trigger an abort. */ static timeout(ms) { const signal = new AbortSignal(); const timer = setTimeout(abortSignal, ms, signal); // Prevent the active Timer from keeping the Node.js event loop active. if (typeof timer.unref === "function") { timer.unref(); } return signal; } } exports.AbortController = AbortController; exports.AbortError = AbortError; exports.AbortSignal = AbortSignal; //# sourceMappingURL=index.js.map /***/ }), /***/ 3905: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * A static-key-based credential that supports updating * the underlying key value. */ class AzureKeyCredential { /** * Create an instance of an AzureKeyCredential for use * with a service client. * * @param key - The initial value of the key to use in authentication */ constructor(key) { if (!key) { throw new Error("key must be a non-empty string"); } this._key = key; } /** * The value of the key to be used in authentication */ get key() { return this._key; } /** * Change the value of the key. * * Updates will take effect upon the next request after * updating the key value. * * @param newKey - The new key value to be used */ update(newKey) { this._key = newKey; } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * Helper TypeGuard that checks if something is defined or not. * @param thing - Anything * @internal */ function isDefined(thing) { return typeof thing !== "undefined" && thing !== null; } /** * Helper TypeGuard that checks if the input is an object with the specified properties. * Note: The properties may be inherited. * @param thing - Anything. * @param properties - The name of the properties that should appear in the object. * @internal */ function isObjectWithProperties(thing, properties) { if (!isDefined(thing) || typeof thing !== "object") { return false; } for (const property of properties) { if (!objectHasProperty(thing, property)) { return false; } } return true; } /** * Helper TypeGuard that checks if the input is an object with the specified property. * Note: The property may be inherited. * @param thing - Any object. * @param property - The name of the property that should appear in the object. * @internal */ function objectHasProperty(thing, property) { return typeof thing === "object" && property in thing; } // Copyright (c) Microsoft Corporation. /** * A static name/key-based credential that supports updating * the underlying name and key values. */ class AzureNamedKeyCredential { /** * Create an instance of an AzureNamedKeyCredential for use * with a service client. * * @param name - The initial value of the name to use in authentication. * @param key - The initial value of the key to use in authentication. */ constructor(name, key) { if (!name || !key) { throw new TypeError("name and key must be non-empty strings"); } this._name = name; this._key = key; } /** * The value of the key to be used in authentication. */ get key() { return this._key; } /** * The value of the name to be used in authentication. */ get name() { return this._name; } /** * Change the value of the key. * * Updates will take effect upon the next request after * updating the key value. * * @param newName - The new name value to be used. * @param newKey - The new key value to be used. */ update(newName, newKey) { if (!newName || !newKey) { throw new TypeError("newName and newKey must be non-empty strings"); } this._name = newName; this._key = newKey; } } /** * Tests an object to determine whether it implements NamedKeyCredential. * * @param credential - The assumed NamedKeyCredential to be tested. */ function isNamedKeyCredential(credential) { return (isObjectWithProperties(credential, ["name", "key"]) && typeof credential.key === "string" && typeof credential.name === "string"); } // Copyright (c) Microsoft Corporation. /** * A static-signature-based credential that supports updating * the underlying signature value. */ class AzureSASCredential { /** * Create an instance of an AzureSASCredential for use * with a service client. * * @param signature - The initial value of the shared access signature to use in authentication */ constructor(signature) { if (!signature) { throw new Error("shared access signature must be a non-empty string"); } this._signature = signature; } /** * The value of the shared access signature to be used in authentication */ get signature() { return this._signature; } /** * Change the value of the signature. * * Updates will take effect upon the next request after * updating the signature value. * * @param newSignature - The new shared access signature value to be used */ update(newSignature) { if (!newSignature) { throw new Error("shared access signature must be a non-empty string"); } this._signature = newSignature; } } /** * Tests an object to determine whether it implements SASCredential. * * @param credential - The assumed SASCredential to be tested. */ function isSASCredential(credential) { return (isObjectWithProperties(credential, ["signature"]) && typeof credential.signature === "string"); } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * Tests an object to determine whether it implements TokenCredential. * * @param credential - The assumed TokenCredential to be tested. */ function isTokenCredential(credential) { // Check for an object with a 'getToken' function and possibly with // a 'signRequest' function. We do this check to make sure that // a ServiceClientCredentials implementor (like TokenClientCredentials // in ms-rest-nodeauth) doesn't get mistaken for a TokenCredential if // it doesn't actually implement TokenCredential also. const castCredential = credential; return (castCredential && typeof castCredential.getToken === "function" && (castCredential.signRequest === undefined || castCredential.getToken.length > 0)); } exports.AzureKeyCredential = AzureKeyCredential; exports.AzureNamedKeyCredential = AzureNamedKeyCredential; exports.AzureSASCredential = AzureSASCredential; exports.isNamedKeyCredential = isNamedKeyCredential; exports.isSASCredential = isSASCredential; exports.isTokenCredential = isTokenCredential; //# sourceMappingURL=index.js.map /***/ }), /***/ 9283: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); var uuid = __nccwpck_require__(2048); var util = __nccwpck_require__(9023); var tslib = __nccwpck_require__(470); var xml2js = __nccwpck_require__(758); var coreUtil = __nccwpck_require__(8735); var logger$1 = __nccwpck_require__(4505); var coreAuth = __nccwpck_require__(3905); var os = __nccwpck_require__(857); var http = __nccwpck_require__(8611); var https = __nccwpck_require__(5692); var abortController = __nccwpck_require__(8110); var tunnel = __nccwpck_require__(770); var stream = __nccwpck_require__(2203); var FormData = __nccwpck_require__(172); var node_fetch = __nccwpck_require__(6705); var coreTracing = __nccwpck_require__(5553); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } 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 xml2js__namespace = /*#__PURE__*/_interopNamespace(xml2js); var os__namespace = /*#__PURE__*/_interopNamespace(os); var http__namespace = /*#__PURE__*/_interopNamespace(http); var https__namespace = /*#__PURE__*/_interopNamespace(https); var tunnel__namespace = /*#__PURE__*/_interopNamespace(tunnel); var FormData__default = /*#__PURE__*/_interopDefaultLegacy(FormData); var node_fetch__default = /*#__PURE__*/_interopDefaultLegacy(node_fetch); // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * A collection of HttpHeaders that can be sent with a HTTP request. */ function getHeaderKey(headerName) { return headerName.toLowerCase(); } function isHttpHeadersLike(object) { if (object && typeof object === "object") { const castObject = object; if (typeof castObject.rawHeaders === "function" && typeof castObject.clone === "function" && typeof castObject.get === "function" && typeof castObject.set === "function" && typeof castObject.contains === "function" && typeof castObject.remove === "function" && typeof castObject.headersArray === "function" && typeof castObject.headerValues === "function" && typeof castObject.headerNames === "function" && typeof castObject.toJson === "function") { return true; } } return false; } /** * A collection of HTTP header key/value pairs. */ class HttpHeaders { constructor(rawHeaders) { this._headersMap = {}; if (rawHeaders) { for (const headerName in rawHeaders) { this.set(headerName, rawHeaders[headerName]); } } } /** * Set a header in this collection with the provided name and value. The name is * case-insensitive. * @param headerName - The name of the header to set. This value is case-insensitive. * @param headerValue - The value of the header to set. */ set(headerName, headerValue) { this._headersMap[getHeaderKey(headerName)] = { name: headerName, value: headerValue.toString().trim(), }; } /** * Get the header value for the provided header name, or undefined if no header exists in this * collection with the provided name. * @param headerName - The name of the header. */ get(headerName) { const header = this._headersMap[getHeaderKey(headerName)]; return !header ? undefined : header.value; } /** * Get whether or not this header collection contains a header entry for the provided header name. */ contains(headerName) { return !!this._headersMap[getHeaderKey(headerName)]; } /** * Remove the header with the provided headerName. Return whether or not the header existed and * was removed. * @param headerName - The name of the header to remove. */ remove(headerName) { const result = this.contains(headerName); delete this._headersMap[getHeaderKey(headerName)]; return result; } /** * Get the headers that are contained this collection as an object. */ rawHeaders() { return this.toJson({ preserveCase: true }); } /** * Get the headers that are contained in this collection as an array. */ headersArray() { const headers = []; for (const headerKey in this._headersMap) { headers.push(this._headersMap[headerKey]); } return headers; } /** * Get the header names that are contained in this collection. */ headerNames() { const headerNames = []; const headers = this.headersArray(); for (let i = 0; i < headers.length; ++i) { headerNames.push(headers[i].name); } return headerNames; } /** * Get the header values that are contained in this collection. */ headerValues() { const headerValues = []; const headers = this.headersArray(); for (let i = 0; i < headers.length; ++i) { headerValues.push(headers[i].value); } return headerValues; } /** * Get the JSON object representation of this HTTP header collection. */ toJson(options = {}) { const result = {}; if (options.preserveCase) { for (const headerKey in this._headersMap) { const header = this._headersMap[headerKey]; result[header.name] = header.value; } } else { for (const headerKey in this._headersMap) { const header = this._headersMap[headerKey]; result[getHeaderKey(header.name)] = header.value; } } return result; } /** * Get the string representation of this HTTP header collection. */ toString() { return JSON.stringify(this.toJson({ preserveCase: true })); } /** * Create a deep clone/copy of this HttpHeaders collection. */ clone() { const resultPreservingCasing = {}; for (const headerKey in this._headersMap) { const header = this._headersMap[headerKey]; resultPreservingCasing[header.name] = header.value; } return new HttpHeaders(resultPreservingCasing); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * Encodes a string in base64 format. * @param value - The string to encode */ function encodeString(value) { return Buffer.from(value).toString("base64"); } /** * Encodes a byte array in base64 format. * @param value - The Uint8Aray to encode */ function encodeByteArray(value) { // Buffer.from accepts | -- the TypeScript definition is off here // https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length const bufferValue = value instanceof Buffer ? value : Buffer.from(value.buffer); return bufferValue.toString("base64"); } /** * Decodes a base64 string into a byte array. * @param value - The base64 string to decode */ function decodeString(value) { return Buffer.from(value, "base64"); } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * A set of constants used internally when processing requests. */ const Constants = { /** * The core-http version */ coreHttpVersion: "3.0.4", /** * Specifies HTTP. */ HTTP: "http:", /** * Specifies HTTPS. */ HTTPS: "https:", /** * Specifies HTTP Proxy. */ HTTP_PROXY: "HTTP_PROXY", /** * Specifies HTTPS Proxy. */ HTTPS_PROXY: "HTTPS_PROXY", /** * Specifies NO Proxy. */ NO_PROXY: "NO_PROXY", /** * Specifies ALL Proxy. */ ALL_PROXY: "ALL_PROXY", HttpConstants: { /** * Http Verbs */ HttpVerbs: { PUT: "PUT", GET: "GET", DELETE: "DELETE", POST: "POST", MERGE: "MERGE", HEAD: "HEAD", PATCH: "PATCH", }, StatusCodes: { TooManyRequests: 429, ServiceUnavailable: 503, }, }, /** * Defines constants for use with HTTP headers. */ HeaderConstants: { /** * The Authorization header. */ AUTHORIZATION: "authorization", AUTHORIZATION_SCHEME: "Bearer", /** * The Retry-After response-header field can be used with a 503 (Service * Unavailable) or 349 (Too Many Requests) responses to indicate how long * the service is expected to be unavailable to the requesting client. */ RETRY_AFTER: "Retry-After", /** * The UserAgent header. */ USER_AGENT: "User-Agent", }, }; // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * Default key used to access the XML attributes. */ const XML_ATTRKEY = "$"; /** * Default key used to access the XML value content. */ 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; /** * Encodes an URI. * * @param uri - The URI to be encoded. * @returns The encoded URI. */ function encodeUri(uri) { return encodeURIComponent(uri) .replace(/!/g, "%21") .replace(/"/g, "%27") .replace(/\(/g, "%28") .replace(/\)/g, "%29") .replace(/\*/g, "%2A"); } /** * Returns a stripped version of the Http Response which only contains body, * headers and the status. * * @param response - The Http Response * @returns The stripped version of Http Response. */ function stripResponse(response) { const strippedResponse = {}; strippedResponse.body = response.bodyAsText; strippedResponse.headers = response.headers; strippedResponse.status = response.status; return strippedResponse; } /** * Returns a stripped version of the Http Request that does not contain the * Authorization header. * * @param request - The Http Request object * @returns The stripped version of Http Request. */ function stripRequest(request) { const strippedRequest = request.clone(); if (strippedRequest.headers) { strippedRequest.headers.remove("authorization"); } return strippedRequest; } /** * Validates the given uuid as a string * * @param uuid - The uuid as a string that needs to be validated * @returns True if the uuid is valid; false otherwise. */ function isValidUuid(uuid) { return validUuidRegex.test(uuid); } /** * Generated UUID * * @returns RFC4122 v4 UUID. */ function generateUuid() { return uuid.v4(); } /** * Executes an array of promises sequentially. Inspiration of this method is here: * https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html. An awesome blog on promises! * * @param promiseFactories - An array of promise factories(A function that return a promise) * @param kickstart - Input to the first promise that is used to kickstart the promise chain. * If not provided then the promise chain starts with undefined. * @returns A chain of resolved or rejected promises */ function executePromisesSequentially(promiseFactories, kickstart) { let result = Promise.resolve(kickstart); promiseFactories.forEach((promiseFactory) => { result = result.then(promiseFactory); }); return result; } /** * Converts a Promise to a callback. * @param promise - The Promise to be converted to a callback * @returns A function that takes the callback `(cb: Function) => void` * @deprecated generated code should instead depend on responseToBody */ // eslint-disable-next-line @typescript-eslint/ban-types function promiseToCallback(promise) { if (typeof promise.then !== "function") { throw new Error("The provided input is not a Promise."); } // eslint-disable-next-line @typescript-eslint/ban-types return (cb) => { promise .then((data) => { // eslint-disable-next-line promise/no-callback-in-promise return cb(undefined, data); }) .catch((err) => { // eslint-disable-next-line promise/no-callback-in-promise cb(err); }); }; } /** * Converts a Promise to a service callback. * @param promise - The Promise of HttpOperationResponse to be converted to a service callback * @returns A function that takes the service callback (cb: ServiceCallback): void */ function promiseToServiceCallback(promise) { if (typeof promise.then !== "function") { throw new Error("The provided input is not a Promise."); } return (cb) => { promise .then((data) => { return process.nextTick(cb, undefined, data.parsedBody, data.request, data); }) .catch((err) => { process.nextTick(cb, err); }); }; } function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) { if (!Array.isArray(obj)) { obj = [obj]; } if (!xmlNamespaceKey || !xmlNamespace) { return { [elementName]: obj }; } const result = { [elementName]: obj }; result[XML_ATTRKEY] = { [xmlNamespaceKey]: xmlNamespace }; return result; } /** * Applies the properties on the prototype of sourceCtors to the prototype of targetCtor * @param targetCtor - The target object on which the properties need to be applied. * @param sourceCtors - An array of source objects from which the properties need to be taken. */ function applyMixins(targetCtorParam, sourceCtors) { const castTargetCtorParam = targetCtorParam; sourceCtors.forEach((sourceCtor) => { Object.getOwnPropertyNames(sourceCtor.prototype).forEach((name) => { castTargetCtorParam.prototype[name] = sourceCtor.prototype[name]; }); }); } const validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; /** * Indicates whether the given string is in ISO 8601 format. * @param value - The value to be validated for ISO 8601 duration format. * @returns `true` if valid, `false` otherwise. */ function isDuration(value) { return validateISODuration.test(value); } /** * Replace all of the instances of searchValue in value with the provided replaceValue. * @param value - The value to search and replace in. * @param searchValue - The value to search for in the value argument. * @param replaceValue - The value to replace searchValue with in the value argument. * @returns The value where each instance of searchValue was replaced with replacedValue. */ function replaceAll(value, searchValue, replaceValue) { return !value || !searchValue ? value : value.split(searchValue).join(replaceValue || ""); } /** * Determines whether the given entity is a basic/primitive type * (string, number, boolean, null, undefined). * @param value - Any entity * @returns true is it is primitive type, false otherwise. */ function isPrimitiveType(value) { return (typeof value !== "object" && typeof value !== "function") || value === null; } function getEnvironmentValue(name) { if (process.env[name]) { return process.env[name]; } else if (process.env[name.toLowerCase()]) { return process.env[name.toLowerCase()]; } return undefined; } /** * @internal * @returns true when input is an object type that is not null, Array, RegExp, or Date. */ function isObject(input) { return (typeof input === "object" && input !== null && !Array.isArray(input) && !(input instanceof RegExp) && !(input instanceof Date)); } // Copyright (c) Microsoft Corporation. // This file contains utility code to serialize and deserialize network operations according to `OperationSpec` objects generated by AutoRest.TypeScript from OpenAPI specifications. /** * Used to map raw response objects to final shapes. * Helps packing and unpacking Dates and other encoded types that are not intrinsic to JSON. * Also allows pulling values from headers, as well as inserting default values and constants. */ class Serializer { constructor( /** * The provided model mapper. */ modelMappers = {}, /** * Whether the contents are XML or not. */ isXML) { this.modelMappers = modelMappers; this.isXML = isXML; } /** * Validates constraints, if any. This function will throw if the provided value does not respect those constraints. * @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) => { throw new Error(`"${objectName}" with value "${value}" should satisfy the constraint "${constraintName}": ${constraintValue}.`); }; if (mapper.constraints && value != undefined) { const valueAsNumber = value; const { ExclusiveMaximum, ExclusiveMinimum, InclusiveMaximum, InclusiveMinimum, MaxItems, MaxLength, MinItems, MinLength, MultipleOf, Pattern, UniqueItems, } = mapper.constraints; if (ExclusiveMaximum != undefined && valueAsNumber >= ExclusiveMaximum) { failValidation("ExclusiveMaximum", ExclusiveMaximum); } if (ExclusiveMinimum != undefined && valueAsNumber <= ExclusiveMinimum) { failValidation("ExclusiveMinimum", ExclusiveMinimum); } if (InclusiveMaximum != undefined && valueAsNumber > InclusiveMaximum) { failValidation("InclusiveMaximum", InclusiveMaximum); } if (InclusiveMinimum != undefined && valueAsNumber < InclusiveMinimum) { failValidation("InclusiveMinimum", InclusiveMinimum); } const valueAsArray = value; if (MaxItems != undefined && valueAsArray.length > MaxItems) { failValidation("MaxItems", MaxItems); } if (MaxLength != undefined && valueAsArray.length > MaxLength) { failValidation("MaxLength", MaxLength); } if (MinItems != undefined && valueAsArray.length < MinItems) { failValidation("MinItems", MinItems); } if (MinLength != undefined && valueAsArray.length < MinLength) { failValidation("MinLength", MinLength); } if (MultipleOf != undefined && valueAsNumber % MultipleOf !== 0) { failValidation("MultipleOf", MultipleOf); } if (Pattern) { const pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern; if (typeof value !== "string" || value.match(pattern) === null) { failValidation("Pattern", Pattern); } } if (UniqueItems && valueAsArray.some((item, i, ar) => ar.indexOf(item) !== i)) { failValidation("UniqueItems", UniqueItems); } } } /** * Serialize the given object based on its metadata defined in the mapper. * * @param mapper - The mapper which defines the metadata of the serializable object. * @param object - A valid Javascript object to be serialized. * @param objectName - Name of the serialized object. * @param options - additional options to deserialization. * @returns A valid serialized Javascript object. */ serialize(mapper, object, objectName, options = {}) { var _a, _b, _c; const updatedOptions = { rootName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "", includeRoot: (_b = options.includeRoot) !== null && _b !== void 0 ? _b : false, xmlCharKey: (_c = options.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY, }; let payload = {}; const mapperType = mapper.type.name; if (!objectName) { objectName = mapper.serializedName; } if (mapperType.match(/^Sequence$/i) !== null) { payload = []; } if (mapper.isConstant) { object = mapper.defaultValue; } // This table of allowed values should help explain // the mapper.required and mapper.nullable properties. // X means "neither undefined or null are allowed". // || required // || true | false // nullable || ========================== // true || null | undefined/null // false || X | undefined // undefined || X | undefined/null const { required, nullable } = mapper; if (required && nullable && object === undefined) { throw new Error(`${objectName} cannot be undefined.`); } if (required && !nullable && object == undefined) { throw new Error(`${objectName} cannot be null or undefined.`); } if (!required && nullable === false && object === null) { throw new Error(`${objectName} cannot be null.`); } if (object == undefined) { payload = object; } else { if (mapperType.match(/^any$/i) !== null) { payload = object; } else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/i) !== null) { payload = serializeBasicTypes(mapperType, objectName, object); } else if (mapperType.match(/^Enum$/i) !== null) { const enumMapper = mapper; payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object); } else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/i) !== null) { payload = serializeDateTypes(mapperType, object, objectName); } else if (mapperType.match(/^ByteArray$/i) !== null) { payload = serializeByteArrayType(objectName, object); } else if (mapperType.match(/^Base64Url$/i) !== null) { payload = serializeBase64UrlType(objectName, object); } else if (mapperType.match(/^Sequence$/i) !== null) { payload = serializeSequenceType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); } else if (mapperType.match(/^Dictionary$/i) !== null) { payload = serializeDictionaryType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); } else if (mapperType.match(/^Composite$/i) !== null) { payload = serializeCompositeType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); } } return payload; } /** * Deserialize the given object based on its metadata defined in the mapper. * * @param mapper - The mapper which defines the metadata of the serializable object. * @param responseBody - A valid Javascript entity to be deserialized. * @param objectName - Name of the deserialized object. * @param options - Controls behavior of XML parser and builder. * @returns A valid deserialized Javascript object. */ deserialize(mapper, responseBody, objectName, options = {}) { var _a, _b, _c; const updatedOptions = { rootName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "", includeRoot: (_b = options.includeRoot) !== null && _b !== void 0 ? _b : false, xmlCharKey: (_c = options.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY, }; if (responseBody == undefined) { if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) { // Edge case for empty XML non-wrapped lists. xml2js can't distinguish // between the list being empty versus being missing, // so let's do the more user-friendly thing and return an empty list. responseBody = []; } // specifically check for undefined as default value can be a falsey value `0, "", false, null` if (mapper.defaultValue !== undefined) { responseBody = mapper.defaultValue; } return responseBody; } let payload; const mapperType = mapper.type.name; if (!objectName) { objectName = mapper.serializedName; } if (mapperType.match(/^Composite$/i) !== null) { payload = deserializeCompositeType(this, mapper, responseBody, objectName, updatedOptions); } else { if (this.isXML) { const xmlCharKey = updatedOptions.xmlCharKey; const castResponseBody = responseBody; /** * If the mapper specifies this as a non-composite type value but the responseBody contains * both header ("$" i.e., XML_ATTRKEY) and body ("#" i.e., XML_CHARKEY) properties, * then just reduce the responseBody value to the body ("#" i.e., XML_CHARKEY) property. */ if (castResponseBody[XML_ATTRKEY] != undefined && castResponseBody[xmlCharKey] != undefined) { responseBody = castResponseBody[xmlCharKey]; } } if (mapperType.match(/^Number$/i) !== null) { payload = parseFloat(responseBody); if (isNaN(payload)) { payload = responseBody; } } else if (mapperType.match(/^Boolean$/i) !== null) { if (responseBody === "true") { payload = true; } else if (responseBody === "false") { payload = false; } else { payload = responseBody; } } else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/i) !== null) { payload = responseBody; } else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/i) !== null) { payload = new Date(responseBody); } else if (mapperType.match(/^UnixTime$/i) !== null) { payload = unixTimeToDate(responseBody); } else if (mapperType.match(/^ByteArray$/i) !== null) { payload = decodeString(responseBody); } else if (mapperType.match(/^Base64Url$/i) !== null) { payload = base64UrlToByteArray(responseBody); } else if (mapperType.match(/^Sequence$/i) !== null) { payload = deserializeSequenceType(this, mapper, responseBody, objectName, updatedOptions); } else if (mapperType.match(/^Dictionary$/i) !== null) { payload = deserializeDictionaryType(this, mapper, responseBody, objectName, updatedOptions); } } if (mapper.isConstant) { payload = mapper.defaultValue; } return payload; } } function trimEnd(str, ch) { let len = str.length; while (len - 1 >= 0 && str[len - 1] === ch) { --len; } return str.substr(0, len); } function bufferToBase64Url(buffer) { if (!buffer) { return undefined; } if (!(buffer instanceof Uint8Array)) { throw new Error(`Please provide an input of type Uint8Array for converting to Base64Url.`); } // Uint8Array to Base64. const str = encodeByteArray(buffer); // Base64 to Base64Url. return trimEnd(str, "=").replace(/\+/g, "-").replace(/\//g, "_"); } function base64UrlToByteArray(str) { if (!str) { return undefined; } if (str && typeof str.valueOf() !== "string") { throw new Error("Please provide an input of type string for converting to Uint8Array"); } // Base64Url to Base64. str = str.replace(/-/g, "+").replace(/_/g, "/"); // Base64 to Uint8Array. return decodeString(str); } function splitSerializeName(prop) { const classes = []; let partialclass = ""; if (prop) { const subwords = prop.split("."); for (const item of subwords) { if (item.charAt(item.length - 1) === "\\") { partialclass += item.substr(0, item.length - 1) + "."; } else { partialclass += item; classes.push(partialclass); partialclass = ""; } } } return classes; } function dateToUnixTime(d) { if (!d) { return undefined; } if (typeof d.valueOf() === "string") { d = new Date(d); } return Math.floor(d.getTime() / 1000); } function unixTimeToDate(n) { if (!n) { return undefined; } return new Date(n * 1000); } function serializeBasicTypes(typeName, objectName, value) { if (value !== null && value !== undefined) { if (typeName.match(/^Number$/i) !== null) { if (typeof value !== "number") { throw new Error(`${objectName} with value ${value} must be of type number.`); } } else if (typeName.match(/^String$/i) !== null) { if (typeof value.valueOf() !== "string") { throw new Error(`${objectName} with value "${value}" must be of type string.`); } } else if (typeName.match(/^Uuid$/i) !== null) { if (!(typeof value.valueOf() === "string" && isValidUuid(value))) { throw new Error(`${objectName} with value "${value}" must be of type string and a valid uuid.`); } } else if (typeName.match(/^Boolean$/i) !== null) { if (typeof value !== "boolean") { throw new Error(`${objectName} with value ${value} must be of type boolean.`); } } else if (typeName.match(/^Stream$/i) !== null) { const objectType = typeof value; if (objectType !== "string" && objectType !== "function" && !(value instanceof ArrayBuffer) && !ArrayBuffer.isView(value) && !((typeof Blob === "function" || typeof Blob === "object") && value instanceof Blob)) { throw new Error(`${objectName} must be a string, Blob, ArrayBuffer, ArrayBufferView, or a function returning NodeJS.ReadableStream.`); } } } return value; } function serializeEnumType(objectName, allowedValues, value) { if (!allowedValues) { throw new Error(`Please provide a set of allowedValues to validate ${objectName} as an Enum Type.`); } const isPresent = allowedValues.some((item) => { if (typeof item.valueOf() === "string") { return item.toLowerCase() === value.toLowerCase(); } return item === value; }); if (!isPresent) { throw new Error(`${value} is not a valid value for ${objectName}. The valid values are: ${JSON.stringify(allowedValues)}.`); } return value; } function serializeByteArrayType(objectName, value) { let returnValue = ""; if (value != undefined) { if (!(value instanceof Uint8Array)) { throw new Error(`${objectName} must be of type Uint8Array.`); } returnValue = encodeByteArray(value); } return returnValue; } function serializeBase64UrlType(objectName, value) { let returnValue = ""; if (value != undefined) { if (!(value instanceof Uint8Array)) { throw new Error(`${objectName} must be of type Uint8Array.`); } returnValue = bufferToBase64Url(value) || ""; } return returnValue; } function serializeDateTypes(typeName, value, objectName) { if (value != undefined) { if (typeName.match(/^Date$/i) !== null) { if (!(value instanceof Date || (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`); } value = value instanceof Date ? value.toISOString().substring(0, 10) : new Date(value).toISOString().substring(0, 10); } else if (typeName.match(/^DateTime$/i) !== null) { if (!(value instanceof Date || (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`); } value = value instanceof Date ? value.toISOString() : new Date(value).toISOString(); } else if (typeName.match(/^DateTimeRfc1123$/i) !== null) { if (!(value instanceof Date || (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123 format.`); } value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString(); } else if (typeName.match(/^UnixTime$/i) !== null) { if (!(value instanceof Date || (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123/ISO8601 format ` + `for it to be serialized in UnixTime/Epoch format.`); } value = dateToUnixTime(value); } else if (typeName.match(/^TimeSpan$/i) !== null) { if (!isDuration(value)) { throw new Error(`${objectName} must be a string in ISO 8601 format. Instead was "${value}".`); } } } return value; } function serializeSequenceType(serializer, mapper, object, objectName, isXml, options) { if (!Array.isArray(object)) { throw new Error(`${objectName} must be of type Array.`); } const elementType = mapper.type.element; if (!elementType || typeof elementType !== "object") { throw new Error(`element" metadata for an Array must be defined in the ` + `mapper and it must of type "object" in ${objectName}.`); } const tempArray = []; for (let i = 0; i < object.length; i++) { const serializedValue = serializer.serialize(elementType, object[i], objectName, options); if (isXml && elementType.xmlNamespace) { const xmlnsKey = elementType.xmlNamespacePrefix ? `xmlns:${elementType.xmlNamespacePrefix}` : "xmlns"; if (elementType.type.name === "Composite") { tempArray[i] = Object.assign({}, serializedValue); tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace }; } else { tempArray[i] = {}; tempArray[i][options.xmlCharKey] = serializedValue; tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace }; } } else { tempArray[i] = serializedValue; } } return tempArray; } function serializeDictionaryType(serializer, mapper, object, objectName, isXml, options) { if (typeof object !== "object") { throw new Error(`${objectName} must be of type object.`); } const valueType = mapper.type.value; if (!valueType || typeof valueType !== "object") { throw new Error(`"value" metadata for a Dictionary must be defined in the ` + `mapper and it must of type "object" in ${objectName}.`); } const tempDictionary = {}; for (const key of Object.keys(object)) { const serializedValue = serializer.serialize(valueType, object[key], objectName, options); // If the element needs an XML namespace we need to add it within the $ property tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml, options); } // Add the namespace to the root element if needed if (isXml && mapper.xmlNamespace) { const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns"; const result = tempDictionary; result[XML_ATTRKEY] = { [xmlnsKey]: mapper.xmlNamespace }; return result; } return tempDictionary; } /** * Resolves the additionalProperties property from a referenced mapper. * @param serializer - The serializer containing the entire set of mappers. * @param mapper - The composite mapper to resolve. * @param objectName - Name of the object being serialized. */ function resolveAdditionalProperties(serializer, mapper, objectName) { const additionalProperties = mapper.type.additionalProperties; if (!additionalProperties && mapper.type.className) { const modelMapper = resolveReferencedMapper(serializer, mapper, objectName); return modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.additionalProperties; } return additionalProperties; } /** * Finds the mapper referenced by `className`. * @param serializer - The serializer containing the entire set of mappers * @param mapper - The composite mapper to resolve * @param objectName - Name of the object being serialized */ function resolveReferencedMapper(serializer, mapper, objectName) { const className = mapper.type.className; if (!className) { throw new Error(`Class name for model "${objectName}" is not provided in the mapper "${JSON.stringify(mapper, undefined, 2)}".`); } return serializer.modelMappers[className]; } /** * Resolves a composite mapper's modelProperties. * @param serializer - The serializer containing the entire set of mappers * @param mapper - The composite mapper to resolve */ function resolveModelProperties(serializer, mapper, objectName) { let modelProps = mapper.type.modelProperties; if (!modelProps) { const modelMapper = resolveReferencedMapper(serializer, mapper, objectName); if (!modelMapper) { throw new Error(`mapper() cannot be null or undefined for model "${mapper.type.className}".`); } modelProps = modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.modelProperties; if (!modelProps) { throw new Error(`modelProperties cannot be null or undefined in the ` + `mapper "${JSON.stringify(modelMapper)}" of type "${mapper.type.className}" for object "${objectName}".`); } } return modelProps; } function serializeCompositeType(serializer, mapper, object, objectName, isXml, options) { if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { mapper = getPolymorphicMapper(serializer, mapper, object, "clientName"); } if (object != undefined) { const payload = {}; const modelProps = resolveModelProperties(serializer, mapper, objectName); for (const key of Object.keys(modelProps)) { const propertyMapper = modelProps[key]; if (propertyMapper.readOnly) { continue; } let propName; let parentObject = payload; if (serializer.isXML) { if (propertyMapper.xmlIsWrapped) { propName = propertyMapper.xmlName; } else { propName = propertyMapper.xmlElementName || propertyMapper.xmlName; } } else { const paths = splitSerializeName(propertyMapper.serializedName); propName = paths.pop(); for (const pathName of paths) { const childObject = parentObject[pathName]; if (childObject == undefined && (object[key] != undefined || propertyMapper.defaultValue !== undefined)) { parentObject[pathName] = {}; } parentObject = parentObject[pathName]; } } if (parentObject != undefined) { if (isXml && mapper.xmlNamespace) { const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns"; parentObject[XML_ATTRKEY] = Object.assign(Object.assign({}, parentObject[XML_ATTRKEY]), { [xmlnsKey]: mapper.xmlNamespace }); } const propertyObjectName = propertyMapper.serializedName !== "" ? objectName + "." + propertyMapper.serializedName : objectName; let toSerialize = object[key]; const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); if (polymorphicDiscriminator && polymorphicDiscriminator.clientName === key && toSerialize == undefined) { toSerialize = mapper.serializedName; } const serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName, options); if (serializedValue !== undefined && propName != undefined) { const value = getXmlObjectValue(propertyMapper, serializedValue, isXml, options); if (isXml && propertyMapper.xmlIsAttribute) { // XML_ATTRKEY, i.e., $ is the key attributes are kept under in xml2js. // This keeps things simple while preventing name collision // with names in user documents. parentObject[XML_ATTRKEY] = parentObject[XML_ATTRKEY] || {}; parentObject[XML_ATTRKEY][propName] = serializedValue; } else if (isXml && propertyMapper.xmlIsWrapped) { parentObject[propName] = { [propertyMapper.xmlElementName]: value }; } else { parentObject[propName] = value; } } } } const additionalPropertiesMapper = resolveAdditionalProperties(serializer, mapper, objectName); if (additionalPropertiesMapper) { const propNames = Object.keys(modelProps); for (const clientPropName in object) { const isAdditionalProperty = propNames.every((pn) => pn !== clientPropName); if (isAdditionalProperty) { payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]', options); } } } return payload; } return object; } function getXmlObjectValue(propertyMapper, serializedValue, isXml, options) { if (!isXml || !propertyMapper.xmlNamespace) { return serializedValue; } const xmlnsKey = propertyMapper.xmlNamespacePrefix ? `xmlns:${propertyMapper.xmlNamespacePrefix}` : "xmlns"; const xmlNamespace = { [xmlnsKey]: propertyMapper.xmlNamespace }; if (["Composite"].includes(propertyMapper.type.name)) { if (serializedValue[XML_ATTRKEY]) { return serializedValue; } else { const result = Object.assign({}, serializedValue); result[XML_ATTRKEY] = xmlNamespace; return result; } } const result = {}; result[options.xmlCharKey] = serializedValue; result[XML_ATTRKEY] = xmlNamespace; return result; } function isSpecialXmlProperty(propertyName, options) { return [XML_ATTRKEY, options.xmlCharKey].includes(propertyName); } function deserializeCompositeType(serializer, mapper, responseBody, objectName, options) { 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"); } const modelProps = resolveModelProperties(serializer, mapper, objectName); let instance = {}; const handledPropertyNames = []; for (const key of Object.keys(modelProps)) { const propertyMapper = modelProps[key]; const paths = splitSerializeName(modelProps[key].serializedName); handledPropertyNames.push(paths[0]); const { serializedName, xmlName, xmlElementName } = propertyMapper; let propertyObjectName = objectName; if (serializedName !== "" && serializedName !== undefined) { propertyObjectName = objectName + "." + serializedName; } const headerCollectionPrefix = propertyMapper.headerCollectionPrefix; if (headerCollectionPrefix) { const dictionary = {}; for (const headerKey of Object.keys(responseBody)) { if (headerKey.startsWith(headerCollectionPrefix)) { dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName, options); } handledPropertyNames.push(headerKey); } instance[key] = dictionary; } else if (serializer.isXML) { 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) { /* a list of wrapped by For the xml example below ... ... the responseBody has { Cors: { CorsRule: [{...}, {...}] } } xmlName is "Cors" and xmlElementName is"CorsRule". */ const wrapped = responseBody[xmlName]; 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); } } } else { // deserialize the property if it is present in the provided responseBody instance let propertyInstance; let res = responseBody; // traversing the object step by step. for (const item of paths) { if (!res) break; res = res[item]; } propertyInstance = res; const polymorphicDiscriminator = mapper.type.polymorphicDiscriminator; // checking that the model property name (key)(ex: "fishtype") and the // clientName of the polymorphicDiscriminator {metadata} (ex: "fishtype") // instead of the serializedName of the polymorphicDiscriminator (ex: "fish.type") // is a better approach. The generator is not consistent with escaping '\.' in the // serializedName of the property (ex: "fish\.type") that is marked as polymorphic discriminator // and the serializedName of the metadata polymorphicDiscriminator (ex: "fish.type"). However, // the clientName transformation of the polymorphicDiscriminator (ex: "fishtype") and // the transformation of model property name (ex: "fishtype") is done consistently. // Hence, it is a safer bet to rely on the clientName of the polymorphicDiscriminator. if (polymorphicDiscriminator && key === polymorphicDiscriminator.clientName && propertyInstance == undefined) { propertyInstance = mapper.serializedName; } let serializedValue; // paging if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") { propertyInstance = responseBody[key]; const arrayInstance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); // Copy over any properties that have already been added into the instance, where they do // not exist on the newly de-serialized array for (const [k, v] of Object.entries(instance)) { if (!Object.prototype.hasOwnProperty.call(arrayInstance, k)) { arrayInstance[k] = v; } } instance = arrayInstance; } else if (propertyInstance !== undefined || propertyMapper.defaultValue !== undefined) { serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); instance[key] = serializedValue; } } } const additionalPropertiesMapper = mapper.type.additionalProperties; if (additionalPropertiesMapper) { const isAdditionalProperty = (responsePropName) => { for (const clientPropName in modelProps) { const paths = splitSerializeName(modelProps[clientPropName].serializedName); if (paths[0] === responsePropName) { return false; } } return true; }; for (const responsePropName in responseBody) { if (isAdditionalProperty(responsePropName)) { instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]', options); } } } else if (responseBody) { for (const key of Object.keys(responseBody)) { if (instance[key] === undefined && !handledPropertyNames.includes(key) && !isSpecialXmlProperty(key, options)) { instance[key] = responseBody[key]; } } } return instance; } function deserializeDictionaryType(serializer, mapper, responseBody, objectName, options) { const value = mapper.type.value; if (!value || typeof value !== "object") { throw new Error(`"value" metadata for a Dictionary must be defined in the ` + `mapper and it must of type "object" in ${objectName}`); } if (responseBody) { const tempDictionary = {}; for (const key of Object.keys(responseBody)) { tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName, options); } return tempDictionary; } return responseBody; } function deserializeSequenceType(serializer, mapper, responseBody, objectName, options) { const element = mapper.type.element; if (!element || typeof element !== "object") { throw new Error(`element" metadata for an Array must be defined in the ` + `mapper and it must of type "object" in ${objectName}`); } if (responseBody) { if (!Array.isArray(responseBody)) { // xml2js will interpret a single element array as just the element, so force it to be an array responseBody = [responseBody]; } const tempArray = []; for (let i = 0; i < responseBody.length; i++) { tempArray[i] = serializer.deserialize(element, responseBody[i], `${objectName}[${i}]`, options); } return tempArray; } return responseBody; } function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) { const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); if (polymorphicDiscriminator) { const discriminatorName = polymorphicDiscriminator[polymorphicPropertyName]; if (discriminatorName != undefined) { const discriminatorValue = object[discriminatorName]; if (discriminatorValue != undefined) { const typeName = mapper.type.uberParent || mapper.type.className; const indexDiscriminator = discriminatorValue === typeName ? discriminatorValue : typeName + "." + discriminatorValue; const polymorphicMapper = serializer.modelMappers.discriminators[indexDiscriminator]; if (polymorphicMapper) { mapper = polymorphicMapper; } } } } return mapper; } function getPolymorphicDiscriminatorRecursively(serializer, mapper) { return (mapper.type.polymorphicDiscriminator || getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) || getPolymorphicDiscriminatorSafely(serializer, mapper.type.className)); } function getPolymorphicDiscriminatorSafely(serializer, typeName) { return (typeName && serializer.modelMappers[typeName] && serializer.modelMappers[typeName].type.polymorphicDiscriminator); } /** * Utility function that serializes an object that might contain binary information into a plain object, array or a string. */ function serializeObject(toSerialize) { const castToSerialize = toSerialize; if (toSerialize == undefined) return undefined; if (toSerialize instanceof Uint8Array) { toSerialize = encodeByteArray(toSerialize); return toSerialize; } else if (toSerialize instanceof Date) { return toSerialize.toISOString(); } else if (Array.isArray(toSerialize)) { const array = []; for (let i = 0; i < toSerialize.length; i++) { array.push(serializeObject(toSerialize[i])); } return array; } else if (typeof toSerialize === "object") { const dictionary = {}; for (const property in toSerialize) { dictionary[property] = serializeObject(castToSerialize[property]); } return dictionary; } return toSerialize; } /** * Utility function to create a K:V from a list of strings */ function strEnum(o) { const result = {}; for (const key of o) { result[key] = key; } return result; } /** * String enum containing the string types of property mappers. */ // eslint-disable-next-line @typescript-eslint/no-redeclare const MapperType = strEnum([ "Base64Url", "Boolean", "ByteArray", "Composite", "Date", "DateTime", "DateTimeRfc1123", "Dictionary", "Enum", "Number", "Object", "Sequence", "String", "Stream", "TimeSpan", "UnixTime", ]); // Copyright (c) Microsoft Corporation. function isWebResourceLike(object) { if (object && typeof object === "object") { const castObject = object; if (typeof castObject.url === "string" && typeof castObject.method === "string" && typeof castObject.headers === "object" && isHttpHeadersLike(castObject.headers) && typeof castObject.validateRequestProperties === "function" && typeof castObject.prepare === "function" && typeof castObject.clone === "function") { return true; } } return false; } /** * Creates a new WebResource object. * * This class provides an abstraction over a REST call by being library / implementation agnostic and wrapping the necessary * properties to initiate a request. */ class WebResource { constructor(url, method, body, query, headers, streamResponseBody, withCredentials, abortSignal, timeout, onUploadProgress, onDownloadProgress, proxySettings, keepAlive, decompressResponse, streamResponseStatusCodes) { this.streamResponseBody = streamResponseBody; this.streamResponseStatusCodes = streamResponseStatusCodes; this.url = url || ""; this.method = method || "GET"; this.headers = isHttpHeadersLike(headers) ? headers : new HttpHeaders(headers); this.body = body; this.query = query; this.formData = undefined; this.withCredentials = withCredentials || false; this.abortSignal = abortSignal; this.timeout = timeout || 0; this.onUploadProgress = onUploadProgress; this.onDownloadProgress = onDownloadProgress; this.proxySettings = proxySettings; this.keepAlive = keepAlive; this.decompressResponse = decompressResponse; this.requestId = this.headers.get("x-ms-client-request-id") || generateUuid(); } /** * Validates that the required properties such as method, url, headers["Content-Type"], * headers["accept-language"] are defined. It will throw an error if one of the above * mentioned properties are not defined. */ validateRequestProperties() { if (!this.method) { throw new Error("WebResource.method is required."); } if (!this.url) { throw new Error("WebResource.url is required."); } } /** * Prepares the request. * @param options - Options to provide for preparing the request. * @returns Returns the prepared WebResource (HTTP Request) object that needs to be given to the request pipeline. */ prepare(options) { if (!options) { throw new Error("options object is required"); } if (options.method === undefined || options.method === null || typeof options.method.valueOf() !== "string") { throw new Error("options.method must be a string."); } if (options.url && options.pathTemplate) { throw new Error("options.url and options.pathTemplate are mutually exclusive. Please provide exactly one of them."); } if ((options.pathTemplate === undefined || options.pathTemplate === null || typeof options.pathTemplate.valueOf() !== "string") && (options.url === undefined || options.url === null || typeof options.url.valueOf() !== "string")) { throw new Error("Please provide exactly one of options.pathTemplate or options.url."); } // set the url if it is provided. if (options.url) { if (typeof options.url !== "string") { throw new Error('options.url must be of type "string".'); } this.url = options.url; } // set the method if (options.method) { const validMethods = ["GET", "PUT", "HEAD", "DELETE", "OPTIONS", "POST", "PATCH", "TRACE"]; if (validMethods.indexOf(options.method.toUpperCase()) === -1) { throw new Error('The provided method "' + options.method + '" is invalid. Supported HTTP methods are: ' + JSON.stringify(validMethods)); } } this.method = options.method.toUpperCase(); // construct the url if path template is provided if (options.pathTemplate) { const { pathTemplate, pathParameters } = options; if (typeof pathTemplate !== "string") { throw new Error('options.pathTemplate must be of type "string".'); } if (!options.baseUrl) { options.baseUrl = "https://management.azure.com"; } const baseUrl = options.baseUrl; let url = baseUrl + (baseUrl.endsWith("/") ? "" : "/") + (pathTemplate.startsWith("/") ? pathTemplate.slice(1) : pathTemplate); const segments = url.match(/({[\w-]*\s*[\w-]*})/gi); if (segments && segments.length) { if (!pathParameters) { throw new Error(`pathTemplate: ${pathTemplate} has been provided. Hence, options.pathParameters must also be provided.`); } segments.forEach(function (item) { const pathParamName = item.slice(1, -1); const pathParam = pathParameters[pathParamName]; if (pathParam === null || pathParam === undefined || !(typeof pathParam === "string" || typeof pathParam === "object")) { const stringifiedPathParameters = JSON.stringify(pathParameters, undefined, 2); throw new Error(`pathTemplate: ${pathTemplate} contains the path parameter ${pathParamName}` + ` however, it is not present in parameters: ${stringifiedPathParameters}.` + `The value of the path parameter can either be a "string" of the form { ${pathParamName}: "some sample value" } or ` + `it can be an "object" of the form { "${pathParamName}": { value: "some sample value", skipUrlEncoding: true } }.`); } if (typeof pathParam.valueOf() === "string") { url = url.replace(item, encodeURIComponent(pathParam)); } if (typeof pathParam.valueOf() === "object") { if (!pathParam.value) { throw new Error(`options.pathParameters[${pathParamName}] is of type "object" but it does not contain a "value" property.`); } if (pathParam.skipUrlEncoding) { url = url.replace(item, pathParam.value); } else { url = url.replace(item, encodeURIComponent(pathParam.value)); } } }); } this.url = url; } // append query parameters to the url if they are provided. They can be provided with pathTemplate or url option. if (options.queryParameters) { const queryParameters = options.queryParameters; if (typeof queryParameters !== "object") { throw new Error(`options.queryParameters must be of type object. It should be a JSON object ` + `of "query-parameter-name" as the key and the "query-parameter-value" as the value. ` + `The "query-parameter-value" may be fo type "string" or an "object" of the form { value: "query-parameter-value", skipUrlEncoding: true }.`); } // append question mark if it is not present in the url if (this.url && this.url.indexOf("?") === -1) { this.url += "?"; } // construct queryString const queryParams = []; // We need to populate this.query as a dictionary if the request is being used for Sway's validateRequest(). this.query = {}; for (const queryParamName in queryParameters) { const queryParam = queryParameters[queryParamName]; if (queryParam) { if (typeof queryParam === "string") { queryParams.push(queryParamName + "=" + encodeURIComponent(queryParam)); this.query[queryParamName] = encodeURIComponent(queryParam); } else if (typeof queryParam === "object") { if (!queryParam.value) { throw new Error(`options.queryParameters[${queryParamName}] is of type "object" but it does not contain a "value" property.`); } if (queryParam.skipUrlEncoding) { queryParams.push(queryParamName + "=" + queryParam.value); this.query[queryParamName] = queryParam.value; } else { queryParams.push(queryParamName + "=" + encodeURIComponent(queryParam.value)); this.query[queryParamName] = encodeURIComponent(queryParam.value); } } } } // end-of-for // append the queryString this.url += queryParams.join("&"); } // add headers to the request if they are provided if (options.headers) { const headers = options.headers; for (const headerName of Object.keys(options.headers)) { this.headers.set(headerName, headers[headerName]); } } // ensure accept-language is set correctly if (!this.headers.get("accept-language")) { this.headers.set("accept-language", "en-US"); } // ensure the request-id is set correctly if (!this.headers.get("x-ms-client-request-id") && !options.disableClientRequestId) { this.headers.set("x-ms-client-request-id", this.requestId); } // default if (!this.headers.get("Content-Type")) { this.headers.set("Content-Type", "application/json; charset=utf-8"); } // set the request body. request.js automatically sets the Content-Length request header, so we need not set it explicitly this.body = options.body; if (options.body !== undefined && options.body !== null) { // body as a stream special case. set the body as-is and check for some special request headers specific to sending a stream. if (options.bodyIsStream) { if (!this.headers.get("Transfer-Encoding")) { this.headers.set("Transfer-Encoding", "chunked"); } if (this.headers.get("Content-Type") !== "application/octet-stream") { this.headers.set("Content-Type", "application/octet-stream"); } } else { if (options.serializationMapper) { this.body = new Serializer(options.mappers).serialize(options.serializationMapper, options.body, "requestBody"); } if (!options.disableJsonStringifyOnBody) { this.body = JSON.stringify(options.body); } } } if (options.spanOptions) { this.spanOptions = options.spanOptions; } if (options.tracingContext) { this.tracingContext = options.tracingContext; } this.abortSignal = options.abortSignal; this.onDownloadProgress = options.onDownloadProgress; this.onUploadProgress = options.onUploadProgress; return this; } /** * Clone this WebResource HTTP request object. * @returns The clone of this WebResource HTTP request object. */ clone() { const result = new WebResource(this.url, this.method, this.body, this.query, this.headers && this.headers.clone(), this.streamResponseBody, this.withCredentials, this.abortSignal, this.timeout, this.onUploadProgress, this.onDownloadProgress, this.proxySettings, this.keepAlive, this.decompressResponse, this.streamResponseStatusCodes); if (this.formData) { result.formData = this.formData; } if (this.operationSpec) { result.operationSpec = this.operationSpec; } if (this.shouldDeserialize) { result.shouldDeserialize = this.shouldDeserialize; } if (this.operationResponseGetter) { result.operationResponseGetter = this.operationResponseGetter; } return result; } } // Copyright (c) Microsoft Corporation. /** * A class that handles the query portion of a URLBuilder. */ class URLQuery { constructor() { this._rawQuery = {}; } /** * Get whether or not there any query parameters in this URLQuery. */ any() { return Object.keys(this._rawQuery).length > 0; } /** * Get the keys of the query string. */ keys() { return Object.keys(this._rawQuery); } /** * Set a query parameter with the provided name and value. If the parameterValue is undefined or * empty, then this will attempt to remove an existing query parameter with the provided * parameterName. */ set(parameterName, parameterValue) { const caseParameterValue = parameterValue; if (parameterName) { if (caseParameterValue !== undefined && caseParameterValue !== null) { const newValue = Array.isArray(caseParameterValue) ? caseParameterValue : caseParameterValue.toString(); this._rawQuery[parameterName] = newValue; } else { delete this._rawQuery[parameterName]; } } } /** * Get the value of the query parameter with the provided name. If no parameter exists with the * provided parameter name, then undefined will be returned. */ get(parameterName) { return parameterName ? this._rawQuery[parameterName] : undefined; } /** * Get the string representation of this query. The return value will not start with a "?". */ toString() { let result = ""; for (const parameterName in this._rawQuery) { if (result) { result += "&"; } const parameterValue = this._rawQuery[parameterName]; if (Array.isArray(parameterValue)) { const parameterStrings = []; for (const parameterValueElement of parameterValue) { parameterStrings.push(`${parameterName}=${parameterValueElement}`); } result += parameterStrings.join("&"); } else { result += `${parameterName}=${parameterValue}`; } } return result; } /** * Parse a URLQuery from the provided text. */ static parse(text) { const result = new URLQuery(); if (text) { if (text.startsWith("?")) { text = text.substring(1); } let currentState = "ParameterName"; let parameterName = ""; let parameterValue = ""; for (let i = 0; i < text.length; ++i) { const currentCharacter = text[i]; switch (currentState) { case "ParameterName": switch (currentCharacter) { case "=": currentState = "ParameterValue"; break; case "&": parameterName = ""; parameterValue = ""; break; default: parameterName += currentCharacter; break; } break; case "ParameterValue": switch (currentCharacter) { case "&": result.set(parameterName, parameterValue); parameterName = ""; parameterValue = ""; currentState = "ParameterName"; break; default: parameterValue += currentCharacter; break; } break; default: throw new Error("Unrecognized URLQuery parse state: " + currentState); } } if (currentState === "ParameterValue") { result.set(parameterName, parameterValue); } } return result; } } /** * A class that handles creating, modifying, and parsing URLs. */ class URLBuilder { /** * Set the scheme/protocol for this URL. If the provided scheme contains other parts of a URL * (such as a host, port, path, or query), those parts will be added to this URL as well. */ setScheme(scheme) { if (!scheme) { this._scheme = undefined; } else { this.set(scheme, "SCHEME"); } } /** * Get the scheme that has been set in this URL. */ getScheme() { return this._scheme; } /** * Set the host for this URL. If the provided host contains other parts of a URL (such as a * port, path, or query), those parts will be added to this URL as well. */ setHost(host) { if (!host) { this._host = undefined; } else { this.set(host, "SCHEME_OR_HOST"); } } /** * Get the host that has been set in this URL. */ getHost() { return this._host; } /** * Set the port for this URL. If the provided port contains other parts of a URL (such as a * path or query), those parts will be added to this URL as well. */ setPort(port) { if (port === undefined || port === null || port === "") { this._port = undefined; } else { this.set(port.toString(), "PORT"); } } /** * Get the port that has been set in this URL. */ getPort() { return this._port; } /** * Set the path for this URL. If the provided path contains a query, then it will be added to * this URL as well. */ setPath(path) { if (!path) { this._path = undefined; } else { const schemeIndex = path.indexOf("://"); if (schemeIndex !== -1) { const schemeStart = path.lastIndexOf("/", schemeIndex); // Make sure to only grab the URL part of the path before setting the state back to SCHEME // this will handle cases such as "/a/b/c/https://microsoft.com" => "https://microsoft.com" this.set(schemeStart === -1 ? path : path.substr(schemeStart + 1), "SCHEME"); } else { this.set(path, "PATH"); } } } /** * Append the provided path to this URL's existing path. If the provided path contains a query, * then it will be added to this URL as well. */ appendPath(path) { if (path) { let currentPath = this.getPath(); if (currentPath) { if (!currentPath.endsWith("/")) { currentPath += "/"; } if (path.startsWith("/")) { path = path.substring(1); } path = currentPath + path; } this.set(path, "PATH"); } } /** * Get the path that has been set in this URL. */ getPath() { return this._path; } /** * Set the query in this URL. */ setQuery(query) { if (!query) { this._query = undefined; } else { this._query = URLQuery.parse(query); } } /** * Set a query parameter with the provided name and value in this URL's query. If the provided * query parameter value is undefined or empty, then the query parameter will be removed if it * existed. */ setQueryParameter(queryParameterName, queryParameterValue) { if (queryParameterName) { if (!this._query) { this._query = new URLQuery(); } this._query.set(queryParameterName, queryParameterValue); } } /** * Get the value of the query parameter with the provided query parameter name. If no query * parameter exists with the provided name, then undefined will be returned. */ getQueryParameterValue(queryParameterName) { return this._query ? this._query.get(queryParameterName) : undefined; } /** * Get the query in this URL. */ getQuery() { return this._query ? this._query.toString() : undefined; } /** * Set the parts of this URL by parsing the provided text using the provided startState. */ set(text, startState) { const tokenizer = new URLTokenizer(text, startState); while (tokenizer.next()) { const token = tokenizer.current(); let tokenPath; if (token) { switch (token.type) { case "SCHEME": this._scheme = token.text || undefined; break; case "HOST": this._host = token.text || undefined; break; case "PORT": this._port = token.text || undefined; break; case "PATH": tokenPath = token.text || undefined; if (!this._path || this._path === "/" || tokenPath !== "/") { this._path = tokenPath; } break; case "QUERY": this._query = URLQuery.parse(token.text); break; default: throw new Error(`Unrecognized URLTokenType: ${token.type}`); } } } } /** * Serializes the URL as a string. * @returns the URL as a string. */ toString() { let result = ""; if (this._scheme) { result += `${this._scheme}://`; } if (this._host) { result += this._host; } if (this._port) { result += `:${this._port}`; } if (this._path) { if (!this._path.startsWith("/")) { result += "/"; } result += this._path; } if (this._query && this._query.any()) { result += `?${this._query.toString()}`; } return result; } /** * If the provided searchValue is found in this URLBuilder, then replace it with the provided * replaceValue. */ replaceAll(searchValue, replaceValue) { if (searchValue) { this.setScheme(replaceAll(this.getScheme(), searchValue, replaceValue)); this.setHost(replaceAll(this.getHost(), searchValue, replaceValue)); this.setPort(replaceAll(this.getPort(), searchValue, replaceValue)); this.setPath(replaceAll(this.getPath(), searchValue, replaceValue)); this.setQuery(replaceAll(this.getQuery(), searchValue, replaceValue)); } } /** * Parses a given string URL into a new {@link URLBuilder}. */ static parse(text) { const result = new URLBuilder(); result.set(text, "SCHEME_OR_HOST"); return result; } } class URLToken { constructor(text, type) { this.text = text; this.type = type; } static scheme(text) { return new URLToken(text, "SCHEME"); } static host(text) { return new URLToken(text, "HOST"); } static port(text) { return new URLToken(text, "PORT"); } static path(text) { return new URLToken(text, "PATH"); } static query(text) { return new URLToken(text, "QUERY"); } } /** * Get whether or not the provided character (single character string) is an alphanumeric (letter or * digit) character. */ function isAlphaNumericCharacter(character) { const characterCode = character.charCodeAt(0); return ((48 /* '0' */ <= characterCode && characterCode <= 57) /* '9' */ || (65 /* 'A' */ <= characterCode && characterCode <= 90) /* 'Z' */ || (97 /* 'a' */ <= characterCode && characterCode <= 122) /* 'z' */); } /** * A class that tokenizes URL strings. */ class URLTokenizer { constructor(_text, state) { this._text = _text; this._textLength = _text ? _text.length : 0; this._currentState = state !== undefined && state !== null ? state : "SCHEME_OR_HOST"; this._currentIndex = 0; } /** * Get the current URLToken this URLTokenizer is pointing at, or undefined if the URLTokenizer * hasn't started or has finished tokenizing. */ current() { return this._currentToken; } /** * Advance to the next URLToken and return whether or not a URLToken was found. */ next() { if (!hasCurrentCharacter(this)) { this._currentToken = undefined; } else { switch (this._currentState) { case "SCHEME": nextScheme(this); break; case "SCHEME_OR_HOST": nextSchemeOrHost(this); break; case "HOST": nextHost(this); break; case "PORT": nextPort(this); break; case "PATH": nextPath(this); break; case "QUERY": nextQuery(this); break; default: throw new Error(`Unrecognized URLTokenizerState: ${this._currentState}`); } } return !!this._currentToken; } } /** * Read the remaining characters from this Tokenizer's character stream. */ function readRemaining(tokenizer) { let result = ""; if (tokenizer._currentIndex < tokenizer._textLength) { result = tokenizer._text.substring(tokenizer._currentIndex); tokenizer._currentIndex = tokenizer._textLength; } return result; } /** * Whether or not this URLTokenizer has a current character. */ function hasCurrentCharacter(tokenizer) { return tokenizer._currentIndex < tokenizer._textLength; } /** * Get the character in the text string at the current index. */ function getCurrentCharacter(tokenizer) { return tokenizer._text[tokenizer._currentIndex]; } /** * Advance to the character in text that is "step" characters ahead. If no step value is provided, * then step will default to 1. */ function nextCharacter(tokenizer, step) { if (hasCurrentCharacter(tokenizer)) { if (!step) { step = 1; } tokenizer._currentIndex += step; } } /** * Starting with the current character, peek "charactersToPeek" number of characters ahead in this * Tokenizer's stream of characters. */ function peekCharacters(tokenizer, charactersToPeek) { let endIndex = tokenizer._currentIndex + charactersToPeek; if (tokenizer._textLength < endIndex) { endIndex = tokenizer._textLength; } return tokenizer._text.substring(tokenizer._currentIndex, endIndex); } /** * Read characters from this Tokenizer until the end of the stream or until the provided condition * is false when provided the current character. */ function readWhile(tokenizer, condition) { let result = ""; while (hasCurrentCharacter(tokenizer)) { const currentCharacter = getCurrentCharacter(tokenizer); if (!condition(currentCharacter)) { break; } else { result += currentCharacter; nextCharacter(tokenizer); } } return result; } /** * Read characters from this Tokenizer until a non-alphanumeric character or the end of the * character stream is reached. */ function readWhileLetterOrDigit(tokenizer) { return readWhile(tokenizer, (character) => isAlphaNumericCharacter(character)); } /** * Read characters from this Tokenizer until one of the provided terminating characters is read or * the end of the character stream is reached. */ function readUntilCharacter(tokenizer, ...terminatingCharacters) { return readWhile(tokenizer, (character) => terminatingCharacters.indexOf(character) === -1); } function nextScheme(tokenizer) { const scheme = readWhileLetterOrDigit(tokenizer); tokenizer._currentToken = URLToken.scheme(scheme); if (!hasCurrentCharacter(tokenizer)) { tokenizer._currentState = "DONE"; } else { tokenizer._currentState = "HOST"; } } function nextSchemeOrHost(tokenizer) { const schemeOrHost = readUntilCharacter(tokenizer, ":", "/", "?"); if (!hasCurrentCharacter(tokenizer)) { tokenizer._currentToken = URLToken.host(schemeOrHost); tokenizer._currentState = "DONE"; } else if (getCurrentCharacter(tokenizer) === ":") { if (peekCharacters(tokenizer, 3) === "://") { tokenizer._currentToken = URLToken.scheme(schemeOrHost); tokenizer._currentState = "HOST"; } else { tokenizer._currentToken = URLToken.host(schemeOrHost); tokenizer._currentState = "PORT"; } } else { tokenizer._currentToken = URLToken.host(schemeOrHost); if (getCurrentCharacter(tokenizer) === "/") { tokenizer._currentState = "PATH"; } else { tokenizer._currentState = "QUERY"; } } } function nextHost(tokenizer) { if (peekCharacters(tokenizer, 3) === "://") { nextCharacter(tokenizer, 3); } const host = readUntilCharacter(tokenizer, ":", "/", "?"); tokenizer._currentToken = URLToken.host(host); if (!hasCurrentCharacter(tokenizer)) { tokenizer._currentState = "DONE"; } else if (getCurrentCharacter(tokenizer) === ":") { tokenizer._currentState = "PORT"; } else if (getCurrentCharacter(tokenizer) === "/") { tokenizer._currentState = "PATH"; } else { tokenizer._currentState = "QUERY"; } } function nextPort(tokenizer) { if (getCurrentCharacter(tokenizer) === ":") { nextCharacter(tokenizer); } const port = readUntilCharacter(tokenizer, "/", "?"); tokenizer._currentToken = URLToken.port(port); if (!hasCurrentCharacter(tokenizer)) { tokenizer._currentState = "DONE"; } else if (getCurrentCharacter(tokenizer) === "/") { tokenizer._currentState = "PATH"; } else { tokenizer._currentState = "QUERY"; } } function nextPath(tokenizer) { const path = readUntilCharacter(tokenizer, "?"); tokenizer._currentToken = URLToken.path(path); if (!hasCurrentCharacter(tokenizer)) { tokenizer._currentState = "DONE"; } else { tokenizer._currentState = "QUERY"; } } function nextQuery(tokenizer) { if (getCurrentCharacter(tokenizer) === "?") { nextCharacter(tokenizer); } const query = readRemaining(tokenizer); tokenizer._currentToken = URLToken.query(query); tokenizer._currentState = "DONE"; } // Copyright (c) Microsoft Corporation. function createProxyAgent(requestUrl, proxySettings, headers) { const host = URLBuilder.parse(proxySettings.host).getHost(); if (!host) { throw new Error("Expecting a non-empty host in proxy settings."); } if (!isValidPort(proxySettings.port)) { throw new Error("Expecting a valid port number in the range of [0, 65535] in proxy settings."); } const tunnelOptions = { proxy: { host: host, port: proxySettings.port, headers: (headers && headers.rawHeaders()) || {}, }, }; if (proxySettings.username && proxySettings.password) { tunnelOptions.proxy.proxyAuth = `${proxySettings.username}:${proxySettings.password}`; } else if (proxySettings.username) { tunnelOptions.proxy.proxyAuth = `${proxySettings.username}`; } const isRequestHttps = isUrlHttps(requestUrl); const isProxyHttps = isUrlHttps(proxySettings.host); const proxyAgent = { isHttps: isRequestHttps, agent: createTunnel(isRequestHttps, isProxyHttps, tunnelOptions), }; return proxyAgent; } function isUrlHttps(url) { const urlScheme = URLBuilder.parse(url).getScheme() || ""; return urlScheme.toLowerCase() === "https"; } function createTunnel(isRequestHttps, isProxyHttps, tunnelOptions) { if (isRequestHttps && isProxyHttps) { return tunnel__namespace.httpsOverHttps(tunnelOptions); } else if (isRequestHttps && !isProxyHttps) { return tunnel__namespace.httpsOverHttp(tunnelOptions); } else if (!isRequestHttps && isProxyHttps) { return tunnel__namespace.httpOverHttps(tunnelOptions); } else { return tunnel__namespace.httpOverHttp(tunnelOptions); } } function isValidPort(port) { // any port in 0-65535 range is valid (RFC 793) even though almost all implementations // will reserve 0 for a specific purpose, and a range of numbers for ephemeral ports return 0 <= port && port <= 65535; } // Copyright (c) Microsoft Corporation. const RedactedString = "REDACTED"; const defaultAllowedHeaderNames = [ "x-ms-client-request-id", "x-ms-return-client-request-id", "x-ms-useragent", "x-ms-correlation-request-id", "x-ms-request-id", "client-request-id", "ms-cv", "return-client-request-id", "traceparent", "Access-Control-Allow-Credentials", "Access-Control-Allow-Headers", "Access-Control-Allow-Methods", "Access-Control-Allow-Origin", "Access-Control-Expose-Headers", "Access-Control-Max-Age", "Access-Control-Request-Headers", "Access-Control-Request-Method", "Origin", "Accept", "Accept-Encoding", "Cache-Control", "Connection", "Content-Length", "Content-Type", "Date", "ETag", "Expires", "If-Match", "If-Modified-Since", "If-None-Match", "If-Unmodified-Since", "Last-Modified", "Pragma", "Request-Id", "Retry-After", "Server", "Transfer-Encoding", "User-Agent", "WWW-Authenticate", ]; const defaultAllowedQueryParameters = ["api-version"]; class Sanitizer { constructor({ allowedHeaderNames = [], allowedQueryParameters = [] } = {}) { allowedHeaderNames = Array.isArray(allowedHeaderNames) ? defaultAllowedHeaderNames.concat(allowedHeaderNames) : defaultAllowedHeaderNames; allowedQueryParameters = Array.isArray(allowedQueryParameters) ? defaultAllowedQueryParameters.concat(allowedQueryParameters) : defaultAllowedQueryParameters; this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase())); this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase())); } sanitize(obj) { const seen = new Set(); return JSON.stringify(obj, (key, value) => { // Ensure Errors include their interesting non-enumerable members if (value instanceof Error) { return Object.assign(Object.assign({}, value), { name: value.name, message: value.message }); } if (key === "_headersMap") { return this.sanitizeHeaders(value); } else if (key === "url") { return this.sanitizeUrl(value); } else if (key === "query") { return this.sanitizeQuery(value); } else if (key === "body") { // Don't log the request body return undefined; } else if (key === "response") { // Don't log response again return undefined; } else if (key === "operationSpec") { // When using sendOperationRequest, the request carries a massive // field with the autorest spec. No need to log it. return undefined; } else if (Array.isArray(value) || isObject(value)) { if (seen.has(value)) { return "[Circular]"; } seen.add(value); } return value; }, 2); } sanitizeHeaders(value) { return this.sanitizeObject(value, this.allowedHeaderNames, (v, k) => v[k].value); } sanitizeQuery(value) { return this.sanitizeObject(value, this.allowedQueryParameters, (v, k) => v[k]); } sanitizeObject(value, allowedKeys, accessor) { if (typeof value !== "object" || value === null) { return value; } const sanitized = {}; for (const k of Object.keys(value)) { if (allowedKeys.has(k.toLowerCase())) { sanitized[k] = accessor(value, k); } else { sanitized[k] = RedactedString; } } return sanitized; } sanitizeUrl(value) { if (typeof value !== "string" || value === null) { return value; } const urlBuilder = URLBuilder.parse(value); const queryString = urlBuilder.getQuery(); if (!queryString) { return value; } const query = URLQuery.parse(queryString); for (const k of query.keys()) { if (!this.allowedQueryParameters.has(k.toLowerCase())) { query.set(k, RedactedString); } } urlBuilder.setQuery(query.toString()); return urlBuilder.toString(); } } // Copyright (c) Microsoft Corporation. const custom = util.inspect.custom; // Copyright (c) Microsoft Corporation. const errorSanitizer = new Sanitizer(); /** * An error resulting from an HTTP request to a service endpoint. */ class RestError extends Error { constructor(message, code, statusCode, request, response) { super(message); this.name = "RestError"; this.code = code; this.statusCode = statusCode; this.request = request; this.response = response; Object.setPrototypeOf(this, RestError.prototype); } /** * Logging method for util.inspect in Node */ [custom]() { return `RestError: ${this.message} \n ${errorSanitizer.sanitize(this)}`; } } /** * A constant string to identify errors that may arise when making an HTTP request that indicates an issue with the transport layer (e.g. the hostname of the URL cannot be resolved via DNS.) */ RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR"; /** * A constant string to identify errors that may arise from parsing an incoming HTTP response. Usually indicates a malformed HTTP body, such as an encoded JSON payload that is incomplete. */ RestError.PARSE_ERROR = "PARSE_ERROR"; // Copyright (c) Microsoft Corporation. const logger = logger$1.createClientLogger("core-http"); // Copyright (c) Microsoft Corporation. function getCachedAgent(isHttps, agentCache) { return isHttps ? agentCache.httpsAgent : agentCache.httpAgent; } class ReportTransform extends stream.Transform { constructor(progressCallback) { super(); this.progressCallback = progressCallback; this.loadedBytes = 0; } _transform(chunk, _encoding, callback) { this.push(chunk); this.loadedBytes += chunk.length; this.progressCallback({ loadedBytes: this.loadedBytes }); callback(undefined); } } function isReadableStream(body) { return body && typeof body.pipe === "function"; } function isStreamComplete(stream, aborter) { return new Promise((resolve) => { stream.once("close", () => { aborter === null || aborter === void 0 ? void 0 : aborter.abort(); resolve(); }); stream.once("end", resolve); stream.once("error", resolve); }); } /** * Transforms a set of headers into the key/value pair defined by {@link HttpHeadersLike} */ function parseHeaders(headers) { const httpHeaders = new HttpHeaders(); headers.forEach((value, key) => { httpHeaders.set(key, value); }); return httpHeaders; } /** * An HTTP client that uses `node-fetch`. */ class NodeFetchHttpClient { constructor() { // a mapping of proxy settings string `${host}:${port}:${username}:${password}` to agent this.proxyAgentMap = new Map(); this.keepAliveAgents = {}; } /** * Provides minimum viable error handling and the logic that executes the abstract methods. * @param httpRequest - Object representing the outgoing HTTP request. * @returns An object representing the incoming HTTP response. */ async sendRequest(httpRequest) { var _a; if (!httpRequest && typeof httpRequest !== "object") { throw new Error("'httpRequest' (WebResourceLike) cannot be null or undefined and must be of type object."); } const abortController$1 = new abortController.AbortController(); let abortListener; if (httpRequest.abortSignal) { if (httpRequest.abortSignal.aborted) { throw new abortController.AbortError("The operation was aborted."); } abortListener = (event) => { if (event.type === "abort") { abortController$1.abort(); } }; httpRequest.abortSignal.addEventListener("abort", abortListener); } if (httpRequest.timeout) { setTimeout(() => { abortController$1.abort(); }, httpRequest.timeout); } if (httpRequest.formData) { const formData = httpRequest.formData; const requestForm = new FormData__default["default"](); const appendFormValue = (key, value) => { // value function probably returns a stream so we can provide a fresh stream on each retry if (typeof value === "function") { value = value(); } if (value && Object.prototype.hasOwnProperty.call(value, "value") && Object.prototype.hasOwnProperty.call(value, "options")) { requestForm.append(key, value.value, value.options); } else { requestForm.append(key, value); } }; for (const formKey of Object.keys(formData)) { const formValue = formData[formKey]; if (Array.isArray(formValue)) { for (let j = 0; j < formValue.length; j++) { appendFormValue(formKey, formValue[j]); } } else { appendFormValue(formKey, formValue); } } httpRequest.body = requestForm; httpRequest.formData = undefined; const contentType = httpRequest.headers.get("Content-Type"); if (contentType && contentType.indexOf("multipart/form-data") !== -1) { if (typeof requestForm.getBoundary === "function") { httpRequest.headers.set("Content-Type", `multipart/form-data; boundary=${requestForm.getBoundary()}`); } else { // browser will automatically apply a suitable content-type header httpRequest.headers.remove("Content-Type"); } } } let body = httpRequest.body ? typeof httpRequest.body === "function" ? httpRequest.body() : httpRequest.body : undefined; if (httpRequest.onUploadProgress && httpRequest.body) { const onUploadProgress = httpRequest.onUploadProgress; const uploadReportStream = new ReportTransform(onUploadProgress); if (isReadableStream(body)) { body.pipe(uploadReportStream); } else { uploadReportStream.end(body); } body = uploadReportStream; } const platformSpecificRequestInit = await this.prepareRequest(httpRequest); 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); const headers = parseHeaders(response.headers); const streaming = ((_a = httpRequest.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(response.status)) || httpRequest.streamResponseBody; operationResponse = { headers: headers, request: httpRequest, status: response.status, readableStreamBody: streaming ? response.body : undefined, bodyAsText: !streaming ? await response.text() : undefined, }; const onDownloadProgress = httpRequest.onDownloadProgress; if (onDownloadProgress) { const responseBody = response.body || undefined; if (isReadableStream(responseBody)) { const downloadReportStream = new ReportTransform(onDownloadProgress); responseBody.pipe(downloadReportStream); operationResponse.readableStreamBody = downloadReportStream; } else { const length = parseInt(headers.get("Content-Length")) || undefined; if (length) { // Calling callback for non-stream response for consistency with browser onDownloadProgress({ loadedBytes: length }); } } } await this.processRequest(operationResponse); return operationResponse; } catch (error) { const fetchError = error; if (fetchError.code === "ENOTFOUND") { throw new RestError(fetchError.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest); } else if (fetchError.type === "aborted") { throw new abortController.AbortError("The operation was aborted."); } throw fetchError; } finally { // clean up event listener if (httpRequest.abortSignal && abortListener) { let uploadStreamDone = Promise.resolve(); if (isReadableStream(body)) { uploadStreamDone = isStreamComplete(body); } let downloadStreamDone = Promise.resolve(); if (isReadableStream(operationResponse === null || operationResponse === void 0 ? void 0 : operationResponse.readableStreamBody)) { downloadStreamDone = isStreamComplete(operationResponse.readableStreamBody, abortController$1); } Promise.all([uploadStreamDone, downloadStreamDone]) .then(() => { var _a; (_a = httpRequest.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener("abort", abortListener); return; }) .catch((e) => { logger.warning("Error when cleaning up abortListener on httpRequest", e); }); } } } getOrCreateAgent(httpRequest) { var _a; const isHttps = isUrlHttps(httpRequest.url); // At the moment, proxy settings and keepAlive are mutually // exclusive because the 'tunnel' library currently lacks the // ability to create a proxy with keepAlive turned on. if (httpRequest.proxySettings) { const { host, port, username, password } = httpRequest.proxySettings; const key = `${host}:${port}:${username}:${password}`; const proxyAgents = (_a = this.proxyAgentMap.get(key)) !== null && _a !== void 0 ? _a : {}; let agent = getCachedAgent(isHttps, proxyAgents); if (agent) { return agent; } const tunnel = createProxyAgent(httpRequest.url, httpRequest.proxySettings, httpRequest.headers); agent = tunnel.agent; if (tunnel.isHttps) { proxyAgents.httpsAgent = tunnel.agent; } else { proxyAgents.httpAgent = tunnel.agent; } this.proxyAgentMap.set(key, proxyAgents); return agent; } else if (httpRequest.keepAlive) { let agent = getCachedAgent(isHttps, this.keepAliveAgents); if (agent) { return agent; } const agentOptions = { keepAlive: httpRequest.keepAlive, }; if (isHttps) { agent = this.keepAliveAgents.httpsAgent = new https__namespace.Agent(agentOptions); } else { agent = this.keepAliveAgents.httpAgent = new http__namespace.Agent(agentOptions); } return agent; } else { return isHttps ? https__namespace.globalAgent : http__namespace.globalAgent; } } /** * Uses `node-fetch` to perform the request. */ // eslint-disable-next-line @azure/azure-sdk/ts-apisurface-standardized-verbs async fetch(input, init) { return node_fetch__default["default"](input, init); } /** * Prepares a request based on the provided web resource. */ async prepareRequest(httpRequest) { const requestInit = {}; // Set the http(s) agent requestInit.agent = this.getOrCreateAgent(httpRequest); requestInit.compress = httpRequest.decompressResponse; return requestInit; } /** * Process an HTTP response. */ async processRequest(_operationResponse) { /* no_op */ } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * The different levels of logs that can be used with the HttpPipelineLogger. */ exports.HttpPipelineLogLevel = void 0; (function (HttpPipelineLogLevel) { /** * A log level that indicates that no logs will be logged. */ HttpPipelineLogLevel[HttpPipelineLogLevel["OFF"] = 0] = "OFF"; /** * An error log. */ HttpPipelineLogLevel[HttpPipelineLogLevel["ERROR"] = 1] = "ERROR"; /** * A warning log. */ HttpPipelineLogLevel[HttpPipelineLogLevel["WARNING"] = 2] = "WARNING"; /** * An information log. */ HttpPipelineLogLevel[HttpPipelineLogLevel["INFO"] = 3] = "INFO"; })(exports.HttpPipelineLogLevel || (exports.HttpPipelineLogLevel = {})); // Copyright (c) Microsoft Corporation. /** * Converts an OperationOptions to a RequestOptionsBase * * @param opts - OperationOptions object to convert to RequestOptionsBase */ function operationOptionsToRequestOptionsBase(opts) { const { requestOptions, tracingOptions } = opts, additionalOptions = tslib.__rest(opts, ["requestOptions", "tracingOptions"]); let result = additionalOptions; if (requestOptions) { result = Object.assign(Object.assign({}, result), requestOptions); } if (tracingOptions) { result.tracingContext = tracingOptions.tracingContext; // By passing spanOptions if they exist at runtime, we're backwards compatible with @azure/core-tracing@preview.13 and earlier. result.spanOptions = tracingOptions === null || tracingOptions === void 0 ? void 0 : tracingOptions.spanOptions; } return result; } // Copyright (c) Microsoft Corporation. /** * The base class from which all request policies derive. */ class BaseRequestPolicy { /** * The main method to implement that manipulates a request/response. */ constructor( /** * The next policy in the pipeline. Each policy is responsible for executing the next one if the request is to continue through the pipeline. */ _nextPolicy, /** * The options that can be passed to a given request policy. */ _options) { this._nextPolicy = _nextPolicy; this._options = _options; } /** * Get whether or not a log with the provided log level should be logged. * @param logLevel - The log level of the log that will be logged. * @returns Whether or not a log with the provided log level should be logged. */ shouldLog(logLevel) { return this._options.shouldLog(logLevel); } /** * Attempt to log the provided message to the provided logger. If no logger was provided or if * the log level does not meat the logger's threshold, then nothing will be logged. * @param logLevel - The log level of this log. * @param message - The message of this log. */ log(logLevel, message) { this._options.log(logLevel, message); } } /** * Optional properties that can be used when creating a RequestPolicy. */ class RequestPolicyOptions { constructor(_logger) { this._logger = _logger; } /** * Get whether or not a log with the provided log level should be logged. * @param logLevel - The log level of the log that will be logged. * @returns Whether or not a log with the provided log level should be logged. */ shouldLog(logLevel) { return (!!this._logger && logLevel !== exports.HttpPipelineLogLevel.OFF && logLevel <= this._logger.minimumLogLevel); } /** * Attempt to log the provided message to the provided logger. If no logger was provided or if * the log level does not meet the logger's threshold, then nothing will be logged. * @param logLevel - The log level of this log. * @param message - The message of this log. */ log(logLevel, message) { if (this._logger && this.shouldLog(logLevel)) { this._logger.log(logLevel, message); } } } // Copyright (c) Microsoft Corporation. // Note: The reason we re-define all of the xml2js default settings (version 2.0) here is because the default settings object exposed // by the xm2js library is mutable. See https://github.com/Leonidas-from-XIV/node-xml2js/issues/536 // By creating a new copy of the settings each time we instantiate the parser, // we are safeguarding against the possibility of the default settings being mutated elsewhere unintentionally. const xml2jsDefaultOptionsV2 = { explicitCharkey: false, trim: false, normalize: false, normalizeTags: false, attrkey: XML_ATTRKEY, explicitArray: true, ignoreAttrs: false, mergeAttrs: false, explicitRoot: true, validator: undefined, xmlns: false, explicitChildren: false, preserveChildrenOrder: false, childkey: "$$", charsAsChildren: false, includeWhiteChars: false, async: false, strict: true, attrNameProcessors: undefined, attrValueProcessors: undefined, tagNameProcessors: undefined, valueProcessors: undefined, rootName: "root", xmldec: { version: "1.0", encoding: "UTF-8", standalone: true, }, doctype: undefined, renderOpts: { pretty: true, indent: " ", newline: "\n", }, headless: false, chunkSize: 10000, emptyTag: "", cdata: false, }; // The xml2js settings for general XML parsing operations. const xml2jsParserSettings = Object.assign({}, xml2jsDefaultOptionsV2); xml2jsParserSettings.explicitArray = false; // The xml2js settings for general XML building operations. const xml2jsBuilderSettings = Object.assign({}, xml2jsDefaultOptionsV2); xml2jsBuilderSettings.explicitArray = false; xml2jsBuilderSettings.renderOpts = { pretty: false, }; /** * Converts given JSON object to XML string * @param obj - JSON object to be converted into XML string * @param opts - Options that govern the parsing of given JSON object */ function stringifyXML(obj, opts = {}) { var _a; xml2jsBuilderSettings.rootName = opts.rootName; xml2jsBuilderSettings.charkey = (_a = opts.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; const builder = new xml2js__namespace.Builder(xml2jsBuilderSettings); return builder.buildObject(obj); } /** * Converts given XML string into JSON * @param str - String containing the XML content to be parsed into JSON * @param opts - Options that govern the parsing of given xml string */ function parseXML(str, opts = {}) { var _a; xml2jsParserSettings.explicitRoot = !!opts.includeRoot; xml2jsParserSettings.charkey = (_a = opts.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; const xmlParser = new xml2js__namespace.Parser(xml2jsParserSettings); return new Promise((resolve, reject) => { if (!str) { reject(new Error("Document is empty")); } else { xmlParser.parseString(str, (err, res) => { if (err) { reject(err); } else { resolve(res); } }); } }); } // Copyright (c) Microsoft Corporation. /** * Create a new serialization RequestPolicyCreator that will serialized HTTP request bodies as they * pass through the HTTP pipeline. */ function deserializationPolicy(deserializationContentTypes, parsingOptions) { return { create: (nextPolicy, options) => { return new DeserializationPolicy(nextPolicy, options, deserializationContentTypes, parsingOptions); }, }; } const defaultJsonContentTypes = ["application/json", "text/json"]; const defaultXmlContentTypes = ["application/xml", "application/atom+xml"]; const DefaultDeserializationOptions = { expectedContentTypes: { json: defaultJsonContentTypes, xml: defaultXmlContentTypes, }, }; /** * A RequestPolicy that will deserialize HTTP response bodies and headers as they pass through the * HTTP pipeline. */ class DeserializationPolicy extends BaseRequestPolicy { constructor(nextPolicy, requestPolicyOptions, deserializationContentTypes, parsingOptions = {}) { var _a; super(nextPolicy, requestPolicyOptions); this.jsonContentTypes = (deserializationContentTypes && deserializationContentTypes.json) || defaultJsonContentTypes; this.xmlContentTypes = (deserializationContentTypes && deserializationContentTypes.xml) || defaultXmlContentTypes; this.xmlCharKey = (_a = parsingOptions.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; } async sendRequest(request) { return this._nextPolicy.sendRequest(request).then((response) => deserializeResponseBody(this.jsonContentTypes, this.xmlContentTypes, response, { xmlCharKey: this.xmlCharKey, })); } } function getOperationResponse(parsedResponse) { let result; const request = parsedResponse.request; const operationSpec = request.operationSpec; if (operationSpec) { const operationResponseGetter = request.operationResponseGetter; if (!operationResponseGetter) { result = operationSpec.responses[parsedResponse.status]; } else { result = operationResponseGetter(operationSpec, parsedResponse); } } return result; } function shouldDeserializeResponse(parsedResponse) { const shouldDeserialize = parsedResponse.request.shouldDeserialize; let result; if (shouldDeserialize === undefined) { result = true; } else if (typeof shouldDeserialize === "boolean") { result = shouldDeserialize; } else { result = shouldDeserialize(parsedResponse); } return result; } /** * Given a particular set of content types to parse as either JSON or XML, consumes the HTTP response to produce the result object defined by the request's {@link OperationSpec}. * @param jsonContentTypes - Response content types to parse the body as JSON. * @param xmlContentTypes - Response content types to parse the body as XML. * @param response - HTTP Response from the pipeline. * @param options - Options to the serializer, mostly for configuring the XML parser if needed. * @returns A parsed {@link HttpOperationResponse} object that can be returned by the {@link ServiceClient}. */ function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options = {}) { var _a, _b, _c; const updatedOptions = { rootName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "", includeRoot: (_b = options.includeRoot) !== null && _b !== void 0 ? _b : false, xmlCharKey: (_c = options.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY, }; return parse(jsonContentTypes, xmlContentTypes, response, updatedOptions).then((parsedResponse) => { if (!shouldDeserializeResponse(parsedResponse)) { return parsedResponse; } const operationSpec = parsedResponse.request.operationSpec; if (!operationSpec || !operationSpec.responses) { return parsedResponse; } const responseSpec = getOperationResponse(parsedResponse); const { error, shouldReturnResponse } = handleErrorResponse(parsedResponse, operationSpec, responseSpec); if (error) { throw error; } else if (shouldReturnResponse) { return parsedResponse; } // An operation response spec does exist for current status code, so // use it to deserialize the response. if (responseSpec) { if (responseSpec.bodyMapper) { let valueToDeserialize = parsedResponse.parsedBody; if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperType.Sequence) { valueToDeserialize = typeof valueToDeserialize === "object" ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName] : []; } try { parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options); } catch (innerError) { const restError = new RestError(`Error ${innerError} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); throw restError; } } else if (operationSpec.httpMethod === "HEAD") { // head methods never have a body, but we return a boolean to indicate presence/absence of the resource parsedResponse.parsedBody = response.status >= 200 && response.status < 300; } if (responseSpec.headersMapper) { parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.toJson(), "operationRes.parsedHeaders", options); } } return parsedResponse; }); } function isOperationSpecEmpty(operationSpec) { const expectedStatusCodes = Object.keys(operationSpec.responses); return (expectedStatusCodes.length === 0 || (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default")); } function handleErrorResponse(parsedResponse, operationSpec, responseSpec) { var _a; const isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300; const isExpectedStatusCode = isOperationSpecEmpty(operationSpec) ? isSuccessByStatus : !!responseSpec; if (isExpectedStatusCode) { if (responseSpec) { if (!responseSpec.isError) { return { error: null, shouldReturnResponse: false }; } } else { return { error: null, shouldReturnResponse: false }; } } const errorResponseSpec = responseSpec !== null && responseSpec !== void 0 ? responseSpec : operationSpec.responses.default; const streaming = ((_a = parsedResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(parsedResponse.status)) || parsedResponse.request.streamResponseBody; const initialErrorMessage = streaming ? `Unexpected status code: ${parsedResponse.status}` : parsedResponse.bodyAsText; const error = new RestError(initialErrorMessage, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); // If the item failed but there's no error spec or default spec to deserialize the error, // we should fail so we just throw the parsed response if (!errorResponseSpec) { throw error; } const defaultBodyMapper = errorResponseSpec.bodyMapper; const defaultHeadersMapper = errorResponseSpec.headersMapper; try { // If error response has a body, try to deserialize it using default body mapper. // Then try to extract error code & message from it if (parsedResponse.parsedBody) { const parsedBody = parsedResponse.parsedBody; let parsedError; if (defaultBodyMapper) { let valueToDeserialize = parsedBody; if (operationSpec.isXML && defaultBodyMapper.type.name === MapperType.Sequence) { valueToDeserialize = typeof parsedBody === "object" ? parsedBody[defaultBodyMapper.xmlElementName] : []; } parsedError = operationSpec.serializer.deserialize(defaultBodyMapper, valueToDeserialize, "error.response.parsedBody"); } const internalError = parsedBody.error || parsedError || parsedBody; error.code = internalError.code; if (internalError.message) { error.message = internalError.message; } if (defaultBodyMapper) { error.response.parsedBody = parsedError; } } // 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.toJson(), "operationRes.parsedHeaders"); } } catch (defaultError) { error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody - "${parsedResponse.bodyAsText}" for the default response.`; } return { error, shouldReturnResponse: false }; } function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts) { var _a; const errorHandler = (err) => { const msg = `Error "${err}" occurred while parsing the response body - ${operationResponse.bodyAsText}.`; const errCode = err.code || RestError.PARSE_ERROR; const e = new RestError(msg, errCode, operationResponse.status, operationResponse.request, operationResponse); return Promise.reject(e); }; const streaming = ((_a = operationResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(operationResponse.status)) || operationResponse.request.streamResponseBody; if (!streaming && operationResponse.bodyAsText) { const text = operationResponse.bodyAsText; const contentType = operationResponse.headers.get("Content-Type") || ""; const contentComponents = !contentType ? [] : contentType.split(";").map((component) => component.toLowerCase()); if (contentComponents.length === 0 || contentComponents.some((component) => jsonContentTypes.indexOf(component) !== -1)) { return new Promise((resolve) => { operationResponse.parsedBody = JSON.parse(text); resolve(operationResponse); }).catch(errorHandler); } else if (contentComponents.some((component) => xmlContentTypes.indexOf(component) !== -1)) { return parseXML(text, opts) .then((body) => { operationResponse.parsedBody = body; return operationResponse; }) .catch(errorHandler); } } return Promise.resolve(operationResponse); } // Copyright (c) Microsoft Corporation. /** * By default, HTTP connections are maintained for future requests. */ const DefaultKeepAliveOptions = { enable: true, }; /** * Creates a policy that controls whether HTTP connections are maintained on future requests. * @param keepAliveOptions - Keep alive options. By default, HTTP connections are maintained for future requests. * @returns An instance of the {@link KeepAlivePolicy} */ function keepAlivePolicy(keepAliveOptions) { return { create: (nextPolicy, options) => { return new KeepAlivePolicy(nextPolicy, options, keepAliveOptions || DefaultKeepAliveOptions); }, }; } /** * KeepAlivePolicy is a policy used to control keep alive settings for every request. */ class KeepAlivePolicy extends BaseRequestPolicy { /** * Creates an instance of KeepAlivePolicy. * * @param nextPolicy - * @param options - * @param keepAliveOptions - */ constructor(nextPolicy, options, keepAliveOptions) { super(nextPolicy, options); this.keepAliveOptions = keepAliveOptions; } /** * Sends out request. * * @param request - * @returns */ async sendRequest(request) { request.keepAlive = this.keepAliveOptions.enable; return this._nextPolicy.sendRequest(request); } } // Copyright (c) Microsoft Corporation. /** * Methods that are allowed to follow redirects 301 and 302 */ const allowedRedirect = ["GET", "HEAD"]; const DefaultRedirectOptions = { handleRedirects: true, maxRetries: 20, }; /** * Creates a redirect policy, which sends a repeats the request to a new destination if a response arrives with a "location" header, and a status code between 300 and 307. * @param maximumRetries - Maximum number of redirects to follow. * @returns An instance of the {@link RedirectPolicy} */ function redirectPolicy(maximumRetries = 20) { return { create: (nextPolicy, options) => { return new RedirectPolicy(nextPolicy, options, maximumRetries); }, }; } /** * Resends the request to a new destination if a response arrives with a "location" header, and a status code between 300 and 307. */ class RedirectPolicy extends BaseRequestPolicy { constructor(nextPolicy, options, maxRetries = 20) { super(nextPolicy, options); this.maxRetries = maxRetries; } sendRequest(request) { return this._nextPolicy .sendRequest(request) .then((response) => handleRedirect(this, response, 0)); } } function handleRedirect(policy, response, currentRetries) { const { request, status } = response; const locationHeader = response.headers.get("location"); if (locationHeader && (status === 300 || (status === 301 && allowedRedirect.includes(request.method)) || (status === 302 && allowedRedirect.includes(request.method)) || (status === 303 && request.method === "POST") || status === 307) && (!policy.maxRetries || currentRetries < policy.maxRetries)) { const builder = URLBuilder.parse(request.url); builder.setPath(locationHeader); request.url = builder.toString(); // POST request with Status code 303 should be converted into a // redirected GET request if the redirect url is present in the location header if (status === 303) { request.method = "GET"; delete request.body; } return policy._nextPolicy .sendRequest(request) .then((res) => handleRedirect(policy, res, currentRetries + 1)); } return Promise.resolve(response); } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. const DEFAULT_CLIENT_RETRY_COUNT = 3; // intervals are in ms const DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30; const DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90; const DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3; function isNumber(n) { return typeof n === "number"; } /** * @internal * Determines if the operation should be retried. * * @param retryLimit - Specifies the max number of retries. * @param predicate - Initial chekck on whether to retry based on given responses or errors * @param retryData - The retry data. * @returns True if the operation qualifies for a retry; false otherwise. */ function shouldRetry(retryLimit, predicate, retryData, response, error) { if (!predicate(response, error)) { return false; } return retryData.retryCount < retryLimit; } /** * @internal * Updates the retry data for the next attempt. * * @param retryOptions - specifies retry interval, and its lower bound and upper bound. * @param retryData - The retry data. * @param err - The operation"s error, if any. */ function updateRetryData(retryOptions, retryData = { retryCount: 0, retryInterval: 0 }, err) { if (err) { if (retryData.error) { err.innerError = retryData.error; } retryData.error = err; } // Adjust retry count retryData.retryCount++; // Adjust retry interval let incrementDelta = Math.pow(2, retryData.retryCount - 1) - 1; const boundedRandDelta = retryOptions.retryInterval * 0.8 + Math.floor(Math.random() * (retryOptions.retryInterval * 0.4)); incrementDelta *= boundedRandDelta; retryData.retryInterval = Math.min(retryOptions.minRetryInterval + incrementDelta, retryOptions.maxRetryInterval); return retryData; } // 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. * @param retryCount - Maximum number of retries. * @param retryInterval - Base time between retries. * @param maxRetryInterval - Maximum time to wait between retries. */ function exponentialRetryPolicy(retryCount, retryInterval, maxRetryInterval) { return { create: (nextPolicy, options) => { return new ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, maxRetryInterval); }, }; } /** * Describes the Retry Mode type. Currently supporting only Exponential. */ exports.RetryMode = void 0; (function (RetryMode) { /** * Currently supported retry mode. * Each time a retry happens, it will take exponentially more time than the last time. */ RetryMode[RetryMode["Exponential"] = 0] = "Exponential"; })(exports.RetryMode || (exports.RetryMode = {})); const DefaultRetryOptions = { maxRetries: DEFAULT_CLIENT_RETRY_COUNT, retryDelayInMs: DEFAULT_CLIENT_RETRY_INTERVAL, maxRetryDelayInMs: DEFAULT_CLIENT_MAX_RETRY_INTERVAL, }; /** * Instantiates a new "ExponentialRetryPolicyFilter" instance. */ class ExponentialRetryPolicy extends BaseRequestPolicy { /** * @param nextPolicy - The next RequestPolicy in the pipeline chain. * @param options - The options for this RequestPolicy. * @param retryCount - The client retry count. * @param retryInterval - The client retry interval, in milliseconds. * @param minRetryInterval - The minimum retry interval, in milliseconds. * @param maxRetryInterval - The maximum retry interval, in milliseconds. */ constructor(nextPolicy, options, retryCount, retryInterval, maxRetryInterval) { super(nextPolicy, options); this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT; this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL; this.maxRetryInterval = isNumber(maxRetryInterval) ? maxRetryInterval : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; } sendRequest(request) { return this._nextPolicy .sendRequest(request.clone()) .then((response) => retry$1(this, request, response)) .catch((error) => retry$1(this, request, error.response, undefined, error)); } } async function retry$1(policy, request, response, retryData, requestError) { function shouldPolicyRetry(responseParam) { const statusCode = responseParam === null || responseParam === void 0 ? void 0 : responseParam.status; if (statusCode === 503 && (response === null || response === void 0 ? void 0 : response.headers.get(Constants.HeaderConstants.RETRY_AFTER))) { return false; } if (statusCode === undefined || (statusCode < 500 && statusCode !== 408) || statusCode === 501 || statusCode === 505) { return false; } return true; } retryData = updateRetryData({ retryInterval: policy.retryInterval, minRetryInterval: 0, maxRetryInterval: policy.maxRetryInterval, }, retryData, requestError); const isAborted = request.abortSignal && request.abortSignal.aborted; if (!isAborted && shouldRetry(policy.retryCount, shouldPolicyRetry, retryData, response)) { logger.info(`Retrying request in ${retryData.retryInterval}`); try { await coreUtil.delay(retryData.retryInterval); const res = await policy._nextPolicy.sendRequest(request.clone()); return retry$1(policy, request, res, retryData); } catch (err) { return retry$1(policy, request, response, retryData, err); } } else if (isAborted || requestError || !response) { // If the operation failed in the end, return all errors instead of just the last one const err = retryData.error || new RestError("Failed to send the request.", RestError.REQUEST_SEND_ERROR, response && response.status, response && response.request, response); throw err; } else { return response; } } // Copyright (c) Microsoft Corporation. /** * Creates a policy that logs information about the outgoing request and the incoming responses. * @param loggingOptions - Logging options. * @returns An instance of the {@link LogPolicy} */ function logPolicy(loggingOptions = {}) { return { create: (nextPolicy, options) => { return new LogPolicy(nextPolicy, options, loggingOptions); }, }; } /** * A policy that logs information about the outgoing request and the incoming responses. */ class LogPolicy extends BaseRequestPolicy { constructor(nextPolicy, options, { logger: logger$1 = logger.info, allowedHeaderNames = [], allowedQueryParameters = [], } = {}) { super(nextPolicy, options); this.logger = logger$1; this.sanitizer = new Sanitizer({ allowedHeaderNames, allowedQueryParameters }); } /** * Header names whose values will be logged when logging is enabled. Defaults to * Date, traceparent, x-ms-client-request-id, and x-ms-request id. Any headers * specified in this field will be added to that list. Any other values will * be written to logs as "REDACTED". * @deprecated Pass these into the constructor instead. */ get allowedHeaderNames() { return this.sanitizer.allowedHeaderNames; } /** * Header names whose values will be logged when logging is enabled. Defaults to * Date, traceparent, x-ms-client-request-id, and x-ms-request id. Any headers * specified in this field will be added to that list. Any other values will * be written to logs as "REDACTED". * @deprecated Pass these into the constructor instead. */ set allowedHeaderNames(allowedHeaderNames) { this.sanitizer.allowedHeaderNames = allowedHeaderNames; } /** * Query string names whose values will be logged when logging is enabled. By default no * query string values are logged. * @deprecated Pass these into the constructor instead. */ get allowedQueryParameters() { return this.sanitizer.allowedQueryParameters; } /** * Query string names whose values will be logged when logging is enabled. By default no * query string values are logged. * @deprecated Pass these into the constructor instead. */ set allowedQueryParameters(allowedQueryParameters) { this.sanitizer.allowedQueryParameters = allowedQueryParameters; } sendRequest(request) { if (!this.logger.enabled) return this._nextPolicy.sendRequest(request); this.logRequest(request); return this._nextPolicy.sendRequest(request).then((response) => this.logResponse(response)); } logRequest(request) { this.logger(`Request: ${this.sanitizer.sanitize(request)}`); } logResponse(response) { this.logger(`Response status code: ${response.status}`); this.logger(`Headers: ${this.sanitizer.sanitize(response.headers)}`); return response; } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * Get the path to this parameter's value as a dotted string (a.b.c). * @param parameter - The parameter to get the path string for. * @returns The path to this parameter's value as a dotted string. */ function getPathStringFromParameter(parameter) { return getPathStringFromParameterPath(parameter.parameterPath, parameter.mapper); } function getPathStringFromParameterPath(parameterPath, mapper) { let result; if (typeof parameterPath === "string") { result = parameterPath; } else if (Array.isArray(parameterPath)) { result = parameterPath.join("."); } else { result = mapper.serializedName; } return result; } // Copyright (c) Microsoft Corporation. /** * Gets the list of status codes for streaming responses. * @internal */ function getStreamResponseStatusCodes(operationSpec) { const result = new Set(); for (const statusCode in operationSpec.responses) { const operationResponse = operationSpec.responses[statusCode]; if (operationResponse.bodyMapper && operationResponse.bodyMapper.type.name === MapperType.Stream) { result.add(Number(statusCode)); } } return result; } // Copyright (c) Microsoft Corporation. function getDefaultUserAgentKey() { return Constants.HeaderConstants.USER_AGENT; } function getPlatformSpecificData() { const runtimeInfo = { key: "Node", value: process.version, }; const osInfo = { key: "OS", value: `(${os__namespace.arch()}-${os__namespace.type()}-${os__namespace.release()})`, }; return [runtimeInfo, osInfo]; } // Copyright (c) Microsoft Corporation. function getRuntimeInfo() { const msRestRuntime = { key: "core-http", value: Constants.coreHttpVersion, }; return [msRestRuntime]; } function getUserAgentString(telemetryInfo, keySeparator = " ", valueSeparator = "/") { return telemetryInfo .map((info) => { const value = info.value ? `${valueSeparator}${info.value}` : ""; return `${info.key}${value}`; }) .join(keySeparator); } const getDefaultUserAgentHeaderName = getDefaultUserAgentKey; /** * The default approach to generate user agents. * Uses static information from this package, plus system information available from the runtime. */ function getDefaultUserAgentValue() { const runtimeInfo = getRuntimeInfo(); const platformSpecificData = getPlatformSpecificData(); const userAgent = getUserAgentString(runtimeInfo.concat(platformSpecificData)); return userAgent; } /** * Returns a policy that adds the user agent header to outgoing requests based on the given {@link TelemetryInfo}. * @param userAgentData - Telemetry information. * @returns A new {@link UserAgentPolicy}. */ function userAgentPolicy(userAgentData) { const key = !userAgentData || userAgentData.key === undefined || userAgentData.key === null ? getDefaultUserAgentKey() : userAgentData.key; const value = !userAgentData || userAgentData.value === undefined || userAgentData.value === null ? getDefaultUserAgentValue() : userAgentData.value; return { create: (nextPolicy, options) => { return new UserAgentPolicy(nextPolicy, options, key, value); }, }; } /** * A policy that adds the user agent header to outgoing requests based on the given {@link TelemetryInfo}. */ class UserAgentPolicy extends BaseRequestPolicy { constructor(_nextPolicy, _options, headerKey, headerValue) { super(_nextPolicy, _options); this._nextPolicy = _nextPolicy; this._options = _options; this.headerKey = headerKey; this.headerValue = headerValue; } sendRequest(request) { this.addUserAgentHeader(request); return this._nextPolicy.sendRequest(request); } /** * Adds the user agent header to the outgoing request. */ addUserAgentHeader(request) { if (!request.headers) { request.headers = new HttpHeaders(); } if (!request.headers.get(this.headerKey) && this.headerValue) { request.headers.set(this.headerKey, this.headerValue); } } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * The format that will be used to join an array of values together for a query parameter value. */ exports.QueryCollectionFormat = void 0; (function (QueryCollectionFormat) { /** * CSV: Each pair of segments joined by a single comma. */ QueryCollectionFormat["Csv"] = ","; /** * SSV: Each pair of segments joined by a single space character. */ QueryCollectionFormat["Ssv"] = " "; /** * TSV: Each pair of segments joined by a single tab character. */ QueryCollectionFormat["Tsv"] = "\t"; /** * Pipes: Each pair of segments joined by a single pipe character. */ QueryCollectionFormat["Pipes"] = "|"; /** * Denotes this is an array of values that should be passed to the server in multiple key/value pairs, e.g. `?queryParam=value1&queryParam=value2` */ QueryCollectionFormat["Multi"] = "Multi"; })(exports.QueryCollectionFormat || (exports.QueryCollectionFormat = {})); // Copyright (c) Microsoft Corporation. // Default options for the cycler if none are provided const DEFAULT_CYCLER_OPTIONS = { forcedRefreshWindowInMs: 1000, retryIntervalInMs: 3000, refreshWindowInMs: 1000 * 60 * 2, // Start refreshing 2m before expiry }; /** * Converts an an unreliable access token getter (which may resolve with null) * into an AccessTokenGetter by retrying the unreliable getter in a regular * interval. * * @param getAccessToken - a function that produces a promise of an access * token that may fail by returning null * @param retryIntervalInMs - the time (in milliseconds) to wait between retry * attempts * @param timeoutInMs - the timestamp after which the refresh attempt will fail, * throwing an exception * @returns - a promise that, if it resolves, will resolve with an access token */ async function beginRefresh(getAccessToken, retryIntervalInMs, timeoutInMs) { // This wrapper handles exceptions gracefully as long as we haven't exceeded // the timeout. async function tryGetAccessToken() { if (Date.now() < timeoutInMs) { try { return await getAccessToken(); } catch (_a) { return null; } } else { const finalToken = await getAccessToken(); // Timeout is up, so throw if it's still null if (finalToken === null) { throw new Error("Failed to refresh access token."); } return finalToken; } } let token = await tryGetAccessToken(); while (token === null) { await coreUtil.delay(retryIntervalInMs); token = await tryGetAccessToken(); } return token; } /** * Creates a token cycler from a credential, scopes, and optional settings. * * A token cycler represents a way to reliably retrieve a valid access token * from a TokenCredential. It will handle initializing the token, refreshing it * when it nears expiration, and synchronizes refresh attempts to avoid * concurrency hazards. * * @param credential - the underlying TokenCredential that provides the access * token * @param scopes - the scopes to request authorization for * @param tokenCyclerOptions - optionally override default settings for the cycler * * @returns - a function that reliably produces a valid access token */ function createTokenCycler(credential, scopes, tokenCyclerOptions) { let refreshWorker = null; let token = null; const options = Object.assign(Object.assign({}, DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions); /** * This little holder defines several predicates that we use to construct * the rules of refreshing the token. */ const cycler = { /** * Produces true if a refresh job is currently in progress. */ get isRefreshing() { return refreshWorker !== null; }, /** * Produces true if the cycler SHOULD refresh (we are within the refresh * window and not already refreshing) */ get shouldRefresh() { var _a; return (!cycler.isRefreshing && ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now()); }, /** * Produces true if the cycler MUST refresh (null or nearly-expired * token). */ get mustRefresh() { return (token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now()); }, }; /** * Starts a refresh job or returns the existing job if one is already * running. */ function refresh(getTokenOptions) { var _a; if (!cycler.isRefreshing) { // We bind `scopes` here to avoid passing it around a lot const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions); // Take advantage of promise chaining to insert an assignment to `token` // before the refresh can be considered done. refreshWorker = beginRefresh(tryGetAccessToken, options.retryIntervalInMs, // If we don't have a token, then we should timeout immediately (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now()) .then((_token) => { refreshWorker = null; token = _token; return token; }) .catch((reason) => { // We also should reset the refresher if we enter a failed state. All // existing awaiters will throw, but subsequent requests will start a // new retry chain. refreshWorker = null; token = null; throw reason; }); } return refreshWorker; } return async (tokenOptions) => { // // Simple rules: // - If we MUST refresh, then return the refresh task, blocking // the pipeline until a token is available. // - If we SHOULD refresh, then run refresh but don't return it // (we can still use the cached token). // - Return the token, since it's fine if we didn't return in // step 1. // if (cycler.mustRefresh) return refresh(tokenOptions); if (cycler.shouldRefresh) { refresh(tokenOptions); } return token; }; } // #endregion /** * Creates a new factory for a RequestPolicy that applies a bearer token to * the requests' `Authorization` headers. * * @param credential - The TokenCredential implementation that can supply the bearer token. * @param scopes - The scopes for which the bearer token applies. */ function bearerTokenAuthenticationPolicy(credential, scopes) { // This simple function encapsulates the entire process of reliably retrieving the token const getToken = createTokenCycler(credential, scopes /* , options */); class BearerTokenAuthenticationPolicy extends BaseRequestPolicy { constructor(nextPolicy, options) { super(nextPolicy, options); } async sendRequest(webResource) { if (!webResource.url.toLowerCase().startsWith("https://")) { throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs."); } const { token } = await getToken({ abortSignal: webResource.abortSignal, tracingOptions: { tracingContext: webResource.tracingContext, }, }); webResource.headers.set(Constants.HeaderConstants.AUTHORIZATION, `Bearer ${token}`); return this._nextPolicy.sendRequest(webResource); } } return { create: (nextPolicy, options) => { return new BearerTokenAuthenticationPolicy(nextPolicy, options); }, }; } // Copyright (c) Microsoft Corporation. /** * Returns a request policy factory that can be used to create an instance of * {@link DisableResponseDecompressionPolicy}. */ function disableResponseDecompressionPolicy() { return { create: (nextPolicy, options) => { return new DisableResponseDecompressionPolicy(nextPolicy, options); }, }; } /** * A policy to disable response decompression according to Accept-Encoding header * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding */ class DisableResponseDecompressionPolicy extends BaseRequestPolicy { /** * Creates an instance of DisableResponseDecompressionPolicy. * * @param nextPolicy - * @param options - */ // The parent constructor is protected. /* eslint-disable-next-line @typescript-eslint/no-useless-constructor */ constructor(nextPolicy, options) { super(nextPolicy, options); } /** * Sends out request. * * @param request - * @returns */ async sendRequest(request) { request.decompressResponse = false; return this._nextPolicy.sendRequest(request); } } // Copyright (c) Microsoft Corporation. /** * Creates a policy that assigns a unique request id to outgoing requests. * @param requestIdHeaderName - The name of the header to use when assigning the unique id to the request. */ function generateClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") { return { create: (nextPolicy, options) => { return new GenerateClientRequestIdPolicy(nextPolicy, options, requestIdHeaderName); }, }; } class GenerateClientRequestIdPolicy extends BaseRequestPolicy { constructor(nextPolicy, options, _requestIdHeaderName) { super(nextPolicy, options); this._requestIdHeaderName = _requestIdHeaderName; } sendRequest(request) { if (!request.headers.contains(this._requestIdHeaderName)) { request.headers.set(this._requestIdHeaderName, request.requestId); } return this._nextPolicy.sendRequest(request); } } // Copyright (c) Microsoft Corporation. let cachedHttpClient; function getCachedDefaultHttpClient() { if (!cachedHttpClient) { cachedHttpClient = new NodeFetchHttpClient(); } return cachedHttpClient; } // Copyright (c) Microsoft Corporation. function ndJsonPolicy() { return { create: (nextPolicy, options) => { return new NdJsonPolicy(nextPolicy, options); }, }; } /** * NdJsonPolicy that formats a JSON array as newline-delimited JSON */ class NdJsonPolicy extends BaseRequestPolicy { /** * Creates an instance of KeepAlivePolicy. */ constructor(nextPolicy, options) { super(nextPolicy, options); } /** * Sends a request. */ async sendRequest(request) { // There currently isn't a good way to bypass the serializer if (typeof request.body === "string" && request.body.startsWith("[")) { const body = JSON.parse(request.body); if (Array.isArray(body)) { request.body = body.map((item) => JSON.stringify(item) + "\n").join(""); } } return this._nextPolicy.sendRequest(request); } } // Copyright (c) Microsoft Corporation. /** * Stores the patterns specified in NO_PROXY environment variable. * @internal */ const globalNoProxyList = []; let noProxyListLoaded = false; /** A cache of whether a host should bypass the proxy. */ const globalBypassedMap = new Map(); function loadEnvironmentProxyValue() { if (!process) { return undefined; } const httpsProxy = getEnvironmentValue(Constants.HTTPS_PROXY); const allProxy = getEnvironmentValue(Constants.ALL_PROXY); const httpProxy = getEnvironmentValue(Constants.HTTP_PROXY); return httpsProxy || allProxy || httpProxy; } /** * Check whether the host of a given `uri` matches any pattern in the no proxy list. * If there's a match, any request sent to the same host shouldn't have the proxy settings set. * This implementation is a port of https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210 */ function isBypassed(uri, noProxyList, bypassedMap) { if (noProxyList.length === 0) { return false; } const host = URLBuilder.parse(uri).getHost(); if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) { return bypassedMap.get(host); } let isBypassedFlag = false; for (const pattern of noProxyList) { if (pattern[0] === ".") { // This should match either domain it self or any subdomain or host // .foo.com will match foo.com it self or *.foo.com if (host.endsWith(pattern)) { isBypassedFlag = true; } else { if (host.length === pattern.length - 1 && host === pattern.slice(1)) { isBypassedFlag = true; } } } else { if (host === pattern) { isBypassedFlag = true; } } } bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag); return isBypassedFlag; } /** * @internal */ function loadNoProxy() { const noProxy = getEnvironmentValue(Constants.NO_PROXY); noProxyListLoaded = true; if (noProxy) { return noProxy .split(",") .map((item) => item.trim()) .filter((item) => item.length); } return []; } /** * Converts a given URL of a proxy server into `ProxySettings` or attempts to retrieve `ProxySettings` from the current environment if one is not passed. * @param proxyUrl - URL of the proxy * @returns The default proxy settings, or undefined. */ function getDefaultProxySettings(proxyUrl) { if (!proxyUrl) { proxyUrl = loadEnvironmentProxyValue(); if (!proxyUrl) { return undefined; } } const { username, password, urlWithoutAuth } = extractAuthFromUrl(proxyUrl); const parsedUrl = URLBuilder.parse(urlWithoutAuth); const schema = parsedUrl.getScheme() ? parsedUrl.getScheme() + "://" : ""; return { host: schema + parsedUrl.getHost(), port: Number.parseInt(parsedUrl.getPort() || "80"), username, password, }; } /** * A policy that allows one to apply proxy settings to all requests. * If not passed static settings, they will be retrieved from the HTTPS_PROXY * or HTTP_PROXY environment variables. * @param proxySettings - ProxySettings to use on each request. * @param options - additional settings, for example, custom NO_PROXY patterns */ function proxyPolicy(proxySettings, options) { if (!proxySettings) { proxySettings = getDefaultProxySettings(); } if (!noProxyListLoaded) { globalNoProxyList.push(...loadNoProxy()); } return { create: (nextPolicy, requestPolicyOptions) => { return new ProxyPolicy(nextPolicy, requestPolicyOptions, proxySettings, options === null || options === void 0 ? void 0 : options.customNoProxyList); }, }; } function extractAuthFromUrl(url) { const atIndex = url.indexOf("@"); if (atIndex === -1) { return { urlWithoutAuth: url }; } const schemeIndex = url.indexOf("://"); const authStart = schemeIndex !== -1 ? schemeIndex + 3 : 0; const auth = url.substring(authStart, atIndex); const colonIndex = auth.indexOf(":"); const hasPassword = colonIndex !== -1; const username = hasPassword ? auth.substring(0, colonIndex) : auth; const password = hasPassword ? auth.substring(colonIndex + 1) : undefined; const urlWithoutAuth = url.substring(0, authStart) + url.substring(atIndex + 1); return { username, password, urlWithoutAuth, }; } class ProxyPolicy extends BaseRequestPolicy { constructor(nextPolicy, options, proxySettings, customNoProxyList) { super(nextPolicy, options); this.proxySettings = proxySettings; this.customNoProxyList = customNoProxyList; } sendRequest(request) { var _a; if (!request.proxySettings && !isBypassed(request.url, (_a = this.customNoProxyList) !== null && _a !== void 0 ? _a : globalNoProxyList, this.customNoProxyList ? undefined : globalBypassedMap)) { request.proxySettings = this.proxySettings; } return this._nextPolicy.sendRequest(request); } } // Copyright (c) Microsoft Corporation. function rpRegistrationPolicy(retryTimeout = 30) { return { create: (nextPolicy, options) => { return new RPRegistrationPolicy(nextPolicy, options, retryTimeout); }, }; } class RPRegistrationPolicy extends BaseRequestPolicy { constructor(nextPolicy, options, _retryTimeout = 30) { super(nextPolicy, options); this._retryTimeout = _retryTimeout; } sendRequest(request) { return this._nextPolicy .sendRequest(request.clone()) .then((response) => registerIfNeeded(this, request, response)); } } function registerIfNeeded(policy, request, response) { if (response.status === 409) { const rpName = checkRPNotRegisteredError(response.bodyAsText); if (rpName) { const urlPrefix = extractSubscriptionUrl(request.url); return (registerRP(policy, urlPrefix, rpName, request) // Autoregistration of ${provider} failed for some reason. We will not return this error // instead will return the initial response with 409 status code back to the user. // do nothing here as we are returning the original response at the end of this method. .catch(() => false) .then((registrationStatus) => { if (registrationStatus) { // Retry the original request. We have to change the x-ms-client-request-id // otherwise Azure endpoint will return the initial 409 (cached) response. request.headers.set("x-ms-client-request-id", generateUuid()); return policy._nextPolicy.sendRequest(request.clone()); } return response; })); } } return Promise.resolve(response); } /** * Reuses the headers of the original request and url (if specified). * @param originalRequest - The original request * @param reuseUrlToo - Should the url from the original request be reused as well. Default false. * @returns A new request object with desired headers. */ function getRequestEssentials(originalRequest, reuseUrlToo = false) { const reqOptions = originalRequest.clone(); if (reuseUrlToo) { reqOptions.url = originalRequest.url; } // We have to change the x-ms-client-request-id otherwise Azure endpoint // will return the initial 409 (cached) response. reqOptions.headers.set("x-ms-client-request-id", generateUuid()); // Set content-type to application/json reqOptions.headers.set("Content-Type", "application/json; charset=utf-8"); return reqOptions; } /** * Validates the error code and message associated with 409 response status code. If it matches to that of * RP not registered then it returns the name of the RP else returns undefined. * @param body - The response body received after making the original request. * @returns The name of the RP if condition is satisfied else undefined. */ function checkRPNotRegisteredError(body) { let result, responseBody; if (body) { try { responseBody = JSON.parse(body); } catch (err) { // do nothing; } if (responseBody && responseBody.error && responseBody.error.message && responseBody.error.code && responseBody.error.code === "MissingSubscriptionRegistration") { const matchRes = responseBody.error.message.match(/.*'(.*)'/i); if (matchRes) { result = matchRes.pop(); } } } return result; } /** * Extracts the first part of the URL, just after subscription: * https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/ * @param url - The original request url * @returns The url prefix as explained above. */ function extractSubscriptionUrl(url) { let result; const matchRes = url.match(/.*\/subscriptions\/[a-f0-9-]+\//gi); if (matchRes && matchRes[0]) { result = matchRes[0]; } else { throw new Error(`Unable to extract subscriptionId from the given url - ${url}.`); } return result; } /** * Registers the given provider. * @param policy - The RPRegistrationPolicy this function is being called against. * @param urlPrefix - https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/ * @param provider - The provider name to be registered. * @param originalRequest - The original request sent by the user that returned a 409 response * with a message that the provider is not registered. */ async function registerRP(policy, urlPrefix, provider, originalRequest) { const postUrl = `${urlPrefix}providers/${provider}/register?api-version=2016-02-01`; const getUrl = `${urlPrefix}providers/${provider}?api-version=2016-02-01`; const reqOptions = getRequestEssentials(originalRequest); reqOptions.method = "POST"; reqOptions.url = postUrl; const response = await policy._nextPolicy.sendRequest(reqOptions); if (response.status !== 200) { throw new Error(`Autoregistration of ${provider} failed. Please try registering manually.`); } return getRegistrationStatus(policy, getUrl, originalRequest); } /** * Polls the registration status of the provider that was registered. Polling happens at an interval of 30 seconds. * Polling will happen till the registrationState property of the response body is "Registered". * @param policy - The RPRegistrationPolicy this function is being called against. * @param url - The request url for polling * @param originalRequest - The original request sent by the user that returned a 409 response * with a message that the provider is not registered. * @returns True if RP Registration is successful. */ async function getRegistrationStatus(policy, url, originalRequest) { const reqOptions = getRequestEssentials(originalRequest); reqOptions.url = url; reqOptions.method = "GET"; const res = await policy._nextPolicy.sendRequest(reqOptions); const obj = res.parsedBody; if (res.parsedBody && obj.registrationState && obj.registrationState === "Registered") { return true; } else { await coreUtil.delay(policy._retryTimeout * 1000); return getRegistrationStatus(policy, url, originalRequest); } } // Copyright (c) Microsoft Corporation. /** * Creates a policy that signs outgoing requests by calling to the provided `authenticationProvider`'s `signRequest` method. * @param authenticationProvider - The authentication provider. * @returns An instance of the {@link SigningPolicy}. */ function signingPolicy(authenticationProvider) { return { create: (nextPolicy, options) => { return new SigningPolicy(nextPolicy, options, authenticationProvider); }, }; } /** * A policy that signs outgoing requests by calling to the provided `authenticationProvider`'s `signRequest` method. */ class SigningPolicy extends BaseRequestPolicy { constructor(nextPolicy, options, authenticationProvider) { super(nextPolicy, options); this.authenticationProvider = authenticationProvider; } signRequest(request) { return this.authenticationProvider.signRequest(request); } sendRequest(request) { return this.signRequest(request).then((nextRequest) => this._nextPolicy.sendRequest(nextRequest)); } } // Copyright (c) Microsoft Corporation. /** * A policy that retries when there's a system error, identified by the codes "ETIMEDOUT", "ESOCKETTIMEDOUT", "ECONNREFUSED", "ECONNRESET" or "ENOENT". * @param retryCount - Maximum number of retries. * @param retryInterval - The client retry interval, in milliseconds. * @param minRetryInterval - The minimum retry interval, in milliseconds. * @param maxRetryInterval - The maximum retry interval, in milliseconds. * @returns An instance of the {@link SystemErrorRetryPolicy} */ function systemErrorRetryPolicy(retryCount, retryInterval, minRetryInterval, maxRetryInterval) { return { create: (nextPolicy, options) => { return new SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval); }, }; } /** * A policy that retries when there's a system error, identified by the codes "ETIMEDOUT", "ESOCKETTIMEDOUT", "ECONNREFUSED", "ECONNRESET" or "ENOENT". * @param retryCount - The client retry count. * @param retryInterval - The client retry interval, in milliseconds. * @param minRetryInterval - The minimum retry interval, in milliseconds. * @param maxRetryInterval - The maximum retry interval, in milliseconds. */ class SystemErrorRetryPolicy extends BaseRequestPolicy { constructor(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval) { super(nextPolicy, options); this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT; this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL; this.minRetryInterval = isNumber(minRetryInterval) ? minRetryInterval : DEFAULT_CLIENT_MIN_RETRY_INTERVAL; this.maxRetryInterval = isNumber(maxRetryInterval) ? maxRetryInterval : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; } sendRequest(request) { return this._nextPolicy .sendRequest(request.clone()) .catch((error) => retry(this, request, error.response, error)); } } async function retry(policy, request, operationResponse, err, retryData) { retryData = updateRetryData(policy, retryData, err); function shouldPolicyRetry(_response, error) { if (error && error.code && (error.code === "ETIMEDOUT" || error.code === "ESOCKETTIMEDOUT" || error.code === "ECONNREFUSED" || error.code === "ECONNRESET" || error.code === "ENOENT")) { return true; } return false; } 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 coreUtil.delay(retryData.retryInterval); return policy._nextPolicy.sendRequest(request.clone()); } catch (nestedErr) { return retry(policy, request, operationResponse, nestedErr, retryData); } } else { if (err) { // If the operation failed in the end, return all errors instead of just the last one return Promise.reject(retryData.error); } return operationResponse; } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * Maximum number of retries for the throttling retry policy */ const DEFAULT_CLIENT_MAX_RETRY_COUNT = 3; // Copyright (c) Microsoft Corporation. const StatusCodes = Constants.HttpConstants.StatusCodes; /** * Creates a policy that re-sends the request if the response indicates the request failed because of throttling reasons. * For example, if the response contains a `Retry-After` header, it will retry sending the request based on the value of that header. * * To learn more, please refer to * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits, * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors * @returns */ function throttlingRetryPolicy() { return { create: (nextPolicy, options) => { return new ThrottlingRetryPolicy(nextPolicy, options); }, }; } const StandardAbortMessage = "The operation was aborted."; /** * Creates a policy that re-sends the request if the response indicates the request failed because of throttling reasons. * For example, if the response contains a `Retry-After` header, it will retry sending the request based on the value of that header. * * To learn more, please refer to * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits, * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors */ class ThrottlingRetryPolicy extends BaseRequestPolicy { constructor(nextPolicy, options, _handleResponse) { super(nextPolicy, options); this.numberOfRetries = 0; this._handleResponse = _handleResponse || this._defaultResponseHandler; } async sendRequest(httpRequest) { const response = await this._nextPolicy.sendRequest(httpRequest.clone()); if (response.status !== StatusCodes.TooManyRequests && response.status !== StatusCodes.ServiceUnavailable) { return response; } else { return this._handleResponse(httpRequest, response); } } async _defaultResponseHandler(httpRequest, httpResponse) { var _a; const retryAfterHeader = httpResponse.headers.get(Constants.HeaderConstants.RETRY_AFTER); if (retryAfterHeader) { const delayInMs = ThrottlingRetryPolicy.parseRetryAfterHeader(retryAfterHeader); if (delayInMs) { this.numberOfRetries += 1; await coreUtil.delay(delayInMs, { abortSignal: httpRequest.abortSignal, abortErrorMsg: StandardAbortMessage, }); if ((_a = httpRequest.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { throw new abortController.AbortError(StandardAbortMessage); } if (this.numberOfRetries < DEFAULT_CLIENT_MAX_RETRY_COUNT) { return this.sendRequest(httpRequest); } else { return this._nextPolicy.sendRequest(httpRequest); } } } return httpResponse; } static parseRetryAfterHeader(headerValue) { const retryAfterInSeconds = Number(headerValue); if (Number.isNaN(retryAfterInSeconds)) { return ThrottlingRetryPolicy.parseDateRetryAfterHeader(headerValue); } else { return retryAfterInSeconds * 1000; } } static parseDateRetryAfterHeader(headerValue) { try { const now = Date.now(); const date = Date.parse(headerValue); const diff = date - now; return Number.isNaN(diff) ? undefined : diff; } catch (error) { return undefined; } } } // Copyright (c) Microsoft Corporation. const createSpan = coreTracing.createSpanFunction({ packagePrefix: "", namespace: "", }); /** * Creates a policy that wraps outgoing requests with a tracing span. * @param tracingOptions - Tracing options. * @returns An instance of the {@link TracingPolicy} class. */ function tracingPolicy(tracingOptions = {}) { return { create(nextPolicy, options) { return new TracingPolicy(nextPolicy, options, tracingOptions); }, }; } /** * A policy that wraps outgoing requests with a tracing span. */ class TracingPolicy extends BaseRequestPolicy { constructor(nextPolicy, options, tracingOptions) { super(nextPolicy, options); this.userAgent = tracingOptions.userAgent; } async sendRequest(request) { if (!request.tracingContext) { return this._nextPolicy.sendRequest(request); } const span = this.tryCreateSpan(request); if (!span) { return this._nextPolicy.sendRequest(request); } try { const response = await this._nextPolicy.sendRequest(request); this.tryProcessResponse(span, response); return response; } catch (err) { this.tryProcessError(span, err); throw err; } } tryCreateSpan(request) { var _a; try { // Passing spanOptions as part of tracingOptions to maintain compatibility @azure/core-tracing@preview.13 and earlier. // We can pass this as a separate parameter once we upgrade to the latest core-tracing. const { span } = createSpan(`HTTP ${request.method}`, { tracingOptions: { spanOptions: Object.assign(Object.assign({}, request.spanOptions), { kind: coreTracing.SpanKind.CLIENT }), tracingContext: request.tracingContext, }, }); // If the span is not recording, don't do any more work. if (!span.isRecording()) { span.end(); return undefined; } const namespaceFromContext = (_a = request.tracingContext) === null || _a === void 0 ? void 0 : _a.getValue(Symbol.for("az.namespace")); if (typeof namespaceFromContext === "string") { span.setAttribute("az.namespace", namespaceFromContext); } span.setAttributes({ "http.method": request.method, "http.url": request.url, requestId: request.requestId, }); if (this.userAgent) { span.setAttribute("http.user_agent", this.userAgent); } // set headers const spanContext = span.spanContext(); const traceParentHeader = coreTracing.getTraceParentHeader(spanContext); if (traceParentHeader && coreTracing.isSpanContextValid(spanContext)) { request.headers.set("traceparent", traceParentHeader); const traceState = spanContext.traceState && spanContext.traceState.serialize(); // if tracestate is set, traceparent MUST be set, so only set tracestate after traceparent if (traceState) { request.headers.set("tracestate", traceState); } } return span; } catch (error) { logger.warning(`Skipping creating a tracing span due to an error: ${error.message}`); return undefined; } } tryProcessError(span, err) { try { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: err.message, }); if (err.statusCode) { span.setAttribute("http.status_code", err.statusCode); } span.end(); } catch (error) { logger.warning(`Skipping tracing span processing due to an error: ${error.message}`); } } tryProcessResponse(span, response) { try { span.setAttribute("http.status_code", response.status); const serviceRequestId = response.headers.get("x-ms-request-id"); if (serviceRequestId) { span.setAttribute("serviceRequestId", serviceRequestId); } span.setStatus({ code: coreTracing.SpanStatusCode.OK, }); span.end(); } catch (error) { logger.warning(`Skipping tracing span processing due to an error: ${error.message}`); } } } // Copyright (c) Microsoft Corporation. /** * ServiceClient sends service requests and receives responses. */ class ServiceClient { /** * The ServiceClient constructor * @param credentials - The credentials used for authentication with the service. * @param options - The service client options that govern the behavior of the client. */ constructor(credentials, /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options */ options) { if (!options) { options = {}; } this._withCredentials = options.withCredentials || false; this._httpClient = options.httpClient || getCachedDefaultHttpClient(); this._requestPolicyOptions = new RequestPolicyOptions(options.httpPipelineLogger); let requestPolicyFactories; if (Array.isArray(options.requestPolicyFactories)) { logger.info("ServiceClient: using custom request policies"); requestPolicyFactories = options.requestPolicyFactories; } else { let authPolicyFactory = undefined; if (coreAuth.isTokenCredential(credentials)) { logger.info("ServiceClient: creating bearer token authentication policy from provided credentials"); // Create a wrapped RequestPolicyFactory here so that we can provide the // correct scope to the BearerTokenAuthenticationPolicy at the first time // one is requested. This is needed because generated ServiceClient // implementations do not set baseUri until after ServiceClient's constructor // is finished, leaving baseUri empty at the time when it is needed to // build the correct scope name. const wrappedPolicyFactory = () => { let bearerTokenPolicyFactory = undefined; // eslint-disable-next-line @typescript-eslint/no-this-alias const serviceClient = this; const serviceClientOptions = options; return { create(nextPolicy, createOptions) { const credentialScopes = getCredentialScopes(serviceClientOptions, serviceClient.baseUri); if (!credentialScopes) { throw new Error(`When using credential, the ServiceClient must contain a baseUri or a credentialScopes in ServiceClientOptions. Unable to create a bearerTokenAuthenticationPolicy`); } if (bearerTokenPolicyFactory === undefined || bearerTokenPolicyFactory === null) { bearerTokenPolicyFactory = bearerTokenAuthenticationPolicy(credentials, credentialScopes); } return bearerTokenPolicyFactory.create(nextPolicy, createOptions); }, }; }; authPolicyFactory = wrappedPolicyFactory(); } else if (credentials && typeof credentials.signRequest === "function") { logger.info("ServiceClient: creating signing policy from provided credentials"); authPolicyFactory = signingPolicy(credentials); } else if (credentials !== undefined && credentials !== null) { throw new Error("The credentials argument must implement the TokenCredential interface"); } logger.info("ServiceClient: using default request policies"); requestPolicyFactories = createDefaultRequestPolicyFactories(authPolicyFactory, options); if (options.requestPolicyFactories) { // options.requestPolicyFactories can also be a function that manipulates // the default requestPolicyFactories array const newRequestPolicyFactories = options.requestPolicyFactories(requestPolicyFactories); if (newRequestPolicyFactories) { requestPolicyFactories = newRequestPolicyFactories; } } } this._requestPolicyFactories = requestPolicyFactories; } /** * Send the provided httpRequest. */ sendRequest(options) { if (options === null || options === undefined || typeof options !== "object") { throw new Error("options cannot be null or undefined and it must be of type object."); } let httpRequest; try { if (isWebResourceLike(options)) { options.validateRequestProperties(); httpRequest = options; } else { httpRequest = new WebResource(); httpRequest = httpRequest.prepare(options); } } catch (error) { return Promise.reject(error); } let httpPipeline = this._httpClient; if (this._requestPolicyFactories && this._requestPolicyFactories.length > 0) { for (let i = this._requestPolicyFactories.length - 1; i >= 0; --i) { httpPipeline = this._requestPolicyFactories[i].create(httpPipeline, this._requestPolicyOptions); } } return httpPipeline.sendRequest(httpRequest); } /** * Send an HTTP request that is populated using the provided OperationSpec. * @param operationArguments - The arguments that the HTTP request's templated values will be populated from. * @param operationSpec - The OperationSpec to use to populate the httpRequest. * @param callback - The callback to call when the response is received. */ async sendOperationRequest(operationArguments, operationSpec, callback) { var _a; if (typeof operationArguments.options === "function") { callback = operationArguments.options; operationArguments.options = undefined; } const serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions; const httpRequest = new WebResource(); let result; try { const baseUri = operationSpec.baseUrl || this.baseUri; if (!baseUri) { throw new Error("If operationSpec.baseUrl is not specified, then the ServiceClient must have a baseUri string property that contains the base URL to use."); } httpRequest.method = operationSpec.httpMethod; httpRequest.operationSpec = operationSpec; const requestUrl = URLBuilder.parse(baseUri); if (operationSpec.path) { requestUrl.appendPath(operationSpec.path); } if (operationSpec.urlParameters && operationSpec.urlParameters.length > 0) { for (const urlParameter of operationSpec.urlParameters) { let urlParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, urlParameter, operationSpec.serializer); urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, getPathStringFromParameter(urlParameter), serializerOptions); if (!urlParameter.skipEncoding) { urlParameterValue = encodeURIComponent(urlParameterValue); } requestUrl.replaceAll(`{${urlParameter.mapper.serializedName || getPathStringFromParameter(urlParameter)}}`, urlParameterValue); } } if (operationSpec.queryParameters && operationSpec.queryParameters.length > 0) { for (const queryParameter of operationSpec.queryParameters) { let queryParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, queryParameter, operationSpec.serializer); if (queryParameterValue !== undefined && queryParameterValue !== null) { queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter), serializerOptions); if (queryParameter.collectionFormat !== undefined && queryParameter.collectionFormat !== null) { if (queryParameter.collectionFormat === exports.QueryCollectionFormat.Multi) { if (queryParameterValue.length === 0) { // The collection is empty, no need to try serializing the current queryParam continue; } else { for (const index in queryParameterValue) { const item = queryParameterValue[index]; queryParameterValue[index] = item === undefined || item === null ? "" : item.toString(); } } } else if (queryParameter.collectionFormat === exports.QueryCollectionFormat.Ssv || queryParameter.collectionFormat === exports.QueryCollectionFormat.Tsv) { queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat); } } if (!queryParameter.skipEncoding) { if (Array.isArray(queryParameterValue)) { for (const index in queryParameterValue) { if (queryParameterValue[index] !== undefined && queryParameterValue[index] !== null) { queryParameterValue[index] = encodeURIComponent(queryParameterValue[index]); } } } else { queryParameterValue = encodeURIComponent(queryParameterValue); } } if (queryParameter.collectionFormat !== undefined && queryParameter.collectionFormat !== null && queryParameter.collectionFormat !== exports.QueryCollectionFormat.Multi && queryParameter.collectionFormat !== exports.QueryCollectionFormat.Ssv && queryParameter.collectionFormat !== exports.QueryCollectionFormat.Tsv) { queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat); } requestUrl.setQueryParameter(queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter), queryParameterValue); } } } httpRequest.url = requestUrl.toString(); const contentType = operationSpec.contentType || this.requestContentType; if (contentType && operationSpec.requestBody) { httpRequest.headers.set("Content-Type", contentType); } if (operationSpec.headerParameters) { for (const headerParameter of operationSpec.headerParameters) { let headerValue = getOperationArgumentValueFromParameter(this, operationArguments, headerParameter, operationSpec.serializer); if (headerValue !== undefined && headerValue !== null) { headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter), serializerOptions); const headerCollectionPrefix = headerParameter.mapper .headerCollectionPrefix; if (headerCollectionPrefix) { for (const key of Object.keys(headerValue)) { httpRequest.headers.set(headerCollectionPrefix + key, headerValue[key]); } } else { httpRequest.headers.set(headerParameter.mapper.serializedName || getPathStringFromParameter(headerParameter), headerValue); } } } } const options = operationArguments.options; if (options) { if (options.customHeaders) { for (const customHeaderName in options.customHeaders) { httpRequest.headers.set(customHeaderName, options.customHeaders[customHeaderName]); } } if (options.abortSignal) { httpRequest.abortSignal = options.abortSignal; } if (options.timeout) { httpRequest.timeout = options.timeout; } if (options.onUploadProgress) { httpRequest.onUploadProgress = options.onUploadProgress; } if (options.onDownloadProgress) { httpRequest.onDownloadProgress = options.onDownloadProgress; } if (options.spanOptions) { // By passing spanOptions if they exist at runtime, we're backwards compatible with @azure/core-tracing@preview.13 and earlier. httpRequest.spanOptions = options.spanOptions; } if (options.tracingContext) { httpRequest.tracingContext = options.tracingContext; } if (options.shouldDeserialize !== undefined && options.shouldDeserialize !== null) { httpRequest.shouldDeserialize = options.shouldDeserialize; } } httpRequest.withCredentials = this._withCredentials; serializeRequestBody(this, httpRequest, operationArguments, operationSpec); if (httpRequest.streamResponseStatusCodes === undefined) { httpRequest.streamResponseStatusCodes = getStreamResponseStatusCodes(operationSpec); } let rawResponse; let sendRequestError; try { rawResponse = await this.sendRequest(httpRequest); } catch (error) { sendRequestError = error; } if (sendRequestError) { if (sendRequestError.response) { sendRequestError.details = flattenResponse(sendRequestError.response, operationSpec.responses[sendRequestError.statusCode] || operationSpec.responses["default"]); } result = Promise.reject(sendRequestError); } else { result = Promise.resolve(flattenResponse(rawResponse, operationSpec.responses[rawResponse.status])); } } catch (error) { result = Promise.reject(error); } const cb = callback; if (cb) { result .then((res) => cb(null, res._response.parsedBody, res._response.request, res._response)) .catch((err) => cb(err)); } return result; } } function serializeRequestBody(serviceClient, httpRequest, operationArguments, operationSpec) { var _a, _b, _c, _d, _e, _f; const serializerOptions = (_b = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions) !== null && _b !== void 0 ? _b : {}; const updatedOptions = { rootName: (_c = serializerOptions.rootName) !== null && _c !== void 0 ? _c : "", includeRoot: (_d = serializerOptions.includeRoot) !== null && _d !== void 0 ? _d : false, xmlCharKey: (_e = serializerOptions.xmlCharKey) !== null && _e !== void 0 ? _e : XML_CHARKEY, }; const xmlCharKey = serializerOptions.xmlCharKey; if (operationSpec.requestBody && operationSpec.requestBody.mapper) { httpRequest.body = getOperationArgumentValueFromParameter(serviceClient, operationArguments, operationSpec.requestBody, operationSpec.serializer); const bodyMapper = operationSpec.requestBody.mapper; const { required, xmlName, xmlElementName, serializedName, xmlNamespace, xmlNamespacePrefix } = bodyMapper; const typeName = bodyMapper.type.name; try { if ((httpRequest.body !== undefined && httpRequest.body !== null) || required) { const requestBodyParameterPathString = getPathStringFromParameter(operationSpec.requestBody); httpRequest.body = operationSpec.serializer.serialize(bodyMapper, httpRequest.body, requestBodyParameterPathString, updatedOptions); const isStream = typeName === MapperType.Stream; if (operationSpec.isXML) { const xmlnsKey = xmlNamespacePrefix ? `xmlns:${xmlNamespacePrefix}` : "xmlns"; const value = getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, httpRequest.body, updatedOptions); if (typeName === MapperType.Sequence) { httpRequest.body = stringifyXML(prepareXMLRootList(value, xmlElementName || xmlName || serializedName, xmlnsKey, xmlNamespace), { rootName: xmlName || serializedName, xmlCharKey, }); } else if (!isStream) { httpRequest.body = stringifyXML(value, { rootName: xmlName || serializedName, xmlCharKey, }); } } else if (typeName === MapperType.String && (((_f = operationSpec.contentType) === null || _f === void 0 ? void 0 : _f.match("text/plain")) || operationSpec.mediaType === "text")) { // the String serializer has validated that request body is a string // so just send the string. return; } else if (!isStream) { httpRequest.body = JSON.stringify(httpRequest.body); } } } catch (error) { throw new Error(`Error "${error.message}" occurred in serializing the payload - ${JSON.stringify(serializedName, undefined, " ")}.`); } } else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) { httpRequest.formData = {}; for (const formDataParameter of operationSpec.formDataParameters) { const formDataParameterValue = getOperationArgumentValueFromParameter(serviceClient, operationArguments, formDataParameter, operationSpec.serializer); if (formDataParameterValue !== undefined && formDataParameterValue !== null) { const formDataParameterPropertyName = formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter); httpRequest.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, getPathStringFromParameter(formDataParameter), updatedOptions); } } } } /** * Adds an xml namespace to the xml serialized object if needed, otherwise it just returns the value itself */ function getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, serializedValue, options) { // Composite and Sequence schemas already got their root namespace set during serialization // We just need to add xmlns to the other schema types if (xmlNamespace && !["Composite", "Sequence", "Dictionary"].includes(typeName)) { const result = {}; result[options.xmlCharKey] = serializedValue; result[XML_ATTRKEY] = { [xmlnsKey]: xmlNamespace }; return result; } return serializedValue; } function getValueOrFunctionResult(value, defaultValueCreator) { let result; if (typeof value === "string") { result = value; } else { result = defaultValueCreator(); if (typeof value === "function") { result = value(result); } } return result; } function createDefaultRequestPolicyFactories(authPolicyFactory, options) { const factories = []; if (options.generateClientRequestIdHeader) { factories.push(generateClientRequestIdPolicy(options.clientRequestIdHeaderName)); } if (authPolicyFactory) { factories.push(authPolicyFactory); } const userAgentHeaderName = getValueOrFunctionResult(options.userAgentHeaderName, getDefaultUserAgentHeaderName); const userAgentHeaderValue = getValueOrFunctionResult(options.userAgent, getDefaultUserAgentValue); if (userAgentHeaderName && userAgentHeaderValue) { factories.push(userAgentPolicy({ key: userAgentHeaderName, value: userAgentHeaderValue })); } factories.push(redirectPolicy()); factories.push(rpRegistrationPolicy(options.rpRegistrationRetryTimeout)); if (!options.noRetryPolicy) { factories.push(exponentialRetryPolicy()); factories.push(systemErrorRetryPolicy()); factories.push(throttlingRetryPolicy()); } factories.push(deserializationPolicy(options.deserializationContentTypes)); if (coreUtil.isNode) { factories.push(proxyPolicy(options.proxySettings)); } factories.push(logPolicy({ logger: logger.info })); return factories; } /** * Creates an HTTP pipeline based on the given options. * @param pipelineOptions - Defines options that are used to configure policies in the HTTP pipeline for an SDK client. * @param authPolicyFactory - An optional authentication policy factory to use for signing requests. * @returns A set of options that can be passed to create a new {@link ServiceClient}. */ function createPipelineFromOptions(pipelineOptions, authPolicyFactory) { const requestPolicyFactories = []; if (pipelineOptions.sendStreamingJson) { requestPolicyFactories.push(ndJsonPolicy()); } let userAgentValue = undefined; if (pipelineOptions.userAgentOptions && pipelineOptions.userAgentOptions.userAgentPrefix) { const userAgentInfo = []; userAgentInfo.push(pipelineOptions.userAgentOptions.userAgentPrefix); // Add the default user agent value if it isn't already specified // by the userAgentPrefix option. const defaultUserAgentInfo = getDefaultUserAgentValue(); if (userAgentInfo.indexOf(defaultUserAgentInfo) === -1) { userAgentInfo.push(defaultUserAgentInfo); } userAgentValue = userAgentInfo.join(" "); } 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 (coreUtil.isNode) { requestPolicyFactories.push(proxyPolicy(pipelineOptions.proxyOptions)); } const deserializationOptions = Object.assign(Object.assign({}, DefaultDeserializationOptions), pipelineOptions.deserializationOptions); const loggingOptions = Object.assign({}, pipelineOptions.loggingOptions); requestPolicyFactories.push(tracingPolicy({ userAgent: userAgentValue }), keepAlivePolicy(keepAliveOptions), userAgentPolicy({ value: userAgentValue }), generateClientRequestIdPolicy(), deserializationPolicy(deserializationOptions.expectedContentTypes), throttlingRetryPolicy(), systemErrorRetryPolicy(), exponentialRetryPolicy(retryOptions.maxRetries, retryOptions.retryDelayInMs, retryOptions.maxRetryDelayInMs)); if (redirectOptions.handleRedirects) { requestPolicyFactories.push(redirectPolicy(redirectOptions.maxRetries)); } if (authPolicyFactory) { requestPolicyFactories.push(authPolicyFactory); } requestPolicyFactories.push(logPolicy(loggingOptions)); if (coreUtil.isNode && pipelineOptions.decompressResponse === false) { requestPolicyFactories.push(disableResponseDecompressionPolicy()); } return { httpClient: pipelineOptions.httpClient, requestPolicyFactories, }; } function getOperationArgumentValueFromParameter(serviceClient, operationArguments, parameter, serializer) { return getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameter.parameterPath, parameter.mapper, serializer); } function getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, serializer) { var _a; let value; if (typeof parameterPath === "string") { parameterPath = [parameterPath]; } const serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions; if (Array.isArray(parameterPath)) { if (parameterPath.length > 0) { if (parameterMapper.isConstant) { value = parameterMapper.defaultValue; } else { let propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath); if (!propertySearchResult.propertyFound) { propertySearchResult = getPropertyFromParameterPath(serviceClient, parameterPath); } let useDefaultValue = false; if (!propertySearchResult.propertyFound) { useDefaultValue = parameterMapper.required || (parameterPath[0] === "options" && parameterPath.length === 2); } value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue; } // Serialize just for validation purposes. const parameterPathString = getPathStringFromParameterPath(parameterPath, parameterMapper); serializer.serialize(parameterMapper, value, parameterPathString, serializerOptions); } } else { if (parameterMapper.required) { value = {}; } for (const propertyName in parameterPath) { const propertyMapper = parameterMapper.type.modelProperties[propertyName]; const propertyPath = parameterPath[propertyName]; const propertyValue = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, propertyPath, propertyMapper, serializer); // Serialize just for validation purposes. const propertyPathString = getPathStringFromParameterPath(propertyPath, propertyMapper); serializer.serialize(propertyMapper, propertyValue, propertyPathString, serializerOptions); if (propertyValue !== undefined && propertyValue !== null) { if (!value) { value = {}; } value[propertyName] = propertyValue; } } } return value; } function getPropertyFromParameterPath(parent, parameterPath) { const result = { propertyFound: false }; let i = 0; for (; i < parameterPath.length; ++i) { const parameterPathPart = parameterPath[i]; // Make sure to check inherited properties too, so don't use hasOwnProperty(). if (parent !== undefined && parent !== null && parameterPathPart in parent) { parent = parent[parameterPathPart]; } else { break; } } if (i === parameterPath.length) { result.propertyValue = parent; result.propertyFound = true; } return result; } /** * Parses an {@link HttpOperationResponse} into a normalized HTTP response object ({@link RestResponse}). * @param _response - Wrapper object for http response. * @param responseSpec - Mappers for how to parse the response properties. * @returns - A normalized response object. */ function flattenResponse(_response, responseSpec) { const parsedHeaders = _response.parsedHeaders; const bodyMapper = responseSpec && responseSpec.bodyMapper; const addOperationResponse = (obj) => { return Object.defineProperty(obj, "_response", { value: _response, }); }; if (bodyMapper) { const typeName = bodyMapper.type.name; if (typeName === "Stream") { return addOperationResponse(Object.assign(Object.assign({}, parsedHeaders), { blobBody: _response.blobBody, readableStreamBody: _response.readableStreamBody })); } const modelProperties = (typeName === "Composite" && bodyMapper.type.modelProperties) || {}; const isPageableResponse = Object.keys(modelProperties).some((k) => modelProperties[k].serializedName === ""); if (typeName === "Sequence" || isPageableResponse) { const arrayResponse = [...(_response.parsedBody || [])]; for (const key of Object.keys(modelProperties)) { if (modelProperties[key].serializedName) { arrayResponse[key] = _response.parsedBody[key]; } } if (parsedHeaders) { for (const key of Object.keys(parsedHeaders)) { arrayResponse[key] = parsedHeaders[key]; } } addOperationResponse(arrayResponse); return arrayResponse; } if (typeName === "Composite" || typeName === "Dictionary") { return addOperationResponse(Object.assign(Object.assign({}, parsedHeaders), _response.parsedBody)); } } if (bodyMapper || _response.request.method === "HEAD" || isPrimitiveType(_response.parsedBody)) { // primitive body types and HEAD booleans return addOperationResponse(Object.assign(Object.assign({}, parsedHeaders), { body: _response.parsedBody })); } return addOperationResponse(Object.assign(Object.assign({}, parsedHeaders), _response.parsedBody)); } function getCredentialScopes(options, baseUri) { if (options === null || options === void 0 ? void 0 : options.credentialScopes) { return options.credentialScopes; } if (baseUri) { return `${baseUri}/.default`; } return undefined; } // Copyright (c) Microsoft Corporation. /** * This function is only here for compatibility. Use createSpanFunction in core-tracing. * * @deprecated This function is only here for compatibility. Use createSpanFunction in core-tracing. * @hidden * @param spanConfig - The name of the operation being performed. * @param tracingOptions - The options for the underlying http request. */ function createSpanFunction(args) { return coreTracing.createSpanFunction(args); } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * Defines the default token refresh buffer duration. */ const TokenRefreshBufferMs = 2 * 60 * 1000; // 2 Minutes /** * Provides an {@link AccessTokenCache} implementation which clears * the cached {@link AccessToken}'s after the expiresOnTimestamp has * passed. * * @deprecated No longer used in the bearer authorization policy. */ class ExpiringAccessTokenCache { /** * Constructs an instance of {@link ExpiringAccessTokenCache} with * an optional expiration buffer time. */ constructor(tokenRefreshBufferMs = TokenRefreshBufferMs) { this.cachedToken = undefined; this.tokenRefreshBufferMs = tokenRefreshBufferMs; } /** * Saves an access token into the internal in-memory cache. * @param accessToken - Access token or undefined to clear the cache. */ setCachedToken(accessToken) { this.cachedToken = accessToken; } /** * Returns the cached access token, or `undefined` if one is not cached or the cached one is expiring soon. */ getCachedToken() { if (this.cachedToken && Date.now() + this.tokenRefreshBufferMs >= this.cachedToken.expiresOnTimestamp) { this.cachedToken = undefined; } return this.cachedToken; } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * Helps the core-http token authentication policies with requesting a new token if we're not currently waiting for a new token. * * @deprecated No longer used in the bearer authorization policy. */ class AccessTokenRefresher { constructor(credential, scopes, requiredMillisecondsBeforeNewRefresh = 30000) { this.credential = credential; this.scopes = scopes; this.requiredMillisecondsBeforeNewRefresh = requiredMillisecondsBeforeNewRefresh; this.lastCalled = 0; } /** * Returns true if the required milliseconds(defaulted to 30000) have been passed signifying * that we are ready for a new refresh. */ isReady() { // We're only ready for a new refresh if the required milliseconds have passed. return (!this.lastCalled || Date.now() - this.lastCalled > this.requiredMillisecondsBeforeNewRefresh); } /** * Stores the time in which it is called, * then requests a new token, * then sets this.promise to undefined, * then returns the token. */ async getToken(options) { this.lastCalled = Date.now(); const token = await this.credential.getToken(this.scopes, options); this.promise = undefined; return token || undefined; } /** * Requests a new token if we're not currently waiting for a new token. * Returns null if the required time between each call hasn't been reached. */ refresh(options) { if (!this.promise) { this.promise = this.getToken(options); } return this.promise; } } // Copyright (c) Microsoft Corporation. const HeaderConstants = Constants.HeaderConstants; const DEFAULT_AUTHORIZATION_SCHEME = "Basic"; /** * A simple {@link ServiceClientCredential} that authenticates with a username and a password. */ class BasicAuthenticationCredentials { /** * Creates a new BasicAuthenticationCredentials object. * * @param userName - User name. * @param password - Password. * @param authorizationScheme - The authorization scheme. */ constructor(userName, password, authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME) { /** * Authorization scheme. Defaults to "Basic". * More information about authorization schemes is available here: https://developer.mozilla.org/docs/Web/HTTP/Authentication#authentication_schemes */ this.authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME; if (userName === null || userName === undefined || typeof userName.valueOf() !== "string") { throw new Error("userName cannot be null or undefined and must be of type string."); } if (password === null || password === undefined || typeof password.valueOf() !== "string") { throw new Error("password cannot be null or undefined and must be of type string."); } this.userName = userName; this.password = password; this.authorizationScheme = authorizationScheme; } /** * Signs a request with the Authentication header. * * @param webResource - The WebResourceLike to be signed. * @returns The signed request object. */ signRequest(webResource) { const credentials = `${this.userName}:${this.password}`; const encodedCredentials = `${this.authorizationScheme} ${encodeString(credentials)}`; if (!webResource.headers) webResource.headers = new HttpHeaders(); webResource.headers.set(HeaderConstants.AUTHORIZATION, encodedCredentials); return Promise.resolve(webResource); } } // Copyright (c) Microsoft Corporation. /** * Authenticates to a service using an API key. */ class ApiKeyCredentials { /** * @param options - Specifies the options to be provided for auth. Either header or query needs to be provided. */ constructor(options) { if (!options || (options && !options.inHeader && !options.inQuery)) { throw new Error(`options cannot be null or undefined. Either "inHeader" or "inQuery" property of the options object needs to be provided.`); } this.inHeader = options.inHeader; this.inQuery = options.inQuery; } /** * Signs a request with the values provided in the inHeader and inQuery parameter. * * @param webResource - The WebResourceLike to be signed. * @returns The signed request object. */ signRequest(webResource) { if (!webResource) { return Promise.reject(new Error(`webResource cannot be null or undefined and must be of type "object".`)); } if (this.inHeader) { if (!webResource.headers) { webResource.headers = new HttpHeaders(); } for (const headerName in this.inHeader) { webResource.headers.set(headerName, this.inHeader[headerName]); } } if (this.inQuery) { if (!webResource.url) { return Promise.reject(new Error(`url cannot be null in the request object.`)); } if (webResource.url.indexOf("?") < 0) { webResource.url += "?"; } for (const key in this.inQuery) { if (!webResource.url.endsWith("?")) { webResource.url += "&"; } webResource.url += `${key}=${this.inQuery[key]}`; } } return Promise.resolve(webResource); } } // Copyright (c) Microsoft Corporation. /** * A {@link TopicCredentials} object used for Azure Event Grid. */ class TopicCredentials extends ApiKeyCredentials { /** * Creates a new EventGrid TopicCredentials object. * * @param topicKey - The EventGrid topic key */ constructor(topicKey) { if (!topicKey || (topicKey && typeof topicKey !== "string")) { throw new Error("topicKey cannot be null or undefined and must be of type string."); } const options = { inHeader: { "aeg-sas-key": topicKey, }, }; super(options); } } 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; } })); exports.AccessTokenRefresher = AccessTokenRefresher; exports.ApiKeyCredentials = ApiKeyCredentials; exports.BaseRequestPolicy = BaseRequestPolicy; exports.BasicAuthenticationCredentials = BasicAuthenticationCredentials; exports.Constants = Constants; exports.DefaultHttpClient = NodeFetchHttpClient; exports.ExpiringAccessTokenCache = ExpiringAccessTokenCache; exports.HttpHeaders = HttpHeaders; exports.MapperType = MapperType; exports.RequestPolicyOptions = RequestPolicyOptions; exports.RestError = RestError; exports.Serializer = Serializer; exports.ServiceClient = ServiceClient; exports.TopicCredentials = TopicCredentials; exports.URLBuilder = URLBuilder; exports.URLQuery = URLQuery; exports.WebResource = WebResource; exports.XML_ATTRKEY = XML_ATTRKEY; exports.XML_CHARKEY = XML_CHARKEY; exports.applyMixins = applyMixins; exports.bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy; exports.createPipelineFromOptions = createPipelineFromOptions; exports.createSpanFunction = createSpanFunction; exports.deserializationPolicy = deserializationPolicy; exports.deserializeResponseBody = deserializeResponseBody; exports.disableResponseDecompressionPolicy = disableResponseDecompressionPolicy; exports.encodeUri = encodeUri; exports.executePromisesSequentially = executePromisesSequentially; exports.exponentialRetryPolicy = exponentialRetryPolicy; exports.flattenResponse = flattenResponse; exports.generateClientRequestIdPolicy = generateClientRequestIdPolicy; exports.generateUuid = generateUuid; exports.getDefaultProxySettings = getDefaultProxySettings; exports.getDefaultUserAgentValue = getDefaultUserAgentValue; exports.isDuration = isDuration; exports.isValidUuid = isValidUuid; exports.keepAlivePolicy = keepAlivePolicy; exports.logPolicy = logPolicy; exports.operationOptionsToRequestOptionsBase = operationOptionsToRequestOptionsBase; exports.parseXML = parseXML; exports.promiseToCallback = promiseToCallback; exports.promiseToServiceCallback = promiseToServiceCallback; exports.proxyPolicy = proxyPolicy; exports.redirectPolicy = redirectPolicy; exports.serializeObject = serializeObject; exports.signingPolicy = signingPolicy; exports.stringifyXML = stringifyXML; exports.stripRequest = stripRequest; exports.stripResponse = stripResponse; exports.systemErrorRetryPolicy = systemErrorRetryPolicy; exports.throttlingRetryPolicy = throttlingRetryPolicy; exports.tracingPolicy = tracingPolicy; exports.userAgentPolicy = userAgentPolicy; //# sourceMappingURL=index.js.map /***/ }), /***/ 172: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var CombinedStream = __nccwpck_require__(5630); var util = __nccwpck_require__(9023); var path = __nccwpck_require__(6928); var http = __nccwpck_require__(8611); var https = __nccwpck_require__(5692); var parseUrl = (__nccwpck_require__(7016).parse); var fs = __nccwpck_require__(9896); var Stream = (__nccwpck_require__(2203).Stream); var mime = __nccwpck_require__(4096); var asynckit = __nccwpck_require__(1324); var populate = __nccwpck_require__(2209); // Public API module.exports = FormData; // make it a Stream util.inherits(FormData, CombinedStream); /** * Create readable "multipart/form-data" streams. * Can be used to submit forms * and file uploads to other web applications. * * @constructor * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream */ function FormData(options) { if (!(this instanceof FormData)) { return new FormData(options); } this._overheadLength = 0; this._valueLength = 0; this._valuesToMeasure = []; CombinedStream.call(this); options = options || {}; for (var option in options) { this[option] = options[option]; } } FormData.LINE_BREAK = '\r\n'; FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; FormData.prototype.append = function(field, value, options) { options = options || {}; // allow filename as single option if (typeof options == 'string') { options = {filename: options}; } var append = CombinedStream.prototype.append.bind(this); // all that streamy business can't handle numbers if (typeof value == 'number') { value = '' + value; } // https://github.com/felixge/node-form-data/issues/38 if (util.isArray(value)) { // Please convert your array into string // the way web server expects it this._error(new Error('Arrays are not supported.')); return; } var header = this._multiPartHeader(field, value, options); var footer = this._multiPartFooter(); append(header); append(value); append(footer); // pass along options.knownLength this._trackLength(header, value, options); }; FormData.prototype._trackLength = function(header, value, options) { var valueLength = 0; // used w/ getLengthSync(), when length is known. // e.g. for streaming directly from a remote server, // w/ a known file a size, and not wanting to wait for // incoming file to finish to get its size. if (options.knownLength != null) { valueLength += +options.knownLength; } else if (Buffer.isBuffer(value)) { valueLength = value.length; } else if (typeof value === 'string') { valueLength = Buffer.byteLength(value); } this._valueLength += valueLength; // @check why add CRLF? does this account for custom/multiple CRLFs? this._overheadLength += Buffer.byteLength(header) + FormData.LINE_BREAK.length; // empty or either doesn't have path or not an http response or not a stream if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) && !(value instanceof Stream))) { return; } // no need to bother with the length if (!options.knownLength) { this._valuesToMeasure.push(value); } }; FormData.prototype._lengthRetriever = function(value, callback) { if (value.hasOwnProperty('fd')) { // take read range into a account // `end` = Infinity –> read file till the end // // TODO: Looks like there is bug in Node fs.createReadStream // it doesn't respect `end` options without `start` options // Fix it when node fixes it. // https://github.com/joyent/node/issues/7819 if (value.end != undefined && value.end != Infinity && value.start != undefined) { // when end specified // no need to calculate range // inclusive, starts with 0 callback(null, value.end + 1 - (value.start ? value.start : 0)); // not that fast snoopy } else { // still need to fetch file size from fs fs.stat(value.path, function(err, stat) { var fileSize; if (err) { callback(err); return; } // update final size based on the range options fileSize = stat.size - (value.start ? value.start : 0); callback(null, fileSize); }); } // or http response } else if (value.hasOwnProperty('httpVersion')) { callback(null, +value.headers['content-length']); // or request stream http://github.com/mikeal/request } else if (value.hasOwnProperty('httpModule')) { // wait till response come back value.on('response', function(response) { value.pause(); callback(null, +response.headers['content-length']); }); value.resume(); // something else } else { callback('Unknown stream'); } }; FormData.prototype._multiPartHeader = function(field, value, options) { // custom header specified (as string)? // it becomes responsible for boundary // (e.g. to handle extra CRLFs on .NET servers) if (typeof options.header == 'string') { return options.header; } var contentDisposition = this._getContentDisposition(value, options); var contentType = this._getContentType(value, options); var contents = ''; var headers = { // add custom disposition as third element or keep it two elements if not 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), // if no content type. allow it to be empty array 'Content-Type': [].concat(contentType || []) }; // allow custom headers. if (typeof options.header == 'object') { populate(headers, options.header); } var header; for (var prop in headers) { if (!headers.hasOwnProperty(prop)) continue; header = headers[prop]; // skip nullish headers. if (header == null) { continue; } // convert all headers to arrays. if (!Array.isArray(header)) { header = [header]; } // add non-empty headers. if (header.length) { contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; } } return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; }; FormData.prototype._getContentDisposition = function(value, options) { var filename , contentDisposition ; if (typeof options.filepath === 'string') { // custom filepath for relative paths filename = path.normalize(options.filepath).replace(/\\/g, '/'); } else if (options.filename || value.name || value.path) { // custom filename take precedence // formidable and the browser add a name property // fs- and request- streams have path property filename = path.basename(options.filename || value.name || value.path); } else if (value.readable && value.hasOwnProperty('httpVersion')) { // or try http response filename = path.basename(value.client._httpMessage.path || ''); } if (filename) { contentDisposition = 'filename="' + filename + '"'; } return contentDisposition; }; FormData.prototype._getContentType = function(value, options) { // use custom content-type above all var contentType = options.contentType; // or try `name` from formidable, browser if (!contentType && value.name) { contentType = mime.lookup(value.name); } // or try `path` from fs-, request- streams if (!contentType && value.path) { contentType = mime.lookup(value.path); } // or if it's http-reponse if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { contentType = value.headers['content-type']; } // or guess it from the filepath or filename if (!contentType && (options.filepath || options.filename)) { contentType = mime.lookup(options.filepath || options.filename); } // fallback to the default content type if `value` is not simple value if (!contentType && typeof value == 'object') { contentType = FormData.DEFAULT_CONTENT_TYPE; } return contentType; }; FormData.prototype._multiPartFooter = function() { return function(next) { var footer = FormData.LINE_BREAK; var lastPart = (this._streams.length === 0); if (lastPart) { footer += this._lastBoundary(); } next(footer); }.bind(this); }; FormData.prototype._lastBoundary = function() { return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; }; FormData.prototype.getHeaders = function(userHeaders) { var header; var formHeaders = { 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() }; for (header in userHeaders) { if (userHeaders.hasOwnProperty(header)) { formHeaders[header.toLowerCase()] = userHeaders[header]; } } return formHeaders; }; FormData.prototype.setBoundary = function(boundary) { this._boundary = boundary; }; FormData.prototype.getBoundary = function() { if (!this._boundary) { this._generateBoundary(); } return this._boundary; }; FormData.prototype.getBuffer = function() { var dataBuffer = new Buffer.alloc( 0 ); var boundary = this.getBoundary(); // Create the form content. Add Line breaks to the end of data. for (var i = 0, len = this._streams.length; i < len; i++) { if (typeof this._streams[i] !== 'function') { // Add content to the buffer. if(Buffer.isBuffer(this._streams[i])) { dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]); }else { dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]); } // Add break after content. if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) { dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData.LINE_BREAK)] ); } } } // Add the footer and return the Buffer object. return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] ); }; FormData.prototype._generateBoundary = function() { // This generates a 50 character boundary similar to those used by Firefox. // They are optimized for boyer-moore parsing. var boundary = '--------------------------'; for (var i = 0; i < 24; i++) { boundary += Math.floor(Math.random() * 10).toString(16); } this._boundary = boundary; }; // Note: getLengthSync DOESN'T calculate streams length // As workaround one can calculate file size manually // and add it as knownLength option FormData.prototype.getLengthSync = function() { var knownLength = this._overheadLength + this._valueLength; // Don't get confused, there are 3 "internal" streams for each keyval pair // so it basically checks if there is any value added to the form if (this._streams.length) { knownLength += this._lastBoundary().length; } // https://github.com/form-data/form-data/issues/40 if (!this.hasKnownLength()) { // Some async length retrievers are present // therefore synchronous length calculation is false. // Please use getLength(callback) to get proper length this._error(new Error('Cannot calculate proper length in synchronous way.')); } return knownLength; }; // Public API to check if length of added values is known // https://github.com/form-data/form-data/issues/196 // https://github.com/form-data/form-data/issues/262 FormData.prototype.hasKnownLength = function() { var hasKnownLength = true; if (this._valuesToMeasure.length) { hasKnownLength = false; } return hasKnownLength; }; FormData.prototype.getLength = function(cb) { var knownLength = this._overheadLength + this._valueLength; if (this._streams.length) { knownLength += this._lastBoundary().length; } if (!this._valuesToMeasure.length) { process.nextTick(cb.bind(this, null, knownLength)); return; } asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { if (err) { cb(err); return; } values.forEach(function(length) { knownLength += length; }); cb(null, knownLength); }); }; FormData.prototype.submit = function(params, cb) { var request , options , defaults = {method: 'post'} ; // parse provided url if it's string // or treat it as options object if (typeof params == 'string') { params = parseUrl(params); options = populate({ port: params.port, path: params.pathname, host: params.hostname, protocol: params.protocol }, defaults); // use custom params } else { options = populate(params, defaults); // if no port provided use default one if (!options.port) { options.port = options.protocol == 'https:' ? 443 : 80; } } // put that good code in getHeaders to some use options.headers = this.getHeaders(params.headers); // https if specified, fallback to http in any other case if (options.protocol == 'https:') { request = https.request(options); } else { request = http.request(options); } // get content length and fire away this.getLength(function(err, length) { if (err && err !== 'Unknown stream') { this._error(err); return; } // add content length if (length) { request.setHeader('Content-Length', length); } this.pipe(request); if (cb) { var onResponse; var callback = function (error, responce) { request.removeListener('error', callback); request.removeListener('response', onResponse); return cb.call(this, error, responce); }; onResponse = callback.bind(this, null); request.on('error', callback); request.on('response', onResponse); } }.bind(this)); return request; }; FormData.prototype._error = function(err) { if (!this.error) { this.error = err; this.pause(); this.emit('error', err); } }; FormData.prototype.toString = function () { return '[object FormData]'; }; /***/ }), /***/ 2209: /***/ ((module) => { // populates missing values module.exports = function(dst, src) { Object.keys(src).forEach(function(prop) { dst[prop] = dst[prop] || src[prop]; }); return dst; }; /***/ }), /***/ 470: /***/ ((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 __esDecorate; var __runInitializers; var __propKey; var __setFunctionName; 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); } }; __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.push(_); } else if (_ = accept(result)) { if (kind === "field") initializers.push(_); 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) { 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 (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]) { 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: false } : 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("__esDecorate", __esDecorate); exporter("__runInitializers", __runInitializers); exporter("__propKey", __propKey); exporter("__setFunctionName", __setFunctionName); 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); }); /***/ }), /***/ 5862: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); var logger$1 = __nccwpck_require__(4505); var abortController = __nccwpck_require__(8110); // Copyright (c) Microsoft Corporation. /** * The `@azure/logger` configuration for this package. * @internal */ const logger = logger$1.createClientLogger("core-lro"); // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * The default time interval to wait before sending the next polling request. */ const POLL_INTERVAL_IN_MS = 2000; /** * The closed set of terminal states. */ const terminalStates = ["succeeded", "canceled", "failed"]; // Copyright (c) Microsoft Corporation. /** * Deserializes the state */ function deserializeState(serializedState) { try { return JSON.parse(serializedState).state; } catch (e) { throw new Error(`Unable to deserialize input state: ${serializedState}`); } } function setStateError(inputs) { const { state, stateProxy, isOperationError } = inputs; return (error) => { if (isOperationError(error)) { stateProxy.setError(state, error); stateProxy.setFailed(state); } throw error; }; } function processOperationStatus(result) { const { state, stateProxy, status, isDone, processResult, response, setErrorAsResult } = result; switch (status) { case "succeeded": { stateProxy.setSucceeded(state); break; } case "failed": { stateProxy.setError(state, new Error(`The long-running operation has failed`)); stateProxy.setFailed(state); break; } case "canceled": { stateProxy.setCanceled(state); break; } } if ((isDone === null || isDone === void 0 ? void 0 : isDone(response, state)) || (isDone === undefined && ["succeeded", "canceled"].concat(setErrorAsResult ? [] : ["failed"]).includes(status))) { stateProxy.setResult(state, buildResult({ response, state, processResult, })); } } function buildResult(inputs) { const { processResult, response, state } = inputs; return processResult ? processResult(response, state) : response; } /** * Initiates the long-running operation. */ async function initOperation(inputs) { const { init, stateProxy, processResult, getOperationStatus, withOperationLocation, setErrorAsResult, } = inputs; const { operationLocation, resourceLocation, metadata, response } = await init(); if (operationLocation) withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false); const config = { metadata, operationLocation, resourceLocation, }; logger.verbose(`LRO: Operation description:`, config); const state = stateProxy.initState(config); const status = getOperationStatus({ response, state, operationLocation }); processOperationStatus({ state, status, stateProxy, response, setErrorAsResult, processResult }); return state; } async function pollOperationHelper(inputs) { const { poll, state, stateProxy, operationLocation, getOperationStatus, getResourceLocation, isOperationError, options, } = inputs; const response = await poll(operationLocation, options).catch(setStateError({ state, stateProxy, isOperationError, })); const status = getOperationStatus(response, state); logger.verbose(`LRO: Status:\n\tPolling from: ${state.config.operationLocation}\n\tOperation status: ${status}\n\tPolling status: ${terminalStates.includes(status) ? "Stopped" : "Running"}`); if (status === "succeeded") { const resourceLocation = getResourceLocation(response, state); if (resourceLocation !== undefined) { return { response: await poll(resourceLocation).catch(setStateError({ state, stateProxy, isOperationError })), status, }; } } return { response, status }; } /** Polls the long-running operation. */ async function pollOperation(inputs) { const { poll, state, stateProxy, options, getOperationStatus, getResourceLocation, getOperationLocation, isOperationError, withOperationLocation, getPollingInterval, processResult, updateState, setDelay, isDone, setErrorAsResult, } = inputs; const { operationLocation } = state.config; if (operationLocation !== undefined) { const { response, status } = await pollOperationHelper({ poll, getOperationStatus, state, stateProxy, operationLocation, getResourceLocation, isOperationError, options, }); processOperationStatus({ status, response, state, stateProxy, isDone, processResult, setErrorAsResult, }); if (!terminalStates.includes(status)) { const intervalInMs = getPollingInterval === null || getPollingInterval === void 0 ? void 0 : getPollingInterval(response); if (intervalInMs) setDelay(intervalInMs); const location = getOperationLocation === null || getOperationLocation === void 0 ? void 0 : getOperationLocation(response, state); if (location !== undefined) { const isUpdated = operationLocation !== location; state.config.operationLocation = location; withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(location, isUpdated); } else withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false); } updateState === null || updateState === void 0 ? void 0 : updateState(state, response); } } // Copyright (c) Microsoft Corporation. function getOperationLocationPollingUrl(inputs) { const { azureAsyncOperation, operationLocation } = inputs; return operationLocation !== null && operationLocation !== void 0 ? operationLocation : azureAsyncOperation; } function getLocationHeader(rawResponse) { return rawResponse.headers["location"]; } function getOperationLocationHeader(rawResponse) { return rawResponse.headers["operation-location"]; } function getAzureAsyncOperationHeader(rawResponse) { return rawResponse.headers["azure-asyncoperation"]; } function findResourceLocation(inputs) { const { location, requestMethod, requestPath, resourceLocationConfig } = inputs; switch (requestMethod) { case "PUT": { return requestPath; } case "DELETE": { return undefined; } default: { switch (resourceLocationConfig) { case "azure-async-operation": { return undefined; } case "original-uri": { return requestPath; } case "location": default: { return location; } } } } } function inferLroMode(inputs) { const { rawResponse, requestMethod, requestPath, resourceLocationConfig } = inputs; const operationLocation = getOperationLocationHeader(rawResponse); const azureAsyncOperation = getAzureAsyncOperationHeader(rawResponse); const pollingUrl = getOperationLocationPollingUrl({ operationLocation, azureAsyncOperation }); const location = getLocationHeader(rawResponse); const normalizedRequestMethod = requestMethod === null || requestMethod === void 0 ? void 0 : requestMethod.toLocaleUpperCase(); if (pollingUrl !== undefined) { return { mode: "OperationLocation", operationLocation: pollingUrl, resourceLocation: findResourceLocation({ requestMethod: normalizedRequestMethod, location, requestPath, resourceLocationConfig, }), }; } else if (location !== undefined) { return { mode: "ResourceLocation", operationLocation: location, }; } else if (normalizedRequestMethod === "PUT" && requestPath) { return { mode: "Body", operationLocation: requestPath, }; } else { return undefined; } } function transformStatus(inputs) { const { status, statusCode } = inputs; if (typeof status !== "string" && status !== undefined) { throw new Error(`Polling was unsuccessful. Expected status to have a string value or no value but it has instead: ${status}. This doesn't necessarily indicate the operation has failed. Check your Azure subscription or resource status for more information.`); } switch (status === null || status === void 0 ? void 0 : status.toLocaleLowerCase()) { case undefined: return toOperationStatus(statusCode); case "succeeded": return "succeeded"; case "failed": return "failed"; case "running": case "accepted": case "started": case "canceling": case "cancelling": return "running"; case "canceled": case "cancelled": return "canceled"; default: { logger.warning(`LRO: unrecognized operation status: ${status}`); return status; } } } function getStatus(rawResponse) { var _a; const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; return transformStatus({ status, statusCode: rawResponse.statusCode }); } function getProvisioningState(rawResponse) { var _a, _b; const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; const status = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState; return transformStatus({ status, statusCode: rawResponse.statusCode }); } function toOperationStatus(statusCode) { if (statusCode === 202) { return "running"; } else if (statusCode < 300) { return "succeeded"; } else { return "failed"; } } function parseRetryAfter({ rawResponse }) { const retryAfter = rawResponse.headers["retry-after"]; if (retryAfter !== undefined) { // Retry-After header value is either in HTTP date format, or in seconds const retryAfterInSeconds = parseInt(retryAfter); return isNaN(retryAfterInSeconds) ? calculatePollingIntervalFromDate(new Date(retryAfter)) : retryAfterInSeconds * 1000; } return undefined; } function calculatePollingIntervalFromDate(retryAfterDate) { const timeNow = Math.floor(new Date().getTime()); const retryAfterTime = retryAfterDate.getTime(); if (timeNow < retryAfterTime) { return retryAfterTime - timeNow; } return undefined; } function getStatusFromInitialResponse(inputs) { const { response, state, operationLocation } = inputs; function helper() { var _a; const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"]; switch (mode) { case undefined: return toOperationStatus(response.rawResponse.statusCode); case "Body": return getOperationStatus(response, state); default: return "running"; } } const status = helper(); return status === "running" && operationLocation === undefined ? "succeeded" : status; } /** * Initiates the long-running operation. */ async function initHttpOperation(inputs) { const { stateProxy, resourceLocationConfig, processResult, lro, setErrorAsResult } = inputs; return initOperation({ init: async () => { const response = await lro.sendInitialRequest(); const config = inferLroMode({ rawResponse: response.rawResponse, requestPath: lro.requestPath, requestMethod: lro.requestMethod, resourceLocationConfig, }); return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {})); }, stateProxy, processResult: processResult ? ({ flatResponse }, state) => processResult(flatResponse, state) : ({ flatResponse }) => flatResponse, getOperationStatus: getStatusFromInitialResponse, setErrorAsResult, }); } function getOperationLocation({ rawResponse }, state) { var _a; const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"]; switch (mode) { case "OperationLocation": { return getOperationLocationPollingUrl({ operationLocation: getOperationLocationHeader(rawResponse), azureAsyncOperation: getAzureAsyncOperationHeader(rawResponse), }); } case "ResourceLocation": { return getLocationHeader(rawResponse); } case "Body": default: { return undefined; } } } function getOperationStatus({ rawResponse }, state) { var _a; const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"]; switch (mode) { case "OperationLocation": { return getStatus(rawResponse); } case "ResourceLocation": { return toOperationStatus(rawResponse.statusCode); } case "Body": { return getProvisioningState(rawResponse); } default: throw new Error(`Internal error: Unexpected operation mode: ${mode}`); } } function getResourceLocation({ flatResponse }, state) { if (typeof flatResponse === "object") { const resourceLocation = flatResponse.resourceLocation; if (resourceLocation !== undefined) { state.config.resourceLocation = resourceLocation; } } return state.config.resourceLocation; } function isOperationError(e) { return e.name === "RestError"; } /** Polls the long-running operation. */ async function pollHttpOperation(inputs) { const { lro, stateProxy, options, processResult, updateState, setDelay, state, setErrorAsResult, } = inputs; return pollOperation({ state, stateProxy, setDelay, processResult: processResult ? ({ flatResponse }, inputState) => processResult(flatResponse, inputState) : ({ flatResponse }) => flatResponse, updateState, getPollingInterval: parseRetryAfter, getOperationLocation, getOperationStatus, isOperationError, getResourceLocation, options, /** * The expansion here is intentional because `lro` could be an object that * references an inner this, so we need to preserve a reference to it. */ poll: async (location, inputOptions) => lro.sendPollRequest(location, inputOptions), setErrorAsResult, }); } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * Map an optional value through a function * @internal */ const maybemap = (value, f) => value === undefined ? undefined : f(value); const INTERRUPTED = new Error("The poller is already stopped"); /** * A promise that delays resolution until a certain amount of time (in milliseconds) has passed, with facilities for * robust cancellation. * * ### Example: * * ```javascript * let toCancel; * * // Wait 20 seconds, and optionally allow the function to be cancelled. * await delayMs(20000, (cancel) => { toCancel = cancel }); * * // ... if `toCancel` is called before the 20 second timer expires, then the delayMs promise will reject. * ``` * * @internal * @param ms - the number of milliseconds to wait before resolving * @param cb - a callback that can provide the caller with a cancellation function */ function delayMs(ms) { let aborted = false; let toReject; return Object.assign(new Promise((resolve, reject) => { let token; toReject = () => { maybemap(token, clearTimeout); reject(INTERRUPTED); }; // In the rare case that the operation is _already_ aborted, we will reject instantly. This could happen, for // example, if the user calls the cancellation function immediately without yielding execution. if (aborted) { toReject(); } else { token = setTimeout(resolve, ms); } }), { cancel: () => { aborted = true; toReject === null || toReject === void 0 ? void 0 : toReject(); }, }); } // Copyright (c) Microsoft Corporation. const createStateProxy$1 = () => ({ /** * The state at this point is created to be of type OperationState. * It will be updated later to be of type TState when the * customer-provided callback, `updateState`, is called during polling. */ initState: (config) => ({ status: "running", config }), setCanceled: (state) => (state.status = "canceled"), setError: (state, error) => (state.error = error), setResult: (state, result) => (state.result = result), setRunning: (state) => (state.status = "running"), setSucceeded: (state) => (state.status = "succeeded"), setFailed: (state) => (state.status = "failed"), getError: (state) => state.error, getResult: (state) => state.result, isCanceled: (state) => state.status === "canceled", isFailed: (state) => state.status === "failed", isRunning: (state) => state.status === "running", isSucceeded: (state) => state.status === "succeeded", }); /** * Returns a poller factory. */ function buildCreatePoller(inputs) { const { getOperationLocation, getStatusFromInitialResponse, getStatusFromPollResponse, isOperationError, getResourceLocation, getPollingInterval, resolveOnUnsuccessful, } = inputs; return async ({ init, poll }, options) => { const { processResult, updateState, withOperationLocation: withOperationLocationCallback, intervalInMs = POLL_INTERVAL_IN_MS, restoreFrom, } = options || {}; const stateProxy = createStateProxy$1(); const withOperationLocation = withOperationLocationCallback ? (() => { let called = false; return (operationLocation, isUpdated) => { if (isUpdated) withOperationLocationCallback(operationLocation); else if (!called) withOperationLocationCallback(operationLocation); called = true; }; })() : undefined; const state = restoreFrom ? deserializeState(restoreFrom) : await initOperation({ init, stateProxy, processResult, getOperationStatus: getStatusFromInitialResponse, withOperationLocation, setErrorAsResult: !resolveOnUnsuccessful, }); let resultPromise; let cancelJob; const abortController$1 = new abortController.AbortController(); const handlers = new Map(); const handleProgressEvents = async () => handlers.forEach((h) => h(state)); const cancelErrMsg = "Operation was canceled"; let currentPollIntervalInMs = intervalInMs; const poller = { getOperationState: () => state, getResult: () => state.result, isDone: () => ["succeeded", "failed", "canceled"].includes(state.status), isStopped: () => resultPromise === undefined, stopPolling: () => { abortController$1.abort(); cancelJob === null || cancelJob === void 0 ? void 0 : cancelJob(); }, toString: () => JSON.stringify({ state, }), onProgress: (callback) => { const s = Symbol(); handlers.set(s, callback); return () => handlers.delete(s); }, pollUntilDone: (pollOptions) => (resultPromise !== null && resultPromise !== void 0 ? resultPromise : (resultPromise = (async () => { const { abortSignal: inputAbortSignal } = pollOptions || {}; const { signal: abortSignal } = inputAbortSignal ? new abortController.AbortController([inputAbortSignal, abortController$1.signal]) : abortController$1; if (!poller.isDone()) { await poller.poll({ abortSignal }); while (!poller.isDone()) { const delay = delayMs(currentPollIntervalInMs); cancelJob = delay.cancel; await delay; await poller.poll({ abortSignal }); } } if (resolveOnUnsuccessful) { return poller.getResult(); } else { switch (state.status) { case "succeeded": return poller.getResult(); case "canceled": throw new Error(cancelErrMsg); case "failed": throw state.error; case "notStarted": case "running": throw new Error(`Polling completed without succeeding or failing`); } } })().finally(() => { resultPromise = undefined; }))), async poll(pollOptions) { if (resolveOnUnsuccessful) { if (poller.isDone()) return; } else { switch (state.status) { case "succeeded": return; case "canceled": throw new Error(cancelErrMsg); case "failed": throw state.error; } } await pollOperation({ poll, state, stateProxy, getOperationLocation, isOperationError, withOperationLocation, getPollingInterval, getOperationStatus: getStatusFromPollResponse, getResourceLocation, processResult, updateState, options: pollOptions, setDelay: (pollIntervalInMs) => { currentPollIntervalInMs = pollIntervalInMs; }, setErrorAsResult: !resolveOnUnsuccessful, }); await handleProgressEvents(); if (!resolveOnUnsuccessful) { switch (state.status) { case "canceled": throw new Error(cancelErrMsg); case "failed": throw state.error; } } }, }; return poller; }; } // Copyright (c) Microsoft Corporation. /** * Creates a poller that can be used to poll a long-running operation. * @param lro - Description of the long-running operation * @param options - options to configure the poller * @returns an initialized poller */ async function createHttpPoller(lro, options) { const { resourceLocationConfig, intervalInMs, processResult, restoreFrom, updateState, withOperationLocation, resolveOnUnsuccessful = false, } = options || {}; return buildCreatePoller({ getStatusFromInitialResponse, getStatusFromPollResponse: getOperationStatus, isOperationError, getOperationLocation, getResourceLocation, getPollingInterval: parseRetryAfter, resolveOnUnsuccessful, })({ init: async () => { const response = await lro.sendInitialRequest(); const config = inferLroMode({ rawResponse: response.rawResponse, requestPath: lro.requestPath, requestMethod: lro.requestMethod, resourceLocationConfig, }); return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {})); }, poll: lro.sendPollRequest, }, { intervalInMs, withOperationLocation, restoreFrom, updateState, processResult: processResult ? ({ flatResponse }, state) => processResult(flatResponse, state) : ({ flatResponse }) => flatResponse, }); } // Copyright (c) Microsoft Corporation. const createStateProxy = () => ({ initState: (config) => ({ config, isStarted: true }), setCanceled: (state) => (state.isCancelled = true), setError: (state, error) => (state.error = error), setResult: (state, result) => (state.result = result), setRunning: (state) => (state.isStarted = true), setSucceeded: (state) => (state.isCompleted = true), setFailed: () => { /** empty body */ }, getError: (state) => state.error, getResult: (state) => state.result, isCanceled: (state) => !!state.isCancelled, isFailed: (state) => !!state.error, isRunning: (state) => !!state.isStarted, isSucceeded: (state) => Boolean(state.isCompleted && !state.isCancelled && !state.error), }); class GenericPollOperation { constructor(state, lro, setErrorAsResult, lroResourceLocationConfig, processResult, updateState, isDone) { this.state = state; this.lro = lro; this.setErrorAsResult = setErrorAsResult; this.lroResourceLocationConfig = lroResourceLocationConfig; this.processResult = processResult; this.updateState = updateState; this.isDone = isDone; } setPollerConfig(pollerConfig) { this.pollerConfig = pollerConfig; } async update(options) { var _a; const stateProxy = createStateProxy(); if (!this.state.isStarted) { this.state = Object.assign(Object.assign({}, this.state), (await initHttpOperation({ lro: this.lro, stateProxy, resourceLocationConfig: this.lroResourceLocationConfig, processResult: this.processResult, setErrorAsResult: this.setErrorAsResult, }))); } const updateState = this.updateState; const isDone = this.isDone; if (!this.state.isCompleted && this.state.error === undefined) { await pollHttpOperation({ lro: this.lro, state: this.state, stateProxy, processResult: this.processResult, updateState: updateState ? (state, { rawResponse }) => updateState(state, rawResponse) : undefined, isDone: isDone ? ({ flatResponse }, state) => isDone(flatResponse, state) : undefined, options, setDelay: (intervalInMs) => { this.pollerConfig.intervalInMs = intervalInMs; }, setErrorAsResult: this.setErrorAsResult, }); } (_a = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _a === void 0 ? void 0 : _a.call(options, this.state); return this; } async cancel() { logger.error("`cancelOperation` is deprecated because it wasn't implemented"); return this; } /** * Serializes the Poller operation. */ toString() { return JSON.stringify({ state: this.state, }); } } // 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 the operation is cancelled, 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) { /** controls whether to throw an error if the operation failed or was canceled. */ this.resolveOnUnsuccessful = false; 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(pollOptions = {}) { if (this.stopped) { this.stopped = false; } while (!this.isStopped() && !this.isDone()) { await this.poll(pollOptions); await this.delay(); } } /** * 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 = {}) { if (!this.isDone()) { this.operation = await this.operation.update({ abortSignal: options.abortSignal, fireProgress: this.fireProgress.bind(this), }); } this.processUpdatedState(); } /** * 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. */ async cancelOnce(options = {}) { this.operation = await this.operation.cancel(options); } /** * 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; } processUpdatedState() { if (this.operation.state.error) { this.stopped = true; if (!this.resolveOnUnsuccessful) { this.reject(this.operation.state.error); throw this.operation.state.error; } } if (this.operation.state.isCancelled) { this.stopped = true; if (!this.resolveOnUnsuccessful) { const error = new PollerCancelledError("Operation was canceled"); this.reject(error); throw error; } } 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.getResult()); } } /** * Returns a promise that will resolve once the underlying operation is completed. */ async pollUntilDone(pollOptions = {}) { if (this.stopped) { this.startPolling(pollOptions).catch(this.reject); } // This is needed because the state could have been updated by // `cancelOperation`, e.g. the operation is canceled or an error occurred. this.processUpdatedState(); 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); }; } /** * 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.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. /** * The LRO Engine, a class that performs polling. */ class LroEngine extends Poller { constructor(lro, options) { const { intervalInMs = POLL_INTERVAL_IN_MS, resumeFrom, resolveOnUnsuccessful = false, isDone, lroResourceLocationConfig, processResult, updateState, } = options || {}; const state = resumeFrom ? deserializeState(resumeFrom) : {}; const operation = new GenericPollOperation(state, lro, !resolveOnUnsuccessful, lroResourceLocationConfig, processResult, updateState, isDone); super(operation); this.resolveOnUnsuccessful = resolveOnUnsuccessful; 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.LroEngine = LroEngine; exports.Poller = Poller; exports.PollerCancelledError = PollerCancelledError; exports.PollerStoppedError = PollerStoppedError; exports.createHttpPoller = createHttpPoller; //# sourceMappingURL=index.js.map /***/ }), /***/ 9851: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); var tslib = __nccwpck_require__(6654); // 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. * * @param pagedResult - an object that specifies how to get pages. * @returns a paged async iterator that iterates over results. */ 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, e_2, _b; 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)) { // can extract elements from this page const { toElements } = pagedResult; if (toElements) { yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(toElements(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; yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(toElements(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; } } } else { 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_2 = tslib.__asyncValues(pages), pages_2_1; pages_2_1 = yield tslib.__await(pages_2.next()), !pages_2_1.done;) { const page = pages_2_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_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (pages_2_1 && !pages_2_1.done && (_b = pages_2.return)) yield tslib.__await(_b.call(pages_2)); } finally { if (e_2) throw e_2.error; } } } }); } 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)); if (!response) { return yield tslib.__await(void 0); } yield yield tslib.__await(response.page); while (response.nextPageLink) { response = yield tslib.__await(pagedResult.getPage(response.nextPageLink, maxPageSize)); if (!response) { return yield tslib.__await(void 0); } yield yield tslib.__await(response.page); } }); } exports.getPagedAsyncIterator = getPagedAsyncIterator; //# sourceMappingURL=index.js.map /***/ }), /***/ 6654: /***/ ((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 __esDecorate; var __runInitializers; var __propKey; var __setFunctionName; 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); } }; __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.push(_); } else if (_ = accept(result)) { if (kind === "field") initializers.push(_); 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) { 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 (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]) { 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: false } : 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("__esDecorate", __esDecorate); exporter("__runInitializers", __runInitializers); exporter("__propKey", __propKey); exporter("__setFunctionName", __setFunctionName); 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); }); /***/ }), /***/ 5553: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); var api = __nccwpck_require__(3914); // 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 azureTracingDisabledValue = (_a = process.env.AZURE_TRACING_DISABLED) === null || _a === void 0 ? void 0 : _a.toLowerCase(); if (azureTracingDisabledValue === "false" || azureTracingDisabledValue === "0") { return false; } 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 /***/ }), /***/ 8735: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); var abortController = __nccwpck_require__(8110); var crypto = __nccwpck_require__(6982); // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. var _a; /** * A constant that indicates whether the environment the code is running is Node.JS. */ const isNode = typeof process !== "undefined" && Boolean(process.version) && Boolean((_a = process.versions) === null || _a === void 0 ? void 0 : _a.node); // Copyright (c) Microsoft Corporation. /** * Creates an abortable promise. * @param buildPromise - A function that takes the resolve and reject functions as parameters. * @param options - The options for the abortable promise. * @returns A promise that can be aborted. */ function createAbortablePromise(buildPromise, options) { const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; return new Promise((resolve, reject) => { function rejectOnAbort() { reject(new abortController.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted.")); } function removeListeners() { abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort); } function onAbort() { cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort(); removeListeners(); rejectOnAbort(); } if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) { return rejectOnAbort(); } try { buildPromise((x) => { removeListeners(); resolve(x); }, (x) => { removeListeners(); reject(x); }); } catch (err) { reject(err); } abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort); }); } // Copyright (c) Microsoft Corporation. const StandardAbortMessage = "The delay was aborted."; /** * A wrapper for setTimeout that resolves a promise after timeInMs milliseconds. * @param timeInMs - The number of milliseconds to be delayed. * @param options - The options for delay - currently abort options * @returns Promise that is resolved after timeInMs */ function delay(timeInMs, options) { let token; const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; return createAbortablePromise((resolve) => { token = setTimeout(resolve, timeInMs); }, { cleanupBeforeAbort: () => clearTimeout(token), abortSignal, abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage, }); } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * Returns a random integer value between a lower and upper bound, * inclusive of both bounds. * Note that this uses Math.random and isn't secure. If you need to use * this for any kind of security purpose, find a better source of random. * @param min - The smallest integer value allowed. * @param max - The largest integer value allowed. */ function getRandomIntegerInclusive(min, max) { // Make sure inputs are integers. min = Math.ceil(min); max = Math.floor(max); // Pick a random offset from zero to the size of the range. // Since Math.random() can never return 1, we have to make the range one larger // in order to be inclusive of the maximum value after we take the floor. const offset = Math.floor(Math.random() * (max - min + 1)); return offset + min; } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * Helper to determine when an input is a generic JS object. * @returns true when input is an object type that is not null, Array, RegExp, or Date. */ function isObject(input) { return (typeof input === "object" && input !== null && !Array.isArray(input) && !(input instanceof RegExp) && !(input instanceof Date)); } // Copyright (c) Microsoft Corporation. /** * Typeguard for an error object shape (has name and message) * @param e - Something caught by a catch clause. */ function isError(e) { if (isObject(e)) { const hasName = typeof e.name === "string"; const hasMessage = typeof e.message === "string"; return hasName && hasMessage; } return false; } /** * Given what is thought to be an error object, return the message if possible. * If the message is missing, returns a stringified version of the input. * @param e - Something thrown from a try block * @returns The error message or a string of the input */ function getErrorMessage(e) { if (isError(e)) { return e.message; } else { let stringified; try { if (typeof e === "object" && e) { stringified = JSON.stringify(e); } else { stringified = String(e); } } catch (err) { stringified = "[unable to stringify input]"; } return `Unknown error ${stringified}`; } } // Copyright (c) Microsoft Corporation. /** * Generates a SHA-256 HMAC signature. * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash. * @param stringToSign - The data to be signed. * @param encoding - The textual encoding to use for the returned HMAC digest. */ async function computeSha256Hmac(key, stringToSign, encoding) { const decodedKey = Buffer.from(key, "base64"); return crypto.createHmac("sha256", decodedKey).update(stringToSign).digest(encoding); } /** * Generates a SHA-256 hash. * @param content - The data to be included in the hash. * @param encoding - The textual encoding to use for the returned hash. */ async function computeSha256Hash(content, encoding) { return crypto.createHash("sha256").update(content).digest(encoding); } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * Helper TypeGuard that checks if something is defined or not. * @param thing - Anything */ function isDefined(thing) { return typeof thing !== "undefined" && thing !== null; } /** * Helper TypeGuard that checks if the input is an object with the specified properties. * @param thing - Anything. * @param properties - The name of the properties that should appear in the object. */ function isObjectWithProperties(thing, properties) { if (!isDefined(thing) || typeof thing !== "object") { return false; } for (const property of properties) { if (!objectHasProperty(thing, property)) { return false; } } return true; } /** * Helper TypeGuard that checks if the input is an object with the specified property. * @param thing - Any object. * @param property - The name of the property that should appear in the object. */ function objectHasProperty(thing, property) { return (isDefined(thing) && typeof thing === "object" && property in thing); } exports.computeSha256Hash = computeSha256Hash; exports.computeSha256Hmac = computeSha256Hmac; exports.createAbortablePromise = createAbortablePromise; exports.delay = delay; exports.getErrorMessage = getErrorMessage; exports.getRandomIntegerInclusive = getRandomIntegerInclusive; exports.isDefined = isDefined; exports.isError = isError; exports.isNode = isNode; exports.isObject = isObject; exports.isObjectWithProperties = isObjectWithProperties; exports.objectHasProperty = objectHasProperty; //# sourceMappingURL=index.js.map /***/ }), /***/ 4505: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); var os = __nccwpck_require__(857); var util = __nccwpck_require__(9023); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var util__default = /*#__PURE__*/_interopDefaultLegacy(util); // Copyright (c) Microsoft Corporation. function log(message, ...args) { process.stderr.write(`${util__default["default"].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; } var debug = debugObj; // 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 = debug("azure"); AzureLogger.log = (...args) => { debug.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. If no level is specified, logging is disabled. * @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); } } debug.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 = debug.disable(); debug.enable(enabledNamespaces + "," + logger.namespace); } registeredLoggers.add(logger); return logger; } function shouldEnable(logger) { return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]); } 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 /***/ }), /***/ 1012: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); var coreHttp = __nccwpck_require__(9283); var tslib = __nccwpck_require__(3849); var coreTracing = __nccwpck_require__(5553); var logger$1 = __nccwpck_require__(4505); var abortController = __nccwpck_require__(8110); var os = __nccwpck_require__(857); var crypto = __nccwpck_require__(6982); var stream = __nccwpck_require__(2203); __nccwpck_require__(9851); var coreLro = __nccwpck_require__(5862); var events = __nccwpck_require__(4434); var fs = __nccwpck_require__(9896); var util = __nccwpck_require__(9023); 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: { 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" } } } } }; 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" } } } } }; 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" } } } } }; 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", type: { name: "DateTimeRfc1123" } } } } }; const ListContainersSegmentResponse = { serializedName: "ListContainersSegmentResponse", xmlName: "EnumerationResults", type: { name: "Composite", className: "ListContainersSegmentResponse", modelProperties: { serviceEndpoint: { serializedName: "ServiceEndpoint", required: true, xmlName: "ServiceEndpoint", xmlIsAttribute: true, type: { name: "String" } }, prefix: { serializedName: "Prefix", xmlName: "Prefix", type: { name: "String" } }, marker: { serializedName: "Marker", xmlName: "Marker", type: { name: "String" } }, maxPageSize: { serializedName: "MaxResults", xmlName: "MaxResults", type: { name: "Number" } }, containerItems: { serializedName: "ContainerItems", required: true, xmlName: "Containers", xmlIsWrapped: true, xmlElementName: "Container", type: { name: "Sequence", element: { type: { name: "Composite", className: "ContainerItem" } } } }, continuationToken: { serializedName: "NextMarker", xmlName: "NextMarker", type: { name: "String" } } } } }; const ContainerItem = { serializedName: "ContainerItem", xmlName: "Container", type: { name: "Composite", className: "ContainerItem", modelProperties: { name: { serializedName: "Name", required: true, xmlName: "Name", type: { name: "String" } }, deleted: { serializedName: "Deleted", xmlName: "Deleted", type: { name: "Boolean" } }, version: { serializedName: "Version", xmlName: "Version", type: { name: "String" } }, properties: { serializedName: "Properties", xmlName: "Properties", type: { name: "Composite", className: "ContainerProperties" } }, metadata: { serializedName: "Metadata", xmlName: "Metadata", type: { name: "Dictionary", value: { type: { name: "String" } } } } } } }; const ContainerProperties = { serializedName: "ContainerProperties", type: { name: "Composite", className: "ContainerProperties", modelProperties: { lastModified: { serializedName: "Last-Modified", required: true, xmlName: "Last-Modified", type: { name: "DateTimeRfc1123" } }, etag: { serializedName: "Etag", required: true, xmlName: "Etag", type: { name: "String" } }, leaseStatus: { serializedName: "LeaseStatus", xmlName: "LeaseStatus", type: { name: "Enum", allowedValues: ["locked", "unlocked"] } }, leaseState: { serializedName: "LeaseState", xmlName: "LeaseState", type: { name: "Enum", allowedValues: [ "available", "leased", "expired", "breaking", "broken" ] } }, leaseDuration: { serializedName: "LeaseDuration", xmlName: "LeaseDuration", type: { name: "Enum", allowedValues: ["infinite", "fixed"] } }, publicAccess: { serializedName: "PublicAccess", xmlName: "PublicAccess", type: { name: "Enum", allowedValues: ["container", "blob"] } }, hasImmutabilityPolicy: { serializedName: "HasImmutabilityPolicy", xmlName: "HasImmutabilityPolicy", type: { name: "Boolean" } }, hasLegalHold: { serializedName: "HasLegalHold", xmlName: "HasLegalHold", type: { name: "Boolean" } }, defaultEncryptionScope: { serializedName: "DefaultEncryptionScope", xmlName: "DefaultEncryptionScope", type: { name: "String" } }, preventEncryptionScopeOverride: { serializedName: "DenyEncryptionScopeOverride", xmlName: "DenyEncryptionScopeOverride", type: { name: "Boolean" } }, deletedOn: { serializedName: "DeletedTime", xmlName: "DeletedTime", type: { name: "DateTimeRfc1123" } }, remainingRetentionDays: { serializedName: "RemainingRetentionDays", xmlName: "RemainingRetentionDays", type: { name: "Number" } }, isImmutableStorageWithVersioningEnabled: { serializedName: "ImmutableStorageWithVersioningEnabled", xmlName: "ImmutableStorageWithVersioningEnabled", type: { name: "Boolean" } } } } }; const KeyInfo = { serializedName: "KeyInfo", type: { name: "Composite", className: "KeyInfo", modelProperties: { startsOn: { serializedName: "Start", required: true, xmlName: "Start", type: { name: "String" } }, expiresOn: { serializedName: "Expiry", required: true, xmlName: "Expiry", type: { name: "String" } } } } }; const UserDelegationKey = { serializedName: "UserDelegationKey", type: { name: "Composite", className: "UserDelegationKey", modelProperties: { signedObjectId: { serializedName: "SignedOid", required: true, xmlName: "SignedOid", type: { name: "String" } }, signedTenantId: { serializedName: "SignedTid", required: true, xmlName: "SignedTid", type: { name: "String" } }, signedStartsOn: { serializedName: "SignedStart", required: true, xmlName: "SignedStart", type: { name: "String" } }, signedExpiresOn: { serializedName: "SignedExpiry", required: true, xmlName: "SignedExpiry", type: { name: "String" } }, signedService: { serializedName: "SignedService", required: true, xmlName: "SignedService", type: { name: "String" } }, signedVersion: { serializedName: "SignedVersion", required: true, xmlName: "SignedVersion", type: { name: "String" } }, value: { serializedName: "Value", required: true, xmlName: "Value", type: { name: "String" } } } } }; const FilterBlobSegment = { serializedName: "FilterBlobSegment", xmlName: "EnumerationResults", type: { name: "Composite", className: "FilterBlobSegment", modelProperties: { serviceEndpoint: { serializedName: "ServiceEndpoint", required: true, xmlName: "ServiceEndpoint", xmlIsAttribute: true, type: { name: "String" } }, where: { serializedName: "Where", required: true, xmlName: "Where", type: { name: "String" } }, blobs: { serializedName: "Blobs", required: true, xmlName: "Blobs", xmlIsWrapped: true, xmlElementName: "Blob", type: { name: "Sequence", element: { type: { name: "Composite", className: "FilterBlobItem" } } } }, continuationToken: { serializedName: "NextMarker", xmlName: "NextMarker", type: { name: "String" } } } } }; const FilterBlobItem = { serializedName: "FilterBlobItem", xmlName: "Blob", type: { name: "Composite", className: "FilterBlobItem", modelProperties: { name: { serializedName: "Name", required: true, xmlName: "Name", type: { name: "String" } }, containerName: { serializedName: "ContainerName", required: true, xmlName: "ContainerName", type: { name: "String" } }, tags: { serializedName: "Tags", xmlName: "Tags", type: { name: "Composite", className: "BlobTags" } } } } }; const BlobTags = { serializedName: "BlobTags", xmlName: "Tags", type: { name: "Composite", className: "BlobTags", modelProperties: { blobTagSet: { serializedName: "BlobTagSet", required: true, xmlName: "TagSet", xmlIsWrapped: true, xmlElementName: "Tag", type: { name: "Sequence", element: { type: { name: "Composite", className: "BlobTag" } } } } } } }; const BlobTag = { serializedName: "BlobTag", xmlName: "Tag", type: { name: "Composite", className: "BlobTag", modelProperties: { key: { serializedName: "Key", required: true, xmlName: "Key", type: { name: "String" } }, value: { serializedName: "Value", required: true, xmlName: "Value", type: { name: "String" } } } } }; const SignedIdentifier = { serializedName: "SignedIdentifier", xmlName: "SignedIdentifier", type: { name: "Composite", className: "SignedIdentifier", modelProperties: { id: { serializedName: "Id", required: true, xmlName: "Id", type: { name: "String" } }, accessPolicy: { serializedName: "AccessPolicy", xmlName: "AccessPolicy", type: { name: "Composite", className: "AccessPolicy" } } } } }; const AccessPolicy = { serializedName: "AccessPolicy", type: { name: "Composite", className: "AccessPolicy", modelProperties: { startsOn: { serializedName: "Start", xmlName: "Start", type: { name: "String" } }, expiresOn: { serializedName: "Expiry", xmlName: "Expiry", type: { name: "String" } }, permissions: { serializedName: "Permission", xmlName: "Permission", type: { name: "String" } } } } }; const ListBlobsFlatSegmentResponse = { serializedName: "ListBlobsFlatSegmentResponse", xmlName: "EnumerationResults", type: { name: "Composite", className: "ListBlobsFlatSegmentResponse", modelProperties: { serviceEndpoint: { serializedName: "ServiceEndpoint", required: true, xmlName: "ServiceEndpoint", xmlIsAttribute: true, type: { name: "String" } }, containerName: { serializedName: "ContainerName", required: true, xmlName: "ContainerName", xmlIsAttribute: true, type: { name: "String" } }, prefix: { serializedName: "Prefix", xmlName: "Prefix", type: { name: "String" } }, marker: { serializedName: "Marker", xmlName: "Marker", type: { name: "String" } }, maxPageSize: { serializedName: "MaxResults", xmlName: "MaxResults", type: { name: "Number" } }, segment: { serializedName: "Segment", xmlName: "Blobs", type: { name: "Composite", className: "BlobFlatListSegment" } }, continuationToken: { serializedName: "NextMarker", xmlName: "NextMarker", type: { name: "String" } } } } }; const BlobFlatListSegment = { serializedName: "BlobFlatListSegment", xmlName: "Blobs", type: { name: "Composite", className: "BlobFlatListSegment", modelProperties: { blobItems: { serializedName: "BlobItems", required: true, xmlName: "BlobItems", xmlElementName: "Blob", type: { name: "Sequence", element: { type: { name: "Composite", className: "BlobItemInternal" } } } } } } }; const BlobItemInternal = { serializedName: "BlobItemInternal", xmlName: "Blob", type: { name: "Composite", className: "BlobItemInternal", modelProperties: { name: { serializedName: "Name", xmlName: "Name", type: { name: "Composite", className: "BlobName" } }, deleted: { serializedName: "Deleted", required: true, xmlName: "Deleted", type: { name: "Boolean" } }, snapshot: { serializedName: "Snapshot", required: true, xmlName: "Snapshot", type: { name: "String" } }, versionId: { serializedName: "VersionId", xmlName: "VersionId", type: { name: "String" } }, isCurrentVersion: { serializedName: "IsCurrentVersion", xmlName: "IsCurrentVersion", type: { name: "Boolean" } }, properties: { serializedName: "Properties", xmlName: "Properties", type: { name: "Composite", className: "BlobPropertiesInternal" } }, metadata: { serializedName: "Metadata", xmlName: "Metadata", type: { name: "Dictionary", value: { type: { name: "String" } } } }, blobTags: { serializedName: "BlobTags", xmlName: "Tags", type: { name: "Composite", className: "BlobTags" } }, objectReplicationMetadata: { serializedName: "ObjectReplicationMetadata", xmlName: "OrMetadata", type: { name: "Dictionary", value: { type: { name: "String" } } } }, hasVersionsOnly: { serializedName: "HasVersionsOnly", xmlName: "HasVersionsOnly", type: { name: "Boolean" } } } } }; const BlobName = { serializedName: "BlobName", type: { name: "Composite", className: "BlobName", modelProperties: { encoded: { serializedName: "Encoded", xmlName: "Encoded", xmlIsAttribute: true, type: { name: "Boolean" } }, content: { serializedName: "content", xmlName: "content", xmlIsMsText: true, type: { name: "String" } } } } }; const BlobPropertiesInternal = { serializedName: "BlobPropertiesInternal", xmlName: "Properties", type: { name: "Composite", className: "BlobPropertiesInternal", modelProperties: { createdOn: { serializedName: "Creation-Time", xmlName: "Creation-Time", type: { name: "DateTimeRfc1123" } }, lastModified: { serializedName: "Last-Modified", required: true, xmlName: "Last-Modified", type: { name: "DateTimeRfc1123" } }, etag: { serializedName: "Etag", required: true, xmlName: "Etag", type: { name: "String" } }, contentLength: { serializedName: "Content-Length", xmlName: "Content-Length", type: { name: "Number" } }, contentType: { serializedName: "Content-Type", xmlName: "Content-Type", type: { name: "String" } }, contentEncoding: { serializedName: "Content-Encoding", xmlName: "Content-Encoding", type: { name: "String" } }, contentLanguage: { serializedName: "Content-Language", xmlName: "Content-Language", type: { name: "String" } }, contentMD5: { serializedName: "Content-MD5", xmlName: "Content-MD5", type: { name: "ByteArray" } }, contentDisposition: { serializedName: "Content-Disposition", xmlName: "Content-Disposition", type: { name: "String" } }, cacheControl: { serializedName: "Cache-Control", xmlName: "Cache-Control", type: { name: "String" } }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", xmlName: "x-ms-blob-sequence-number", type: { name: "Number" } }, blobType: { serializedName: "BlobType", xmlName: "BlobType", type: { name: "Enum", allowedValues: ["BlockBlob", "PageBlob", "AppendBlob"] } }, leaseStatus: { serializedName: "LeaseStatus", xmlName: "LeaseStatus", type: { name: "Enum", allowedValues: ["locked", "unlocked"] } }, leaseState: { serializedName: "LeaseState", xmlName: "LeaseState", type: { name: "Enum", allowedValues: [ "available", "leased", "expired", "breaking", "broken" ] } }, leaseDuration: { serializedName: "LeaseDuration", xmlName: "LeaseDuration", type: { name: "Enum", allowedValues: ["infinite", "fixed"] } }, copyId: { serializedName: "CopyId", xmlName: "CopyId", type: { name: "String" } }, copyStatus: { serializedName: "CopyStatus", xmlName: "CopyStatus", type: { name: "Enum", allowedValues: ["pending", "success", "aborted", "failed"] } }, copySource: { serializedName: "CopySource", xmlName: "CopySource", type: { name: "String" } }, copyProgress: { serializedName: "CopyProgress", xmlName: "CopyProgress", type: { name: "String" } }, copyCompletedOn: { serializedName: "CopyCompletionTime", xmlName: "CopyCompletionTime", type: { name: "DateTimeRfc1123" } }, copyStatusDescription: { serializedName: "CopyStatusDescription", xmlName: "CopyStatusDescription", type: { name: "String" } }, serverEncrypted: { serializedName: "ServerEncrypted", xmlName: "ServerEncrypted", type: { name: "Boolean" } }, incrementalCopy: { serializedName: "IncrementalCopy", xmlName: "IncrementalCopy", type: { name: "Boolean" } }, destinationSnapshot: { serializedName: "DestinationSnapshot", xmlName: "DestinationSnapshot", type: { name: "String" } }, deletedOn: { serializedName: "DeletedTime", xmlName: "DeletedTime", type: { name: "DateTimeRfc1123" } }, remainingRetentionDays: { serializedName: "RemainingRetentionDays", xmlName: "RemainingRetentionDays", type: { name: "Number" } }, accessTier: { serializedName: "AccessTier", xmlName: "AccessTier", type: { name: "Enum", allowedValues: [ "P4", "P6", "P10", "P15", "P20", "P30", "P40", "P50", "P60", "P70", "P80", "Hot", "Cool", "Archive", "Cold" ] } }, accessTierInferred: { serializedName: "AccessTierInferred", xmlName: "AccessTierInferred", type: { name: "Boolean" } }, archiveStatus: { serializedName: "ArchiveStatus", xmlName: "ArchiveStatus", type: { name: "Enum", allowedValues: [ "rehydrate-pending-to-hot", "rehydrate-pending-to-cool" ] } }, customerProvidedKeySha256: { serializedName: "CustomerProvidedKeySha256", xmlName: "CustomerProvidedKeySha256", type: { name: "String" } }, encryptionScope: { serializedName: "EncryptionScope", xmlName: "EncryptionScope", type: { name: "String" } }, accessTierChangedOn: { serializedName: "AccessTierChangeTime", xmlName: "AccessTierChangeTime", type: { name: "DateTimeRfc1123" } }, tagCount: { serializedName: "TagCount", xmlName: "TagCount", type: { name: "Number" } }, expiresOn: { serializedName: "Expiry-Time", xmlName: "Expiry-Time", type: { name: "DateTimeRfc1123" } }, isSealed: { serializedName: "Sealed", xmlName: "Sealed", type: { name: "Boolean" } }, rehydratePriority: { serializedName: "RehydratePriority", xmlName: "RehydratePriority", type: { name: "Enum", allowedValues: ["High", "Standard"] } }, lastAccessedOn: { serializedName: "LastAccessTime", xmlName: "LastAccessTime", type: { name: "DateTimeRfc1123" } }, immutabilityPolicyExpiresOn: { serializedName: "ImmutabilityPolicyUntilDate", xmlName: "ImmutabilityPolicyUntilDate", type: { name: "DateTimeRfc1123" } }, immutabilityPolicyMode: { serializedName: "ImmutabilityPolicyMode", xmlName: "ImmutabilityPolicyMode", type: { name: "Enum", allowedValues: ["Mutable", "Unlocked", "Locked"] } }, legalHold: { serializedName: "LegalHold", xmlName: "LegalHold", type: { name: "Boolean" } } } } }; const ListBlobsHierarchySegmentResponse = { serializedName: "ListBlobsHierarchySegmentResponse", xmlName: "EnumerationResults", type: { name: "Composite", className: "ListBlobsHierarchySegmentResponse", modelProperties: { serviceEndpoint: { serializedName: "ServiceEndpoint", required: true, xmlName: "ServiceEndpoint", xmlIsAttribute: true, type: { name: "String" } }, containerName: { serializedName: "ContainerName", required: true, xmlName: "ContainerName", xmlIsAttribute: true, type: { name: "String" } }, prefix: { serializedName: "Prefix", xmlName: "Prefix", type: { name: "String" } }, marker: { serializedName: "Marker", xmlName: "Marker", type: { name: "String" } }, maxPageSize: { serializedName: "MaxResults", xmlName: "MaxResults", type: { name: "Number" } }, delimiter: { serializedName: "Delimiter", xmlName: "Delimiter", type: { name: "String" } }, segment: { serializedName: "Segment", xmlName: "Blobs", type: { name: "Composite", className: "BlobHierarchyListSegment" } }, continuationToken: { serializedName: "NextMarker", xmlName: "NextMarker", type: { name: "String" } } } } }; const BlobHierarchyListSegment = { serializedName: "BlobHierarchyListSegment", xmlName: "Blobs", type: { name: "Composite", className: "BlobHierarchyListSegment", modelProperties: { blobPrefixes: { serializedName: "BlobPrefixes", xmlName: "BlobPrefixes", xmlElementName: "BlobPrefix", type: { name: "Sequence", element: { type: { name: "Composite", className: "BlobPrefix" } } } }, blobItems: { serializedName: "BlobItems", required: true, xmlName: "BlobItems", xmlElementName: "Blob", type: { name: "Sequence", element: { type: { name: "Composite", className: "BlobItemInternal" } } } } } } }; const BlobPrefix = { serializedName: "BlobPrefix", type: { name: "Composite", className: "BlobPrefix", modelProperties: { name: { serializedName: "Name", xmlName: "Name", type: { name: "Composite", className: "BlobName" } } } } }; const BlockLookupList = { serializedName: "BlockLookupList", xmlName: "BlockList", type: { name: "Composite", className: "BlockLookupList", modelProperties: { committed: { serializedName: "Committed", xmlName: "Committed", xmlElementName: "Committed", type: { name: "Sequence", element: { type: { name: "String" } } } }, uncommitted: { serializedName: "Uncommitted", xmlName: "Uncommitted", xmlElementName: "Uncommitted", type: { name: "Sequence", element: { type: { name: "String" } } } }, latest: { serializedName: "Latest", xmlName: "Latest", xmlElementName: "Latest", type: { name: "Sequence", element: { type: { name: "String" } } } } } } }; const BlockList = { serializedName: "BlockList", type: { name: "Composite", className: "BlockList", modelProperties: { committedBlocks: { serializedName: "CommittedBlocks", xmlName: "CommittedBlocks", xmlIsWrapped: true, xmlElementName: "Block", type: { name: "Sequence", element: { type: { name: "Composite", className: "Block" } } } }, uncommittedBlocks: { serializedName: "UncommittedBlocks", xmlName: "UncommittedBlocks", xmlIsWrapped: true, xmlElementName: "Block", type: { name: "Sequence", element: { type: { name: "Composite", className: "Block" } } } } } } }; const Block = { serializedName: "Block", type: { name: "Composite", className: "Block", modelProperties: { name: { serializedName: "Name", required: true, xmlName: "Name", type: { name: "String" } }, size: { serializedName: "Size", required: true, xmlName: "Size", type: { name: "Number" } } } } }; const PageList = { serializedName: "PageList", type: { name: "Composite", className: "PageList", modelProperties: { pageRange: { serializedName: "PageRange", xmlName: "PageRange", xmlElementName: "PageRange", type: { name: "Sequence", element: { type: { name: "Composite", className: "PageRange" } } } }, clearRange: { serializedName: "ClearRange", xmlName: "ClearRange", xmlElementName: "ClearRange", type: { name: "Sequence", element: { type: { name: "Composite", className: "ClearRange" } } } }, continuationToken: { serializedName: "NextMarker", xmlName: "NextMarker", type: { name: "String" } } } } }; const PageRange = { serializedName: "PageRange", xmlName: "PageRange", type: { name: "Composite", className: "PageRange", modelProperties: { start: { serializedName: "Start", required: true, xmlName: "Start", type: { name: "Number" } }, end: { serializedName: "End", required: true, xmlName: "End", type: { name: "Number" } } } } }; const ClearRange = { serializedName: "ClearRange", xmlName: "ClearRange", type: { name: "Composite", className: "ClearRange", modelProperties: { start: { serializedName: "Start", required: true, xmlName: "Start", type: { name: "Number" } }, end: { serializedName: "End", required: true, xmlName: "End", type: { name: "Number" } } } } }; const QueryRequest = { serializedName: "QueryRequest", xmlName: "QueryRequest", type: { name: "Composite", className: "QueryRequest", modelProperties: { queryType: { serializedName: "QueryType", required: true, xmlName: "QueryType", type: { name: "String" } }, expression: { serializedName: "Expression", required: true, xmlName: "Expression", type: { name: "String" } }, inputSerialization: { serializedName: "InputSerialization", xmlName: "InputSerialization", type: { name: "Composite", className: "QuerySerialization" } }, outputSerialization: { serializedName: "OutputSerialization", xmlName: "OutputSerialization", type: { name: "Composite", className: "QuerySerialization" } } } } }; const QuerySerialization = { serializedName: "QuerySerialization", type: { name: "Composite", className: "QuerySerialization", modelProperties: { format: { serializedName: "Format", xmlName: "Format", type: { name: "Composite", className: "QueryFormat" } } } } }; const QueryFormat = { serializedName: "QueryFormat", type: { name: "Composite", className: "QueryFormat", modelProperties: { type: { serializedName: "Type", required: true, xmlName: "Type", type: { name: "Enum", allowedValues: ["delimited", "json", "arrow", "parquet"] } }, delimitedTextConfiguration: { serializedName: "DelimitedTextConfiguration", xmlName: "DelimitedTextConfiguration", type: { name: "Composite", className: "DelimitedTextConfiguration" } }, jsonTextConfiguration: { serializedName: "JsonTextConfiguration", xmlName: "JsonTextConfiguration", type: { name: "Composite", className: "JsonTextConfiguration" } }, arrowConfiguration: { serializedName: "ArrowConfiguration", xmlName: "ArrowConfiguration", type: { name: "Composite", className: "ArrowConfiguration" } }, parquetTextConfiguration: { serializedName: "ParquetTextConfiguration", xmlName: "ParquetTextConfiguration", type: { name: "any" } } } } }; const DelimitedTextConfiguration = { serializedName: "DelimitedTextConfiguration", xmlName: "DelimitedTextConfiguration", type: { name: "Composite", className: "DelimitedTextConfiguration", modelProperties: { columnSeparator: { serializedName: "ColumnSeparator", xmlName: "ColumnSeparator", type: { name: "String" } }, fieldQuote: { serializedName: "FieldQuote", xmlName: "FieldQuote", type: { name: "String" } }, recordSeparator: { serializedName: "RecordSeparator", xmlName: "RecordSeparator", type: { name: "String" } }, escapeChar: { serializedName: "EscapeChar", xmlName: "EscapeChar", type: { name: "String" } }, headersPresent: { serializedName: "HeadersPresent", xmlName: "HasHeaders", type: { name: "Boolean" } } } } }; const JsonTextConfiguration = { serializedName: "JsonTextConfiguration", xmlName: "JsonTextConfiguration", type: { name: "Composite", className: "JsonTextConfiguration", modelProperties: { recordSeparator: { serializedName: "RecordSeparator", xmlName: "RecordSeparator", type: { name: "String" } } } } }; const ArrowConfiguration = { serializedName: "ArrowConfiguration", xmlName: "ArrowConfiguration", type: { name: "Composite", className: "ArrowConfiguration", modelProperties: { schema: { serializedName: "Schema", required: true, xmlName: "Schema", xmlIsWrapped: true, xmlElementName: "Field", type: { name: "Sequence", element: { type: { name: "Composite", className: "ArrowField" } } } } } } }; const ArrowField = { serializedName: "ArrowField", xmlName: "Field", type: { name: "Composite", className: "ArrowField", modelProperties: { type: { serializedName: "Type", required: true, xmlName: "Type", type: { name: "String" } }, name: { serializedName: "Name", xmlName: "Name", type: { name: "String" } }, precision: { serializedName: "Precision", xmlName: "Precision", type: { name: "Number" } }, scale: { serializedName: "Scale", xmlName: "Scale", type: { name: "Number" } } } } }; const ServiceSetPropertiesHeaders = { serializedName: "Service_setPropertiesHeaders", type: { name: "Composite", className: "ServiceSetPropertiesHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ServiceSetPropertiesExceptionHeaders = { serializedName: "Service_setPropertiesExceptionHeaders", type: { name: "Composite", className: "ServiceSetPropertiesExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ServiceGetPropertiesHeaders = { serializedName: "Service_getPropertiesHeaders", type: { name: "Composite", className: "ServiceGetPropertiesHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ServiceGetPropertiesExceptionHeaders = { serializedName: "Service_getPropertiesExceptionHeaders", type: { name: "Composite", className: "ServiceGetPropertiesExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ServiceGetStatisticsHeaders = { serializedName: "Service_getStatisticsHeaders", type: { name: "Composite", className: "ServiceGetStatisticsHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ServiceGetStatisticsExceptionHeaders = { serializedName: "Service_getStatisticsExceptionHeaders", type: { name: "Composite", className: "ServiceGetStatisticsExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ServiceListContainersSegmentHeaders = { serializedName: "Service_listContainersSegmentHeaders", type: { name: "Composite", className: "ServiceListContainersSegmentHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ServiceListContainersSegmentExceptionHeaders = { serializedName: "Service_listContainersSegmentExceptionHeaders", type: { name: "Composite", className: "ServiceListContainersSegmentExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ServiceGetUserDelegationKeyHeaders = { serializedName: "Service_getUserDelegationKeyHeaders", type: { name: "Composite", className: "ServiceGetUserDelegationKeyHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ServiceGetUserDelegationKeyExceptionHeaders = { serializedName: "Service_getUserDelegationKeyExceptionHeaders", type: { name: "Composite", className: "ServiceGetUserDelegationKeyExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ServiceGetAccountInfoHeaders = { serializedName: "Service_getAccountInfoHeaders", type: { name: "Composite", className: "ServiceGetAccountInfoHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, skuName: { serializedName: "x-ms-sku-name", xmlName: "x-ms-sku-name", type: { name: "Enum", allowedValues: [ "Standard_LRS", "Standard_GRS", "Standard_RAGRS", "Standard_ZRS", "Premium_LRS" ] } }, accountKind: { serializedName: "x-ms-account-kind", xmlName: "x-ms-account-kind", type: { name: "Enum", allowedValues: [ "Storage", "BlobStorage", "StorageV2", "FileStorage", "BlockBlobStorage" ] } }, isHierarchicalNamespaceEnabled: { serializedName: "x-ms-is-hns-enabled", xmlName: "x-ms-is-hns-enabled", type: { name: "Boolean" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ServiceGetAccountInfoExceptionHeaders = { serializedName: "Service_getAccountInfoExceptionHeaders", type: { name: "Composite", className: "ServiceGetAccountInfoExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ServiceSubmitBatchHeaders = { serializedName: "Service_submitBatchHeaders", type: { name: "Composite", className: "ServiceSubmitBatchHeaders", modelProperties: { contentType: { serializedName: "content-type", xmlName: "content-type", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ServiceSubmitBatchExceptionHeaders = { serializedName: "Service_submitBatchExceptionHeaders", type: { name: "Composite", className: "ServiceSubmitBatchExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ServiceFilterBlobsHeaders = { serializedName: "Service_filterBlobsHeaders", type: { name: "Composite", className: "ServiceFilterBlobsHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ServiceFilterBlobsExceptionHeaders = { serializedName: "Service_filterBlobsExceptionHeaders", type: { name: "Composite", className: "ServiceFilterBlobsExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerCreateHeaders = { serializedName: "Container_createHeaders", type: { name: "Composite", className: "ContainerCreateHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerCreateExceptionHeaders = { serializedName: "Container_createExceptionHeaders", type: { name: "Composite", className: "ContainerCreateExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerGetPropertiesHeaders = { serializedName: "Container_getPropertiesHeaders", type: { name: "Composite", className: "ContainerGetPropertiesHeaders", modelProperties: { metadata: { serializedName: "x-ms-meta", xmlName: "x-ms-meta", type: { name: "Dictionary", value: { type: { name: "String" } } }, headerCollectionPrefix: "x-ms-meta-" }, etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, leaseDuration: { serializedName: "x-ms-lease-duration", xmlName: "x-ms-lease-duration", type: { name: "Enum", allowedValues: ["infinite", "fixed"] } }, leaseState: { serializedName: "x-ms-lease-state", xmlName: "x-ms-lease-state", type: { name: "Enum", allowedValues: [ "available", "leased", "expired", "breaking", "broken" ] } }, leaseStatus: { serializedName: "x-ms-lease-status", xmlName: "x-ms-lease-status", type: { name: "Enum", allowedValues: ["locked", "unlocked"] } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, blobPublicAccess: { serializedName: "x-ms-blob-public-access", xmlName: "x-ms-blob-public-access", type: { name: "Enum", allowedValues: ["container", "blob"] } }, hasImmutabilityPolicy: { serializedName: "x-ms-has-immutability-policy", xmlName: "x-ms-has-immutability-policy", type: { name: "Boolean" } }, hasLegalHold: { serializedName: "x-ms-has-legal-hold", xmlName: "x-ms-has-legal-hold", type: { name: "Boolean" } }, defaultEncryptionScope: { serializedName: "x-ms-default-encryption-scope", xmlName: "x-ms-default-encryption-scope", type: { name: "String" } }, denyEncryptionScopeOverride: { serializedName: "x-ms-deny-encryption-scope-override", xmlName: "x-ms-deny-encryption-scope-override", type: { name: "Boolean" } }, isImmutableStorageWithVersioningEnabled: { serializedName: "x-ms-immutable-storage-with-versioning-enabled", xmlName: "x-ms-immutable-storage-with-versioning-enabled", type: { name: "Boolean" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerGetPropertiesExceptionHeaders = { serializedName: "Container_getPropertiesExceptionHeaders", type: { name: "Composite", className: "ContainerGetPropertiesExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerDeleteHeaders = { serializedName: "Container_deleteHeaders", type: { name: "Composite", className: "ContainerDeleteHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerDeleteExceptionHeaders = { serializedName: "Container_deleteExceptionHeaders", type: { name: "Composite", className: "ContainerDeleteExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerSetMetadataHeaders = { serializedName: "Container_setMetadataHeaders", type: { name: "Composite", className: "ContainerSetMetadataHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerSetMetadataExceptionHeaders = { serializedName: "Container_setMetadataExceptionHeaders", type: { name: "Composite", className: "ContainerSetMetadataExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerGetAccessPolicyHeaders = { serializedName: "Container_getAccessPolicyHeaders", type: { name: "Composite", className: "ContainerGetAccessPolicyHeaders", modelProperties: { blobPublicAccess: { serializedName: "x-ms-blob-public-access", xmlName: "x-ms-blob-public-access", type: { name: "Enum", allowedValues: ["container", "blob"] } }, etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerGetAccessPolicyExceptionHeaders = { serializedName: "Container_getAccessPolicyExceptionHeaders", type: { name: "Composite", className: "ContainerGetAccessPolicyExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerSetAccessPolicyHeaders = { serializedName: "Container_setAccessPolicyHeaders", type: { name: "Composite", className: "ContainerSetAccessPolicyHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerSetAccessPolicyExceptionHeaders = { serializedName: "Container_setAccessPolicyExceptionHeaders", type: { name: "Composite", className: "ContainerSetAccessPolicyExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerRestoreHeaders = { serializedName: "Container_restoreHeaders", type: { name: "Composite", className: "ContainerRestoreHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerRestoreExceptionHeaders = { serializedName: "Container_restoreExceptionHeaders", type: { name: "Composite", className: "ContainerRestoreExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerRenameHeaders = { serializedName: "Container_renameHeaders", type: { name: "Composite", className: "ContainerRenameHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerRenameExceptionHeaders = { serializedName: "Container_renameExceptionHeaders", type: { name: "Composite", className: "ContainerRenameExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerSubmitBatchHeaders = { serializedName: "Container_submitBatchHeaders", type: { name: "Composite", className: "ContainerSubmitBatchHeaders", modelProperties: { contentType: { serializedName: "content-type", xmlName: "content-type", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } } } } }; const ContainerSubmitBatchExceptionHeaders = { serializedName: "Container_submitBatchExceptionHeaders", type: { name: "Composite", className: "ContainerSubmitBatchExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerFilterBlobsHeaders = { serializedName: "Container_filterBlobsHeaders", type: { name: "Composite", className: "ContainerFilterBlobsHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } } } } }; const ContainerFilterBlobsExceptionHeaders = { serializedName: "Container_filterBlobsExceptionHeaders", type: { name: "Composite", className: "ContainerFilterBlobsExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerAcquireLeaseHeaders = { serializedName: "Container_acquireLeaseHeaders", type: { name: "Composite", className: "ContainerAcquireLeaseHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, leaseId: { serializedName: "x-ms-lease-id", xmlName: "x-ms-lease-id", type: { name: "String" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } } } } }; const ContainerAcquireLeaseExceptionHeaders = { serializedName: "Container_acquireLeaseExceptionHeaders", type: { name: "Composite", className: "ContainerAcquireLeaseExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerReleaseLeaseHeaders = { serializedName: "Container_releaseLeaseHeaders", type: { name: "Composite", className: "ContainerReleaseLeaseHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } } } } }; const ContainerReleaseLeaseExceptionHeaders = { serializedName: "Container_releaseLeaseExceptionHeaders", type: { name: "Composite", className: "ContainerReleaseLeaseExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerRenewLeaseHeaders = { serializedName: "Container_renewLeaseHeaders", type: { name: "Composite", className: "ContainerRenewLeaseHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, leaseId: { serializedName: "x-ms-lease-id", xmlName: "x-ms-lease-id", type: { name: "String" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } } } } }; const ContainerRenewLeaseExceptionHeaders = { serializedName: "Container_renewLeaseExceptionHeaders", type: { name: "Composite", className: "ContainerRenewLeaseExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerBreakLeaseHeaders = { serializedName: "Container_breakLeaseHeaders", type: { name: "Composite", className: "ContainerBreakLeaseHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, leaseTime: { serializedName: "x-ms-lease-time", xmlName: "x-ms-lease-time", type: { name: "Number" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } } } } }; const ContainerBreakLeaseExceptionHeaders = { serializedName: "Container_breakLeaseExceptionHeaders", type: { name: "Composite", className: "ContainerBreakLeaseExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerChangeLeaseHeaders = { serializedName: "Container_changeLeaseHeaders", type: { name: "Composite", className: "ContainerChangeLeaseHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, leaseId: { serializedName: "x-ms-lease-id", xmlName: "x-ms-lease-id", type: { name: "String" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } } } } }; const ContainerChangeLeaseExceptionHeaders = { serializedName: "Container_changeLeaseExceptionHeaders", type: { name: "Composite", className: "ContainerChangeLeaseExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerListBlobFlatSegmentHeaders = { serializedName: "Container_listBlobFlatSegmentHeaders", type: { name: "Composite", className: "ContainerListBlobFlatSegmentHeaders", modelProperties: { contentType: { serializedName: "content-type", xmlName: "content-type", type: { name: "String" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerListBlobFlatSegmentExceptionHeaders = { serializedName: "Container_listBlobFlatSegmentExceptionHeaders", type: { name: "Composite", className: "ContainerListBlobFlatSegmentExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerListBlobHierarchySegmentHeaders = { serializedName: "Container_listBlobHierarchySegmentHeaders", type: { name: "Composite", className: "ContainerListBlobHierarchySegmentHeaders", modelProperties: { contentType: { serializedName: "content-type", xmlName: "content-type", type: { name: "String" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerListBlobHierarchySegmentExceptionHeaders = { serializedName: "Container_listBlobHierarchySegmentExceptionHeaders", type: { name: "Composite", className: "ContainerListBlobHierarchySegmentExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const ContainerGetAccountInfoHeaders = { serializedName: "Container_getAccountInfoHeaders", type: { name: "Composite", className: "ContainerGetAccountInfoHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, skuName: { serializedName: "x-ms-sku-name", xmlName: "x-ms-sku-name", type: { name: "Enum", allowedValues: [ "Standard_LRS", "Standard_GRS", "Standard_RAGRS", "Standard_ZRS", "Premium_LRS" ] } }, accountKind: { serializedName: "x-ms-account-kind", xmlName: "x-ms-account-kind", type: { name: "Enum", allowedValues: [ "Storage", "BlobStorage", "StorageV2", "FileStorage", "BlockBlobStorage" ] } } } } }; const ContainerGetAccountInfoExceptionHeaders = { serializedName: "Container_getAccountInfoExceptionHeaders", type: { name: "Composite", className: "ContainerGetAccountInfoExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobDownloadHeaders = { serializedName: "Blob_downloadHeaders", type: { name: "Composite", className: "BlobDownloadHeaders", modelProperties: { lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { 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", type: { name: "Dictionary", value: { type: { name: "String" } } }, headerCollectionPrefix: "x-ms-meta-" }, objectReplicationPolicyId: { serializedName: "x-ms-or-policy-id", xmlName: "x-ms-or-policy-id", type: { name: "String" } }, objectReplicationRules: { serializedName: "x-ms-or", xmlName: "x-ms-or", type: { name: "Dictionary", value: { type: { name: "String" } } }, headerCollectionPrefix: "x-ms-or-" }, contentLength: { serializedName: "content-length", xmlName: "content-length", type: { name: "Number" } }, contentType: { serializedName: "content-type", xmlName: "content-type", type: { name: "String" } }, contentRange: { serializedName: "content-range", xmlName: "content-range", type: { name: "String" } }, etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray" } }, contentEncoding: { serializedName: "content-encoding", xmlName: "content-encoding", type: { name: "String" } }, cacheControl: { serializedName: "cache-control", xmlName: "cache-control", type: { name: "String" } }, contentDisposition: { serializedName: "content-disposition", xmlName: "content-disposition", type: { name: "String" } }, contentLanguage: { serializedName: "content-language", xmlName: "content-language", type: { name: "String" } }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", xmlName: "x-ms-blob-sequence-number", type: { name: "Number" } }, blobType: { serializedName: "x-ms-blob-type", xmlName: "x-ms-blob-type", type: { name: "Enum", allowedValues: ["BlockBlob", "PageBlob", "AppendBlob"] } }, copyCompletedOn: { serializedName: "x-ms-copy-completion-time", xmlName: "x-ms-copy-completion-time", type: { name: "DateTimeRfc1123" } }, copyStatusDescription: { serializedName: "x-ms-copy-status-description", xmlName: "x-ms-copy-status-description", type: { name: "String" } }, copyId: { serializedName: "x-ms-copy-id", xmlName: "x-ms-copy-id", type: { name: "String" } }, copyProgress: { serializedName: "x-ms-copy-progress", xmlName: "x-ms-copy-progress", type: { name: "String" } }, copySource: { serializedName: "x-ms-copy-source", xmlName: "x-ms-copy-source", type: { name: "String" } }, copyStatus: { serializedName: "x-ms-copy-status", xmlName: "x-ms-copy-status", type: { name: "Enum", allowedValues: ["pending", "success", "aborted", "failed"] } }, leaseDuration: { serializedName: "x-ms-lease-duration", xmlName: "x-ms-lease-duration", type: { name: "Enum", allowedValues: ["infinite", "fixed"] } }, leaseState: { serializedName: "x-ms-lease-state", xmlName: "x-ms-lease-state", type: { name: "Enum", allowedValues: [ "available", "leased", "expired", "breaking", "broken" ] } }, leaseStatus: { serializedName: "x-ms-lease-status", xmlName: "x-ms-lease-status", type: { name: "Enum", allowedValues: ["locked", "unlocked"] } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, versionId: { serializedName: "x-ms-version-id", xmlName: "x-ms-version-id", type: { name: "String" } }, isCurrentVersion: { serializedName: "x-ms-is-current-version", xmlName: "x-ms-is-current-version", type: { name: "Boolean" } }, acceptRanges: { serializedName: "accept-ranges", xmlName: "accept-ranges", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, blobCommittedBlockCount: { serializedName: "x-ms-blob-committed-block-count", xmlName: "x-ms-blob-committed-block-count", type: { name: "Number" } }, isServerEncrypted: { serializedName: "x-ms-server-encrypted", xmlName: "x-ms-server-encrypted", type: { name: "Boolean" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String" } }, blobContentMD5: { serializedName: "x-ms-blob-content-md5", xmlName: "x-ms-blob-content-md5", type: { name: "ByteArray" } }, tagCount: { serializedName: "x-ms-tag-count", xmlName: "x-ms-tag-count", type: { name: "Number" } }, isSealed: { serializedName: "x-ms-blob-sealed", xmlName: "x-ms-blob-sealed", type: { name: "Boolean" } }, lastAccessed: { serializedName: "x-ms-last-access-time", xmlName: "x-ms-last-access-time", type: { name: "DateTimeRfc1123" } }, immutabilityPolicyExpiresOn: { serializedName: "x-ms-immutability-policy-until-date", xmlName: "x-ms-immutability-policy-until-date", type: { name: "DateTimeRfc1123" } }, immutabilityPolicyMode: { serializedName: "x-ms-immutability-policy-mode", xmlName: "x-ms-immutability-policy-mode", type: { name: "Enum", allowedValues: ["Mutable", "Unlocked", "Locked"] } }, legalHold: { serializedName: "x-ms-legal-hold", xmlName: "x-ms-legal-hold", type: { name: "Boolean" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } }, contentCrc64: { serializedName: "x-ms-content-crc64", xmlName: "x-ms-content-crc64", type: { name: "ByteArray" } } } } }; const BlobDownloadExceptionHeaders = { serializedName: "Blob_downloadExceptionHeaders", type: { name: "Composite", className: "BlobDownloadExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobGetPropertiesHeaders = { serializedName: "Blob_getPropertiesHeaders", type: { name: "Composite", className: "BlobGetPropertiesHeaders", modelProperties: { lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { 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", type: { name: "Dictionary", value: { type: { name: "String" } } }, headerCollectionPrefix: "x-ms-meta-" }, objectReplicationPolicyId: { serializedName: "x-ms-or-policy-id", xmlName: "x-ms-or-policy-id", type: { name: "String" } }, objectReplicationRules: { serializedName: "x-ms-or", xmlName: "x-ms-or", type: { name: "Dictionary", value: { type: { name: "String" } } }, headerCollectionPrefix: "x-ms-or-" }, blobType: { serializedName: "x-ms-blob-type", xmlName: "x-ms-blob-type", type: { name: "Enum", allowedValues: ["BlockBlob", "PageBlob", "AppendBlob"] } }, copyCompletedOn: { serializedName: "x-ms-copy-completion-time", xmlName: "x-ms-copy-completion-time", type: { name: "DateTimeRfc1123" } }, copyStatusDescription: { serializedName: "x-ms-copy-status-description", xmlName: "x-ms-copy-status-description", type: { name: "String" } }, copyId: { serializedName: "x-ms-copy-id", xmlName: "x-ms-copy-id", type: { name: "String" } }, copyProgress: { serializedName: "x-ms-copy-progress", xmlName: "x-ms-copy-progress", type: { name: "String" } }, copySource: { serializedName: "x-ms-copy-source", xmlName: "x-ms-copy-source", type: { name: "String" } }, copyStatus: { serializedName: "x-ms-copy-status", xmlName: "x-ms-copy-status", type: { name: "Enum", allowedValues: ["pending", "success", "aborted", "failed"] } }, isIncrementalCopy: { serializedName: "x-ms-incremental-copy", xmlName: "x-ms-incremental-copy", type: { name: "Boolean" } }, destinationSnapshot: { serializedName: "x-ms-copy-destination-snapshot", xmlName: "x-ms-copy-destination-snapshot", type: { name: "String" } }, leaseDuration: { serializedName: "x-ms-lease-duration", xmlName: "x-ms-lease-duration", type: { name: "Enum", allowedValues: ["infinite", "fixed"] } }, leaseState: { serializedName: "x-ms-lease-state", xmlName: "x-ms-lease-state", type: { name: "Enum", allowedValues: [ "available", "leased", "expired", "breaking", "broken" ] } }, leaseStatus: { serializedName: "x-ms-lease-status", xmlName: "x-ms-lease-status", type: { name: "Enum", allowedValues: ["locked", "unlocked"] } }, contentLength: { serializedName: "content-length", xmlName: "content-length", type: { name: "Number" } }, contentType: { serializedName: "content-type", xmlName: "content-type", type: { name: "String" } }, etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray" } }, contentEncoding: { serializedName: "content-encoding", xmlName: "content-encoding", type: { name: "String" } }, contentDisposition: { serializedName: "content-disposition", xmlName: "content-disposition", type: { name: "String" } }, contentLanguage: { serializedName: "content-language", xmlName: "content-language", type: { name: "String" } }, cacheControl: { serializedName: "cache-control", xmlName: "cache-control", type: { name: "String" } }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", xmlName: "x-ms-blob-sequence-number", type: { name: "Number" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, acceptRanges: { serializedName: "accept-ranges", xmlName: "accept-ranges", type: { name: "String" } }, blobCommittedBlockCount: { serializedName: "x-ms-blob-committed-block-count", xmlName: "x-ms-blob-committed-block-count", type: { name: "Number" } }, isServerEncrypted: { serializedName: "x-ms-server-encrypted", xmlName: "x-ms-server-encrypted", type: { name: "Boolean" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String" } }, accessTier: { serializedName: "x-ms-access-tier", xmlName: "x-ms-access-tier", type: { name: "String" } }, accessTierInferred: { serializedName: "x-ms-access-tier-inferred", xmlName: "x-ms-access-tier-inferred", type: { name: "Boolean" } }, archiveStatus: { serializedName: "x-ms-archive-status", xmlName: "x-ms-archive-status", type: { name: "String" } }, accessTierChangedOn: { serializedName: "x-ms-access-tier-change-time", xmlName: "x-ms-access-tier-change-time", type: { name: "DateTimeRfc1123" } }, versionId: { serializedName: "x-ms-version-id", xmlName: "x-ms-version-id", type: { name: "String" } }, isCurrentVersion: { serializedName: "x-ms-is-current-version", xmlName: "x-ms-is-current-version", type: { name: "Boolean" } }, tagCount: { serializedName: "x-ms-tag-count", xmlName: "x-ms-tag-count", type: { name: "Number" } }, expiresOn: { serializedName: "x-ms-expiry-time", xmlName: "x-ms-expiry-time", type: { name: "DateTimeRfc1123" } }, isSealed: { serializedName: "x-ms-blob-sealed", xmlName: "x-ms-blob-sealed", type: { name: "Boolean" } }, rehydratePriority: { serializedName: "x-ms-rehydrate-priority", xmlName: "x-ms-rehydrate-priority", type: { name: "Enum", allowedValues: ["High", "Standard"] } }, lastAccessed: { serializedName: "x-ms-last-access-time", xmlName: "x-ms-last-access-time", type: { name: "DateTimeRfc1123" } }, immutabilityPolicyExpiresOn: { serializedName: "x-ms-immutability-policy-until-date", xmlName: "x-ms-immutability-policy-until-date", type: { name: "DateTimeRfc1123" } }, immutabilityPolicyMode: { serializedName: "x-ms-immutability-policy-mode", xmlName: "x-ms-immutability-policy-mode", type: { name: "Enum", allowedValues: ["Mutable", "Unlocked", "Locked"] } }, legalHold: { serializedName: "x-ms-legal-hold", xmlName: "x-ms-legal-hold", type: { name: "Boolean" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobGetPropertiesExceptionHeaders = { serializedName: "Blob_getPropertiesExceptionHeaders", type: { name: "Composite", className: "BlobGetPropertiesExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobDeleteHeaders = { serializedName: "Blob_deleteHeaders", type: { name: "Composite", className: "BlobDeleteHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobDeleteExceptionHeaders = { serializedName: "Blob_deleteExceptionHeaders", type: { name: "Composite", className: "BlobDeleteExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobUndeleteHeaders = { serializedName: "Blob_undeleteHeaders", type: { name: "Composite", className: "BlobUndeleteHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobUndeleteExceptionHeaders = { serializedName: "Blob_undeleteExceptionHeaders", type: { name: "Composite", className: "BlobUndeleteExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobSetExpiryHeaders = { serializedName: "Blob_setExpiryHeaders", type: { name: "Composite", className: "BlobSetExpiryHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } } } } }; const BlobSetExpiryExceptionHeaders = { serializedName: "Blob_setExpiryExceptionHeaders", type: { name: "Composite", className: "BlobSetExpiryExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobSetHttpHeadersHeaders = { serializedName: "Blob_setHttpHeadersHeaders", type: { name: "Composite", className: "BlobSetHttpHeadersHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", xmlName: "x-ms-blob-sequence-number", type: { name: "Number" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobSetHttpHeadersExceptionHeaders = { serializedName: "Blob_setHttpHeadersExceptionHeaders", type: { name: "Composite", className: "BlobSetHttpHeadersExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobSetImmutabilityPolicyHeaders = { serializedName: "Blob_setImmutabilityPolicyHeaders", type: { name: "Composite", className: "BlobSetImmutabilityPolicyHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, immutabilityPolicyExpiry: { serializedName: "x-ms-immutability-policy-until-date", xmlName: "x-ms-immutability-policy-until-date", type: { name: "DateTimeRfc1123" } }, immutabilityPolicyMode: { serializedName: "x-ms-immutability-policy-mode", xmlName: "x-ms-immutability-policy-mode", type: { name: "Enum", allowedValues: ["Mutable", "Unlocked", "Locked"] } } } } }; const BlobSetImmutabilityPolicyExceptionHeaders = { serializedName: "Blob_setImmutabilityPolicyExceptionHeaders", type: { name: "Composite", className: "BlobSetImmutabilityPolicyExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobDeleteImmutabilityPolicyHeaders = { serializedName: "Blob_deleteImmutabilityPolicyHeaders", type: { name: "Composite", className: "BlobDeleteImmutabilityPolicyHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } } } } }; const BlobDeleteImmutabilityPolicyExceptionHeaders = { serializedName: "Blob_deleteImmutabilityPolicyExceptionHeaders", type: { name: "Composite", className: "BlobDeleteImmutabilityPolicyExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobSetLegalHoldHeaders = { serializedName: "Blob_setLegalHoldHeaders", type: { name: "Composite", className: "BlobSetLegalHoldHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, legalHold: { serializedName: "x-ms-legal-hold", xmlName: "x-ms-legal-hold", type: { name: "Boolean" } } } } }; const BlobSetLegalHoldExceptionHeaders = { serializedName: "Blob_setLegalHoldExceptionHeaders", type: { name: "Composite", className: "BlobSetLegalHoldExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobSetMetadataHeaders = { serializedName: "Blob_setMetadataHeaders", type: { name: "Composite", className: "BlobSetMetadataHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, versionId: { serializedName: "x-ms-version-id", xmlName: "x-ms-version-id", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", xmlName: "x-ms-request-server-encrypted", type: { name: "Boolean" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobSetMetadataExceptionHeaders = { serializedName: "Blob_setMetadataExceptionHeaders", type: { name: "Composite", className: "BlobSetMetadataExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobAcquireLeaseHeaders = { serializedName: "Blob_acquireLeaseHeaders", type: { name: "Composite", className: "BlobAcquireLeaseHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, leaseId: { serializedName: "x-ms-lease-id", xmlName: "x-ms-lease-id", type: { name: "String" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } } } } }; const BlobAcquireLeaseExceptionHeaders = { serializedName: "Blob_acquireLeaseExceptionHeaders", type: { name: "Composite", className: "BlobAcquireLeaseExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobReleaseLeaseHeaders = { serializedName: "Blob_releaseLeaseHeaders", type: { name: "Composite", className: "BlobReleaseLeaseHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } } } } }; const BlobReleaseLeaseExceptionHeaders = { serializedName: "Blob_releaseLeaseExceptionHeaders", type: { name: "Composite", className: "BlobReleaseLeaseExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobRenewLeaseHeaders = { serializedName: "Blob_renewLeaseHeaders", type: { name: "Composite", className: "BlobRenewLeaseHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, leaseId: { serializedName: "x-ms-lease-id", xmlName: "x-ms-lease-id", type: { name: "String" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } } } } }; const BlobRenewLeaseExceptionHeaders = { serializedName: "Blob_renewLeaseExceptionHeaders", type: { name: "Composite", className: "BlobRenewLeaseExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobChangeLeaseHeaders = { serializedName: "Blob_changeLeaseHeaders", type: { name: "Composite", className: "BlobChangeLeaseHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, leaseId: { serializedName: "x-ms-lease-id", xmlName: "x-ms-lease-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } } } } }; const BlobChangeLeaseExceptionHeaders = { serializedName: "Blob_changeLeaseExceptionHeaders", type: { name: "Composite", className: "BlobChangeLeaseExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobBreakLeaseHeaders = { serializedName: "Blob_breakLeaseHeaders", type: { name: "Composite", className: "BlobBreakLeaseHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, leaseTime: { serializedName: "x-ms-lease-time", xmlName: "x-ms-lease-time", type: { name: "Number" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } } } } }; const BlobBreakLeaseExceptionHeaders = { serializedName: "Blob_breakLeaseExceptionHeaders", type: { name: "Composite", className: "BlobBreakLeaseExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobCreateSnapshotHeaders = { serializedName: "Blob_createSnapshotHeaders", type: { name: "Composite", className: "BlobCreateSnapshotHeaders", modelProperties: { snapshot: { serializedName: "x-ms-snapshot", xmlName: "x-ms-snapshot", type: { name: "String" } }, etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, versionId: { serializedName: "x-ms-version-id", xmlName: "x-ms-version-id", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", xmlName: "x-ms-request-server-encrypted", type: { name: "Boolean" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobCreateSnapshotExceptionHeaders = { serializedName: "Blob_createSnapshotExceptionHeaders", type: { name: "Composite", className: "BlobCreateSnapshotExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobStartCopyFromURLHeaders = { serializedName: "Blob_startCopyFromURLHeaders", type: { name: "Composite", className: "BlobStartCopyFromURLHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, versionId: { serializedName: "x-ms-version-id", xmlName: "x-ms-version-id", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, copyId: { serializedName: "x-ms-copy-id", xmlName: "x-ms-copy-id", type: { name: "String" } }, copyStatus: { serializedName: "x-ms-copy-status", xmlName: "x-ms-copy-status", type: { name: "Enum", allowedValues: ["pending", "success", "aborted", "failed"] } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobStartCopyFromURLExceptionHeaders = { serializedName: "Blob_startCopyFromURLExceptionHeaders", type: { name: "Composite", className: "BlobStartCopyFromURLExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobCopyFromURLHeaders = { serializedName: "Blob_copyFromURLHeaders", type: { name: "Composite", className: "BlobCopyFromURLHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, versionId: { serializedName: "x-ms-version-id", xmlName: "x-ms-version-id", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, copyId: { serializedName: "x-ms-copy-id", xmlName: "x-ms-copy-id", type: { name: "String" } }, copyStatus: { defaultValue: "success", isConstant: true, serializedName: "x-ms-copy-status", type: { name: "String" } }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray" } }, xMsContentCrc64: { serializedName: "x-ms-content-crc64", xmlName: "x-ms-content-crc64", type: { name: "ByteArray" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobCopyFromURLExceptionHeaders = { serializedName: "Blob_copyFromURLExceptionHeaders", type: { name: "Composite", className: "BlobCopyFromURLExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobAbortCopyFromURLHeaders = { serializedName: "Blob_abortCopyFromURLHeaders", type: { name: "Composite", className: "BlobAbortCopyFromURLHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobAbortCopyFromURLExceptionHeaders = { serializedName: "Blob_abortCopyFromURLExceptionHeaders", type: { name: "Composite", className: "BlobAbortCopyFromURLExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobSetTierHeaders = { serializedName: "Blob_setTierHeaders", type: { name: "Composite", className: "BlobSetTierHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobSetTierExceptionHeaders = { serializedName: "Blob_setTierExceptionHeaders", type: { name: "Composite", className: "BlobSetTierExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobGetAccountInfoHeaders = { serializedName: "Blob_getAccountInfoHeaders", type: { name: "Composite", className: "BlobGetAccountInfoHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, skuName: { serializedName: "x-ms-sku-name", xmlName: "x-ms-sku-name", type: { name: "Enum", allowedValues: [ "Standard_LRS", "Standard_GRS", "Standard_RAGRS", "Standard_ZRS", "Premium_LRS" ] } }, accountKind: { serializedName: "x-ms-account-kind", xmlName: "x-ms-account-kind", type: { name: "Enum", allowedValues: [ "Storage", "BlobStorage", "StorageV2", "FileStorage", "BlockBlobStorage" ] } } } } }; const BlobGetAccountInfoExceptionHeaders = { serializedName: "Blob_getAccountInfoExceptionHeaders", type: { name: "Composite", className: "BlobGetAccountInfoExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobQueryHeaders = { serializedName: "Blob_queryHeaders", type: { name: "Composite", className: "BlobQueryHeaders", modelProperties: { lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, metadata: { serializedName: "x-ms-meta", xmlName: "x-ms-meta", type: { name: "Dictionary", value: { type: { name: "String" } } } }, contentLength: { serializedName: "content-length", xmlName: "content-length", type: { name: "Number" } }, contentType: { serializedName: "content-type", xmlName: "content-type", type: { name: "String" } }, contentRange: { serializedName: "content-range", xmlName: "content-range", type: { name: "String" } }, etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray" } }, contentEncoding: { serializedName: "content-encoding", xmlName: "content-encoding", type: { name: "String" } }, cacheControl: { serializedName: "cache-control", xmlName: "cache-control", type: { name: "String" } }, contentDisposition: { serializedName: "content-disposition", xmlName: "content-disposition", type: { name: "String" } }, contentLanguage: { serializedName: "content-language", xmlName: "content-language", type: { name: "String" } }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", xmlName: "x-ms-blob-sequence-number", type: { name: "Number" } }, blobType: { serializedName: "x-ms-blob-type", xmlName: "x-ms-blob-type", type: { name: "Enum", allowedValues: ["BlockBlob", "PageBlob", "AppendBlob"] } }, copyCompletionTime: { serializedName: "x-ms-copy-completion-time", xmlName: "x-ms-copy-completion-time", type: { name: "DateTimeRfc1123" } }, copyStatusDescription: { serializedName: "x-ms-copy-status-description", xmlName: "x-ms-copy-status-description", type: { name: "String" } }, copyId: { serializedName: "x-ms-copy-id", xmlName: "x-ms-copy-id", type: { name: "String" } }, copyProgress: { serializedName: "x-ms-copy-progress", xmlName: "x-ms-copy-progress", type: { name: "String" } }, copySource: { serializedName: "x-ms-copy-source", xmlName: "x-ms-copy-source", type: { name: "String" } }, copyStatus: { serializedName: "x-ms-copy-status", xmlName: "x-ms-copy-status", type: { name: "Enum", allowedValues: ["pending", "success", "aborted", "failed"] } }, leaseDuration: { serializedName: "x-ms-lease-duration", xmlName: "x-ms-lease-duration", type: { name: "Enum", allowedValues: ["infinite", "fixed"] } }, leaseState: { serializedName: "x-ms-lease-state", xmlName: "x-ms-lease-state", type: { name: "Enum", allowedValues: [ "available", "leased", "expired", "breaking", "broken" ] } }, leaseStatus: { serializedName: "x-ms-lease-status", xmlName: "x-ms-lease-status", type: { name: "Enum", allowedValues: ["locked", "unlocked"] } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, acceptRanges: { serializedName: "accept-ranges", xmlName: "accept-ranges", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, blobCommittedBlockCount: { serializedName: "x-ms-blob-committed-block-count", xmlName: "x-ms-blob-committed-block-count", type: { name: "Number" } }, isServerEncrypted: { serializedName: "x-ms-server-encrypted", xmlName: "x-ms-server-encrypted", type: { name: "Boolean" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String" } }, blobContentMD5: { serializedName: "x-ms-blob-content-md5", xmlName: "x-ms-blob-content-md5", type: { name: "ByteArray" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } }, contentCrc64: { serializedName: "x-ms-content-crc64", xmlName: "x-ms-content-crc64", type: { name: "ByteArray" } } } } }; const BlobQueryExceptionHeaders = { serializedName: "Blob_queryExceptionHeaders", type: { name: "Composite", className: "BlobQueryExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobGetTagsHeaders = { serializedName: "Blob_getTagsHeaders", type: { name: "Composite", className: "BlobGetTagsHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobGetTagsExceptionHeaders = { serializedName: "Blob_getTagsExceptionHeaders", type: { name: "Composite", className: "BlobGetTagsExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobSetTagsHeaders = { serializedName: "Blob_setTagsHeaders", type: { name: "Composite", className: "BlobSetTagsHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlobSetTagsExceptionHeaders = { serializedName: "Blob_setTagsExceptionHeaders", type: { name: "Composite", className: "BlobSetTagsExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const PageBlobCreateHeaders = { serializedName: "PageBlob_createHeaders", type: { name: "Composite", className: "PageBlobCreateHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, versionId: { serializedName: "x-ms-version-id", xmlName: "x-ms-version-id", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", xmlName: "x-ms-request-server-encrypted", type: { name: "Boolean" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const PageBlobCreateExceptionHeaders = { serializedName: "PageBlob_createExceptionHeaders", type: { name: "Composite", className: "PageBlobCreateExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const PageBlobUploadPagesHeaders = { serializedName: "PageBlob_uploadPagesHeaders", type: { name: "Composite", className: "PageBlobUploadPagesHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray" } }, xMsContentCrc64: { serializedName: "x-ms-content-crc64", xmlName: "x-ms-content-crc64", type: { name: "ByteArray" } }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", xmlName: "x-ms-blob-sequence-number", type: { name: "Number" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", xmlName: "x-ms-request-server-encrypted", type: { name: "Boolean" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const PageBlobUploadPagesExceptionHeaders = { serializedName: "PageBlob_uploadPagesExceptionHeaders", type: { name: "Composite", className: "PageBlobUploadPagesExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const PageBlobClearPagesHeaders = { serializedName: "PageBlob_clearPagesHeaders", type: { name: "Composite", className: "PageBlobClearPagesHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray" } }, xMsContentCrc64: { serializedName: "x-ms-content-crc64", xmlName: "x-ms-content-crc64", type: { name: "ByteArray" } }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", xmlName: "x-ms-blob-sequence-number", type: { name: "Number" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const PageBlobClearPagesExceptionHeaders = { serializedName: "PageBlob_clearPagesExceptionHeaders", type: { name: "Composite", className: "PageBlobClearPagesExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const PageBlobUploadPagesFromURLHeaders = { serializedName: "PageBlob_uploadPagesFromURLHeaders", type: { name: "Composite", className: "PageBlobUploadPagesFromURLHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray" } }, xMsContentCrc64: { serializedName: "x-ms-content-crc64", xmlName: "x-ms-content-crc64", type: { name: "ByteArray" } }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", xmlName: "x-ms-blob-sequence-number", type: { name: "Number" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", xmlName: "x-ms-request-server-encrypted", type: { name: "Boolean" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const PageBlobUploadPagesFromURLExceptionHeaders = { serializedName: "PageBlob_uploadPagesFromURLExceptionHeaders", type: { name: "Composite", className: "PageBlobUploadPagesFromURLExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const PageBlobGetPageRangesHeaders = { serializedName: "PageBlob_getPageRangesHeaders", type: { name: "Composite", className: "PageBlobGetPageRangesHeaders", modelProperties: { lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, blobContentLength: { serializedName: "x-ms-blob-content-length", xmlName: "x-ms-blob-content-length", type: { name: "Number" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const PageBlobGetPageRangesExceptionHeaders = { serializedName: "PageBlob_getPageRangesExceptionHeaders", type: { name: "Composite", className: "PageBlobGetPageRangesExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const PageBlobGetPageRangesDiffHeaders = { serializedName: "PageBlob_getPageRangesDiffHeaders", type: { name: "Composite", className: "PageBlobGetPageRangesDiffHeaders", modelProperties: { lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, blobContentLength: { serializedName: "x-ms-blob-content-length", xmlName: "x-ms-blob-content-length", type: { name: "Number" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const PageBlobGetPageRangesDiffExceptionHeaders = { serializedName: "PageBlob_getPageRangesDiffExceptionHeaders", type: { name: "Composite", className: "PageBlobGetPageRangesDiffExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const PageBlobResizeHeaders = { serializedName: "PageBlob_resizeHeaders", type: { name: "Composite", className: "PageBlobResizeHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", xmlName: "x-ms-blob-sequence-number", type: { name: "Number" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const PageBlobResizeExceptionHeaders = { serializedName: "PageBlob_resizeExceptionHeaders", type: { name: "Composite", className: "PageBlobResizeExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const PageBlobUpdateSequenceNumberHeaders = { serializedName: "PageBlob_updateSequenceNumberHeaders", type: { name: "Composite", className: "PageBlobUpdateSequenceNumberHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", xmlName: "x-ms-blob-sequence-number", type: { name: "Number" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const PageBlobUpdateSequenceNumberExceptionHeaders = { serializedName: "PageBlob_updateSequenceNumberExceptionHeaders", type: { name: "Composite", className: "PageBlobUpdateSequenceNumberExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const PageBlobCopyIncrementalHeaders = { serializedName: "PageBlob_copyIncrementalHeaders", type: { name: "Composite", className: "PageBlobCopyIncrementalHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, copyId: { serializedName: "x-ms-copy-id", xmlName: "x-ms-copy-id", type: { name: "String" } }, copyStatus: { serializedName: "x-ms-copy-status", xmlName: "x-ms-copy-status", type: { name: "Enum", allowedValues: ["pending", "success", "aborted", "failed"] } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const PageBlobCopyIncrementalExceptionHeaders = { serializedName: "PageBlob_copyIncrementalExceptionHeaders", type: { name: "Composite", className: "PageBlobCopyIncrementalExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const AppendBlobCreateHeaders = { serializedName: "AppendBlob_createHeaders", type: { name: "Composite", className: "AppendBlobCreateHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, versionId: { serializedName: "x-ms-version-id", xmlName: "x-ms-version-id", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", xmlName: "x-ms-request-server-encrypted", type: { name: "Boolean" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const AppendBlobCreateExceptionHeaders = { serializedName: "AppendBlob_createExceptionHeaders", type: { name: "Composite", className: "AppendBlobCreateExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const AppendBlobAppendBlockHeaders = { serializedName: "AppendBlob_appendBlockHeaders", type: { name: "Composite", className: "AppendBlobAppendBlockHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray" } }, xMsContentCrc64: { serializedName: "x-ms-content-crc64", xmlName: "x-ms-content-crc64", type: { name: "ByteArray" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, blobAppendOffset: { serializedName: "x-ms-blob-append-offset", xmlName: "x-ms-blob-append-offset", type: { name: "String" } }, blobCommittedBlockCount: { serializedName: "x-ms-blob-committed-block-count", xmlName: "x-ms-blob-committed-block-count", type: { name: "Number" } }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", xmlName: "x-ms-request-server-encrypted", type: { name: "Boolean" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const AppendBlobAppendBlockExceptionHeaders = { serializedName: "AppendBlob_appendBlockExceptionHeaders", type: { name: "Composite", className: "AppendBlobAppendBlockExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const AppendBlobAppendBlockFromUrlHeaders = { serializedName: "AppendBlob_appendBlockFromUrlHeaders", type: { name: "Composite", className: "AppendBlobAppendBlockFromUrlHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray" } }, xMsContentCrc64: { serializedName: "x-ms-content-crc64", xmlName: "x-ms-content-crc64", type: { name: "ByteArray" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, blobAppendOffset: { serializedName: "x-ms-blob-append-offset", xmlName: "x-ms-blob-append-offset", type: { name: "String" } }, blobCommittedBlockCount: { serializedName: "x-ms-blob-committed-block-count", xmlName: "x-ms-blob-committed-block-count", type: { name: "Number" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String" } }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", xmlName: "x-ms-request-server-encrypted", type: { name: "Boolean" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const AppendBlobAppendBlockFromUrlExceptionHeaders = { serializedName: "AppendBlob_appendBlockFromUrlExceptionHeaders", type: { name: "Composite", className: "AppendBlobAppendBlockFromUrlExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const AppendBlobSealHeaders = { serializedName: "AppendBlob_sealHeaders", type: { name: "Composite", className: "AppendBlobSealHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, isSealed: { serializedName: "x-ms-blob-sealed", xmlName: "x-ms-blob-sealed", type: { name: "Boolean" } } } } }; const AppendBlobSealExceptionHeaders = { serializedName: "AppendBlob_sealExceptionHeaders", type: { name: "Composite", className: "AppendBlobSealExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlockBlobUploadHeaders = { serializedName: "BlockBlob_uploadHeaders", type: { name: "Composite", className: "BlockBlobUploadHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, versionId: { serializedName: "x-ms-version-id", xmlName: "x-ms-version-id", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", xmlName: "x-ms-request-server-encrypted", type: { name: "Boolean" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlockBlobUploadExceptionHeaders = { serializedName: "BlockBlob_uploadExceptionHeaders", type: { name: "Composite", className: "BlockBlobUploadExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlockBlobPutBlobFromUrlHeaders = { serializedName: "BlockBlob_putBlobFromUrlHeaders", type: { name: "Composite", className: "BlockBlobPutBlobFromUrlHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, versionId: { serializedName: "x-ms-version-id", xmlName: "x-ms-version-id", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", xmlName: "x-ms-request-server-encrypted", type: { name: "Boolean" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlockBlobPutBlobFromUrlExceptionHeaders = { serializedName: "BlockBlob_putBlobFromUrlExceptionHeaders", type: { name: "Composite", className: "BlockBlobPutBlobFromUrlExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlockBlobStageBlockHeaders = { serializedName: "BlockBlob_stageBlockHeaders", type: { name: "Composite", className: "BlockBlobStageBlockHeaders", modelProperties: { contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, xMsContentCrc64: { serializedName: "x-ms-content-crc64", xmlName: "x-ms-content-crc64", type: { name: "ByteArray" } }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", xmlName: "x-ms-request-server-encrypted", type: { name: "Boolean" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlockBlobStageBlockExceptionHeaders = { serializedName: "BlockBlob_stageBlockExceptionHeaders", type: { name: "Composite", className: "BlockBlobStageBlockExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlockBlobStageBlockFromURLHeaders = { serializedName: "BlockBlob_stageBlockFromURLHeaders", type: { name: "Composite", className: "BlockBlobStageBlockFromURLHeaders", modelProperties: { contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray" } }, xMsContentCrc64: { serializedName: "x-ms-content-crc64", xmlName: "x-ms-content-crc64", type: { name: "ByteArray" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", xmlName: "x-ms-request-server-encrypted", type: { name: "Boolean" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlockBlobStageBlockFromURLExceptionHeaders = { serializedName: "BlockBlob_stageBlockFromURLExceptionHeaders", type: { name: "Composite", className: "BlockBlobStageBlockFromURLExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlockBlobCommitBlockListHeaders = { serializedName: "BlockBlob_commitBlockListHeaders", type: { name: "Composite", className: "BlockBlobCommitBlockListHeaders", modelProperties: { etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, contentMD5: { serializedName: "content-md5", xmlName: "content-md5", type: { name: "ByteArray" } }, xMsContentCrc64: { serializedName: "x-ms-content-crc64", xmlName: "x-ms-content-crc64", type: { name: "ByteArray" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, versionId: { serializedName: "x-ms-version-id", xmlName: "x-ms-version-id", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", xmlName: "x-ms-request-server-encrypted", type: { name: "Boolean" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlockBlobCommitBlockListExceptionHeaders = { serializedName: "BlockBlob_commitBlockListExceptionHeaders", type: { name: "Composite", className: "BlockBlobCommitBlockListExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlockBlobGetBlockListHeaders = { serializedName: "BlockBlob_getBlockListHeaders", type: { name: "Composite", className: "BlockBlobGetBlockListHeaders", modelProperties: { lastModified: { serializedName: "last-modified", xmlName: "last-modified", type: { name: "DateTimeRfc1123" } }, etag: { serializedName: "etag", xmlName: "etag", type: { name: "String" } }, contentType: { serializedName: "content-type", xmlName: "content-type", type: { name: "String" } }, blobContentLength: { serializedName: "x-ms-blob-content-length", xmlName: "x-ms-blob-content-length", type: { name: "Number" } }, clientRequestId: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", xmlName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", xmlName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", xmlName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; const BlockBlobGetBlockListExceptionHeaders = { serializedName: "BlockBlob_getBlockListExceptionHeaders", type: { name: "Composite", className: "BlockBlobGetBlockListExceptionHeaders", modelProperties: { errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } } } } }; var Mappers = /*#__PURE__*/Object.freeze({ __proto__: null, BlobServiceProperties: BlobServiceProperties, Logging: Logging, RetentionPolicy: RetentionPolicy, Metrics: Metrics, CorsRule: CorsRule, StaticWebsite: StaticWebsite, StorageError: StorageError, BlobServiceStatistics: BlobServiceStatistics, GeoReplication: GeoReplication, ListContainersSegmentResponse: ListContainersSegmentResponse, ContainerItem: ContainerItem, ContainerProperties: ContainerProperties, KeyInfo: KeyInfo, UserDelegationKey: UserDelegationKey, FilterBlobSegment: FilterBlobSegment, FilterBlobItem: FilterBlobItem, BlobTags: BlobTags, BlobTag: BlobTag, SignedIdentifier: SignedIdentifier, AccessPolicy: AccessPolicy, ListBlobsFlatSegmentResponse: ListBlobsFlatSegmentResponse, BlobFlatListSegment: BlobFlatListSegment, BlobItemInternal: BlobItemInternal, BlobName: BlobName, BlobPropertiesInternal: BlobPropertiesInternal, ListBlobsHierarchySegmentResponse: ListBlobsHierarchySegmentResponse, BlobHierarchyListSegment: BlobHierarchyListSegment, BlobPrefix: BlobPrefix, BlockLookupList: BlockLookupList, BlockList: BlockList, Block: Block, PageList: PageList, PageRange: PageRange, ClearRange: ClearRange, QueryRequest: QueryRequest, QuerySerialization: QuerySerialization, QueryFormat: QueryFormat, DelimitedTextConfiguration: DelimitedTextConfiguration, JsonTextConfiguration: JsonTextConfiguration, ArrowConfiguration: ArrowConfiguration, ArrowField: ArrowField, ServiceSetPropertiesHeaders: ServiceSetPropertiesHeaders, ServiceSetPropertiesExceptionHeaders: ServiceSetPropertiesExceptionHeaders, ServiceGetPropertiesHeaders: ServiceGetPropertiesHeaders, ServiceGetPropertiesExceptionHeaders: ServiceGetPropertiesExceptionHeaders, ServiceGetStatisticsHeaders: ServiceGetStatisticsHeaders, ServiceGetStatisticsExceptionHeaders: ServiceGetStatisticsExceptionHeaders, ServiceListContainersSegmentHeaders: ServiceListContainersSegmentHeaders, ServiceListContainersSegmentExceptionHeaders: ServiceListContainersSegmentExceptionHeaders, ServiceGetUserDelegationKeyHeaders: ServiceGetUserDelegationKeyHeaders, ServiceGetUserDelegationKeyExceptionHeaders: ServiceGetUserDelegationKeyExceptionHeaders, ServiceGetAccountInfoHeaders: ServiceGetAccountInfoHeaders, ServiceGetAccountInfoExceptionHeaders: ServiceGetAccountInfoExceptionHeaders, ServiceSubmitBatchHeaders: ServiceSubmitBatchHeaders, ServiceSubmitBatchExceptionHeaders: ServiceSubmitBatchExceptionHeaders, ServiceFilterBlobsHeaders: ServiceFilterBlobsHeaders, ServiceFilterBlobsExceptionHeaders: ServiceFilterBlobsExceptionHeaders, ContainerCreateHeaders: ContainerCreateHeaders, ContainerCreateExceptionHeaders: ContainerCreateExceptionHeaders, ContainerGetPropertiesHeaders: ContainerGetPropertiesHeaders, ContainerGetPropertiesExceptionHeaders: ContainerGetPropertiesExceptionHeaders, ContainerDeleteHeaders: ContainerDeleteHeaders, ContainerDeleteExceptionHeaders: ContainerDeleteExceptionHeaders, ContainerSetMetadataHeaders: ContainerSetMetadataHeaders, ContainerSetMetadataExceptionHeaders: ContainerSetMetadataExceptionHeaders, ContainerGetAccessPolicyHeaders: ContainerGetAccessPolicyHeaders, ContainerGetAccessPolicyExceptionHeaders: ContainerGetAccessPolicyExceptionHeaders, ContainerSetAccessPolicyHeaders: ContainerSetAccessPolicyHeaders, ContainerSetAccessPolicyExceptionHeaders: ContainerSetAccessPolicyExceptionHeaders, ContainerRestoreHeaders: ContainerRestoreHeaders, ContainerRestoreExceptionHeaders: ContainerRestoreExceptionHeaders, ContainerRenameHeaders: ContainerRenameHeaders, ContainerRenameExceptionHeaders: ContainerRenameExceptionHeaders, ContainerSubmitBatchHeaders: ContainerSubmitBatchHeaders, ContainerSubmitBatchExceptionHeaders: ContainerSubmitBatchExceptionHeaders, ContainerFilterBlobsHeaders: ContainerFilterBlobsHeaders, ContainerFilterBlobsExceptionHeaders: ContainerFilterBlobsExceptionHeaders, ContainerAcquireLeaseHeaders: ContainerAcquireLeaseHeaders, ContainerAcquireLeaseExceptionHeaders: ContainerAcquireLeaseExceptionHeaders, ContainerReleaseLeaseHeaders: ContainerReleaseLeaseHeaders, ContainerReleaseLeaseExceptionHeaders: ContainerReleaseLeaseExceptionHeaders, ContainerRenewLeaseHeaders: ContainerRenewLeaseHeaders, ContainerRenewLeaseExceptionHeaders: ContainerRenewLeaseExceptionHeaders, ContainerBreakLeaseHeaders: ContainerBreakLeaseHeaders, ContainerBreakLeaseExceptionHeaders: ContainerBreakLeaseExceptionHeaders, ContainerChangeLeaseHeaders: ContainerChangeLeaseHeaders, ContainerChangeLeaseExceptionHeaders: ContainerChangeLeaseExceptionHeaders, ContainerListBlobFlatSegmentHeaders: ContainerListBlobFlatSegmentHeaders, ContainerListBlobFlatSegmentExceptionHeaders: ContainerListBlobFlatSegmentExceptionHeaders, ContainerListBlobHierarchySegmentHeaders: ContainerListBlobHierarchySegmentHeaders, ContainerListBlobHierarchySegmentExceptionHeaders: ContainerListBlobHierarchySegmentExceptionHeaders, ContainerGetAccountInfoHeaders: ContainerGetAccountInfoHeaders, ContainerGetAccountInfoExceptionHeaders: ContainerGetAccountInfoExceptionHeaders, BlobDownloadHeaders: BlobDownloadHeaders, BlobDownloadExceptionHeaders: BlobDownloadExceptionHeaders, BlobGetPropertiesHeaders: BlobGetPropertiesHeaders, BlobGetPropertiesExceptionHeaders: BlobGetPropertiesExceptionHeaders, BlobDeleteHeaders: BlobDeleteHeaders, BlobDeleteExceptionHeaders: BlobDeleteExceptionHeaders, BlobUndeleteHeaders: BlobUndeleteHeaders, BlobUndeleteExceptionHeaders: BlobUndeleteExceptionHeaders, BlobSetExpiryHeaders: BlobSetExpiryHeaders, BlobSetExpiryExceptionHeaders: BlobSetExpiryExceptionHeaders, BlobSetHttpHeadersHeaders: BlobSetHttpHeadersHeaders, BlobSetHttpHeadersExceptionHeaders: BlobSetHttpHeadersExceptionHeaders, BlobSetImmutabilityPolicyHeaders: BlobSetImmutabilityPolicyHeaders, BlobSetImmutabilityPolicyExceptionHeaders: BlobSetImmutabilityPolicyExceptionHeaders, BlobDeleteImmutabilityPolicyHeaders: BlobDeleteImmutabilityPolicyHeaders, BlobDeleteImmutabilityPolicyExceptionHeaders: BlobDeleteImmutabilityPolicyExceptionHeaders, BlobSetLegalHoldHeaders: BlobSetLegalHoldHeaders, BlobSetLegalHoldExceptionHeaders: BlobSetLegalHoldExceptionHeaders, BlobSetMetadataHeaders: BlobSetMetadataHeaders, BlobSetMetadataExceptionHeaders: BlobSetMetadataExceptionHeaders, BlobAcquireLeaseHeaders: BlobAcquireLeaseHeaders, BlobAcquireLeaseExceptionHeaders: BlobAcquireLeaseExceptionHeaders, BlobReleaseLeaseHeaders: BlobReleaseLeaseHeaders, BlobReleaseLeaseExceptionHeaders: BlobReleaseLeaseExceptionHeaders, BlobRenewLeaseHeaders: BlobRenewLeaseHeaders, BlobRenewLeaseExceptionHeaders: BlobRenewLeaseExceptionHeaders, BlobChangeLeaseHeaders: BlobChangeLeaseHeaders, BlobChangeLeaseExceptionHeaders: BlobChangeLeaseExceptionHeaders, BlobBreakLeaseHeaders: BlobBreakLeaseHeaders, BlobBreakLeaseExceptionHeaders: BlobBreakLeaseExceptionHeaders, BlobCreateSnapshotHeaders: BlobCreateSnapshotHeaders, BlobCreateSnapshotExceptionHeaders: BlobCreateSnapshotExceptionHeaders, BlobStartCopyFromURLHeaders: BlobStartCopyFromURLHeaders, BlobStartCopyFromURLExceptionHeaders: BlobStartCopyFromURLExceptionHeaders, BlobCopyFromURLHeaders: BlobCopyFromURLHeaders, BlobCopyFromURLExceptionHeaders: BlobCopyFromURLExceptionHeaders, BlobAbortCopyFromURLHeaders: BlobAbortCopyFromURLHeaders, BlobAbortCopyFromURLExceptionHeaders: BlobAbortCopyFromURLExceptionHeaders, BlobSetTierHeaders: BlobSetTierHeaders, BlobSetTierExceptionHeaders: BlobSetTierExceptionHeaders, BlobGetAccountInfoHeaders: BlobGetAccountInfoHeaders, BlobGetAccountInfoExceptionHeaders: BlobGetAccountInfoExceptionHeaders, BlobQueryHeaders: BlobQueryHeaders, BlobQueryExceptionHeaders: BlobQueryExceptionHeaders, BlobGetTagsHeaders: BlobGetTagsHeaders, BlobGetTagsExceptionHeaders: BlobGetTagsExceptionHeaders, BlobSetTagsHeaders: BlobSetTagsHeaders, BlobSetTagsExceptionHeaders: BlobSetTagsExceptionHeaders, PageBlobCreateHeaders: PageBlobCreateHeaders, PageBlobCreateExceptionHeaders: PageBlobCreateExceptionHeaders, PageBlobUploadPagesHeaders: PageBlobUploadPagesHeaders, PageBlobUploadPagesExceptionHeaders: PageBlobUploadPagesExceptionHeaders, PageBlobClearPagesHeaders: PageBlobClearPagesHeaders, PageBlobClearPagesExceptionHeaders: PageBlobClearPagesExceptionHeaders, PageBlobUploadPagesFromURLHeaders: PageBlobUploadPagesFromURLHeaders, PageBlobUploadPagesFromURLExceptionHeaders: PageBlobUploadPagesFromURLExceptionHeaders, PageBlobGetPageRangesHeaders: PageBlobGetPageRangesHeaders, PageBlobGetPageRangesExceptionHeaders: PageBlobGetPageRangesExceptionHeaders, PageBlobGetPageRangesDiffHeaders: PageBlobGetPageRangesDiffHeaders, PageBlobGetPageRangesDiffExceptionHeaders: PageBlobGetPageRangesDiffExceptionHeaders, PageBlobResizeHeaders: PageBlobResizeHeaders, PageBlobResizeExceptionHeaders: PageBlobResizeExceptionHeaders, PageBlobUpdateSequenceNumberHeaders: PageBlobUpdateSequenceNumberHeaders, PageBlobUpdateSequenceNumberExceptionHeaders: PageBlobUpdateSequenceNumberExceptionHeaders, PageBlobCopyIncrementalHeaders: PageBlobCopyIncrementalHeaders, PageBlobCopyIncrementalExceptionHeaders: PageBlobCopyIncrementalExceptionHeaders, AppendBlobCreateHeaders: AppendBlobCreateHeaders, AppendBlobCreateExceptionHeaders: AppendBlobCreateExceptionHeaders, AppendBlobAppendBlockHeaders: AppendBlobAppendBlockHeaders, AppendBlobAppendBlockExceptionHeaders: AppendBlobAppendBlockExceptionHeaders, AppendBlobAppendBlockFromUrlHeaders: AppendBlobAppendBlockFromUrlHeaders, AppendBlobAppendBlockFromUrlExceptionHeaders: AppendBlobAppendBlockFromUrlExceptionHeaders, AppendBlobSealHeaders: AppendBlobSealHeaders, AppendBlobSealExceptionHeaders: AppendBlobSealExceptionHeaders, BlockBlobUploadHeaders: BlockBlobUploadHeaders, BlockBlobUploadExceptionHeaders: BlockBlobUploadExceptionHeaders, BlockBlobPutBlobFromUrlHeaders: BlockBlobPutBlobFromUrlHeaders, BlockBlobPutBlobFromUrlExceptionHeaders: BlockBlobPutBlobFromUrlExceptionHeaders, BlockBlobStageBlockHeaders: BlockBlobStageBlockHeaders, BlockBlobStageBlockExceptionHeaders: BlockBlobStageBlockExceptionHeaders, BlockBlobStageBlockFromURLHeaders: BlockBlobStageBlockFromURLHeaders, BlockBlobStageBlockFromURLExceptionHeaders: BlockBlobStageBlockFromURLExceptionHeaders, BlockBlobCommitBlockListHeaders: BlockBlobCommitBlockListHeaders, BlockBlobCommitBlockListExceptionHeaders: BlockBlobCommitBlockListExceptionHeaders, BlockBlobGetBlockListHeaders: BlockBlobGetBlockListHeaders, BlockBlobGetBlockListExceptionHeaders: BlockBlobGetBlockListExceptionHeaders }); /* * 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 contentType = { parameterPath: ["options", "contentType"], mapper: { defaultValue: "application/xml", isConstant: true, serializedName: "Content-Type", type: { name: "String" } } }; const blobServiceProperties = { parameterPath: "blobServiceProperties", mapper: BlobServiceProperties }; const accept = { parameterPath: "accept", mapper: { defaultValue: "application/xml", isConstant: true, serializedName: "Accept", type: { name: "String" } } }; const url = { parameterPath: "url", mapper: { serializedName: "url", required: true, xmlName: "url", type: { name: "String" } }, skipEncoding: true }; const restype = { parameterPath: "restype", mapper: { defaultValue: "service", isConstant: true, serializedName: "restype", type: { name: "String" } } }; const comp = { parameterPath: "comp", mapper: { defaultValue: "properties", isConstant: true, serializedName: "comp", type: { name: "String" } } }; const timeoutInSeconds = { parameterPath: ["options", "timeoutInSeconds"], mapper: { constraints: { InclusiveMinimum: 0 }, serializedName: "timeout", xmlName: "timeout", type: { name: "Number" } } }; const version = { parameterPath: "version", mapper: { defaultValue: "2021-12-02", isConstant: true, serializedName: "x-ms-version", type: { name: "String" } } }; const requestId = { parameterPath: ["options", "requestId"], mapper: { serializedName: "x-ms-client-request-id", xmlName: "x-ms-client-request-id", type: { name: "String" } } }; const accept1 = { parameterPath: "accept", mapper: { defaultValue: "application/xml", isConstant: true, serializedName: "Accept", type: { name: "String" } } }; const comp1 = { parameterPath: "comp", mapper: { defaultValue: "stats", isConstant: true, serializedName: "comp", type: { name: "String" } } }; const comp2 = { parameterPath: "comp", mapper: { defaultValue: "list", isConstant: true, serializedName: "comp", type: { name: "String" } } }; const prefix = { parameterPath: ["options", "prefix"], mapper: { serializedName: "prefix", xmlName: "prefix", type: { name: "String" } } }; const marker = { parameterPath: ["options", "marker"], mapper: { serializedName: "marker", xmlName: "marker", type: { name: "String" } } }; const maxPageSize = { parameterPath: ["options", "maxPageSize"], mapper: { constraints: { InclusiveMinimum: 1 }, serializedName: "maxresults", xmlName: "maxresults", type: { name: "Number" } } }; const include = { parameterPath: ["options", "include"], mapper: { serializedName: "include", xmlName: "include", xmlElementName: "ListContainersIncludeType", type: { name: "Sequence", element: { type: { name: "Enum", allowedValues: ["metadata", "deleted", "system"] } } } }, collectionFormat: coreHttp.QueryCollectionFormat.Csv }; const keyInfo = { parameterPath: "keyInfo", mapper: KeyInfo }; const comp3 = { parameterPath: "comp", mapper: { defaultValue: "userdelegationkey", isConstant: true, serializedName: "comp", type: { name: "String" } } }; const restype1 = { parameterPath: "restype", mapper: { defaultValue: "account", isConstant: true, serializedName: "restype", type: { name: "String" } } }; const body = { parameterPath: "body", mapper: { serializedName: "body", required: true, xmlName: "body", type: { name: "Stream" } } }; const comp4 = { parameterPath: "comp", mapper: { defaultValue: "batch", isConstant: true, serializedName: "comp", type: { name: "String" } } }; const contentLength = { parameterPath: "contentLength", mapper: { serializedName: "Content-Length", required: true, xmlName: "Content-Length", type: { name: "Number" } } }; const multipartContentType = { parameterPath: "multipartContentType", mapper: { serializedName: "Content-Type", required: true, xmlName: "Content-Type", type: { name: "String" } } }; const comp5 = { parameterPath: "comp", mapper: { defaultValue: "blobs", isConstant: true, serializedName: "comp", type: { name: "String" } } }; const where = { parameterPath: ["options", "where"], mapper: { serializedName: "where", xmlName: "where", type: { name: "String" } } }; const restype2 = { parameterPath: "restype", mapper: { defaultValue: "container", isConstant: true, serializedName: "restype", type: { name: "String" } } }; const metadata = { parameterPath: ["options", "metadata"], mapper: { serializedName: "x-ms-meta", xmlName: "x-ms-meta", type: { name: "Dictionary", value: { type: { name: "String" } } }, headerCollectionPrefix: "x-ms-meta-" } }; const access = { parameterPath: ["options", "access"], mapper: { serializedName: "x-ms-blob-public-access", xmlName: "x-ms-blob-public-access", type: { name: "Enum", allowedValues: ["container", "blob"] } } }; const defaultEncryptionScope = { parameterPath: [ "options", "containerEncryptionScope", "defaultEncryptionScope" ], mapper: { serializedName: "x-ms-default-encryption-scope", xmlName: "x-ms-default-encryption-scope", type: { name: "String" } } }; const preventEncryptionScopeOverride = { parameterPath: [ "options", "containerEncryptionScope", "preventEncryptionScopeOverride" ], mapper: { serializedName: "x-ms-deny-encryption-scope-override", xmlName: "x-ms-deny-encryption-scope-override", type: { name: "Boolean" } } }; const leaseId = { parameterPath: ["options", "leaseAccessConditions", "leaseId"], mapper: { serializedName: "x-ms-lease-id", xmlName: "x-ms-lease-id", type: { name: "String" } } }; const ifModifiedSince = { parameterPath: ["options", "modifiedAccessConditions", "ifModifiedSince"], mapper: { serializedName: "If-Modified-Since", xmlName: "If-Modified-Since", type: { name: "DateTimeRfc1123" } } }; const ifUnmodifiedSince = { parameterPath: ["options", "modifiedAccessConditions", "ifUnmodifiedSince"], mapper: { serializedName: "If-Unmodified-Since", xmlName: "If-Unmodified-Since", type: { name: "DateTimeRfc1123" } } }; const comp6 = { parameterPath: "comp", mapper: { defaultValue: "metadata", isConstant: true, serializedName: "comp", type: { name: "String" } } }; const comp7 = { parameterPath: "comp", mapper: { defaultValue: "acl", isConstant: true, serializedName: "comp", type: { name: "String" } } }; const containerAcl = { parameterPath: ["options", "containerAcl"], mapper: { serializedName: "containerAcl", xmlName: "SignedIdentifiers", xmlIsWrapped: true, xmlElementName: "SignedIdentifier", type: { name: "Sequence", element: { type: { name: "Composite", className: "SignedIdentifier" } } } } }; const comp8 = { parameterPath: "comp", mapper: { defaultValue: "undelete", isConstant: true, serializedName: "comp", type: { name: "String" } } }; const deletedContainerName = { parameterPath: ["options", "deletedContainerName"], mapper: { serializedName: "x-ms-deleted-container-name", xmlName: "x-ms-deleted-container-name", type: { name: "String" } } }; const deletedContainerVersion = { parameterPath: ["options", "deletedContainerVersion"], mapper: { serializedName: "x-ms-deleted-container-version", xmlName: "x-ms-deleted-container-version", type: { name: "String" } } }; const comp9 = { parameterPath: "comp", mapper: { defaultValue: "rename", isConstant: true, serializedName: "comp", type: { name: "String" } } }; const sourceContainerName = { parameterPath: "sourceContainerName", mapper: { serializedName: "x-ms-source-container-name", required: true, xmlName: "x-ms-source-container-name", type: { name: "String" } } }; const sourceLeaseId = { parameterPath: ["options", "sourceLeaseId"], mapper: { serializedName: "x-ms-source-lease-id", xmlName: "x-ms-source-lease-id", type: { name: "String" } } }; const comp10 = { parameterPath: "comp", mapper: { defaultValue: "lease", isConstant: true, serializedName: "comp", type: { name: "String" } } }; const action = { parameterPath: "action", mapper: { defaultValue: "acquire", isConstant: true, serializedName: "x-ms-lease-action", type: { name: "String" } } }; const duration = { parameterPath: ["options", "duration"], mapper: { serializedName: "x-ms-lease-duration", xmlName: "x-ms-lease-duration", type: { name: "Number" } } }; const proposedLeaseId = { parameterPath: ["options", "proposedLeaseId"], mapper: { serializedName: "x-ms-proposed-lease-id", xmlName: "x-ms-proposed-lease-id", type: { name: "String" } } }; const action1 = { parameterPath: "action", mapper: { defaultValue: "release", isConstant: true, serializedName: "x-ms-lease-action", type: { name: "String" } } }; const leaseId1 = { parameterPath: "leaseId", mapper: { serializedName: "x-ms-lease-id", required: true, xmlName: "x-ms-lease-id", type: { name: "String" } } }; const action2 = { parameterPath: "action", mapper: { defaultValue: "renew", isConstant: true, serializedName: "x-ms-lease-action", type: { name: "String" } } }; const action3 = { parameterPath: "action", mapper: { defaultValue: "break", isConstant: true, serializedName: "x-ms-lease-action", type: { name: "String" } } }; const breakPeriod = { parameterPath: ["options", "breakPeriod"], mapper: { serializedName: "x-ms-lease-break-period", xmlName: "x-ms-lease-break-period", type: { name: "Number" } } }; const action4 = { parameterPath: "action", mapper: { defaultValue: "change", isConstant: true, serializedName: "x-ms-lease-action", type: { name: "String" } } }; const proposedLeaseId1 = { parameterPath: "proposedLeaseId", mapper: { serializedName: "x-ms-proposed-lease-id", required: true, xmlName: "x-ms-proposed-lease-id", type: { name: "String" } } }; const include1 = { parameterPath: ["options", "include"], mapper: { serializedName: "include", xmlName: "include", xmlElementName: "ListBlobsIncludeItem", type: { name: "Sequence", element: { type: { name: "Enum", allowedValues: [ "copy", "deleted", "metadata", "snapshots", "uncommittedblobs", "versions", "tags", "immutabilitypolicy", "legalhold", "deletedwithversions" ] } } } }, collectionFormat: coreHttp.QueryCollectionFormat.Csv }; const delimiter = { parameterPath: "delimiter", mapper: { serializedName: "delimiter", required: true, xmlName: "delimiter", type: { name: "String" } } }; const snapshot = { parameterPath: ["options", "snapshot"], mapper: { serializedName: "snapshot", xmlName: "snapshot", type: { name: "String" } } }; const versionId = { parameterPath: ["options", "versionId"], mapper: { serializedName: "versionid", xmlName: "versionid", type: { name: "String" } } }; const range = { parameterPath: ["options", "range"], mapper: { serializedName: "x-ms-range", xmlName: "x-ms-range", type: { name: "String" } } }; const rangeGetContentMD5 = { parameterPath: ["options", "rangeGetContentMD5"], mapper: { serializedName: "x-ms-range-get-content-md5", xmlName: "x-ms-range-get-content-md5", type: { name: "Boolean" } } }; const rangeGetContentCRC64 = { parameterPath: ["options", "rangeGetContentCRC64"], mapper: { serializedName: "x-ms-range-get-content-crc64", xmlName: "x-ms-range-get-content-crc64", type: { name: "Boolean" } } }; const encryptionKey = { parameterPath: ["options", "cpkInfo", "encryptionKey"], mapper: { serializedName: "x-ms-encryption-key", xmlName: "x-ms-encryption-key", type: { name: "String" } } }; const encryptionKeySha256 = { parameterPath: ["options", "cpkInfo", "encryptionKeySha256"], mapper: { serializedName: "x-ms-encryption-key-sha256", xmlName: "x-ms-encryption-key-sha256", type: { name: "String" } } }; const encryptionAlgorithm = { parameterPath: ["options", "cpkInfo", "encryptionAlgorithm"], mapper: { serializedName: "x-ms-encryption-algorithm", xmlName: "x-ms-encryption-algorithm", type: { name: "String" } } }; const ifMatch = { parameterPath: ["options", "modifiedAccessConditions", "ifMatch"], mapper: { serializedName: "If-Match", xmlName: "If-Match", type: { name: "String" } } }; const ifNoneMatch = { parameterPath: ["options", "modifiedAccessConditions", "ifNoneMatch"], mapper: { serializedName: "If-None-Match", xmlName: "If-None-Match", type: { name: "String" } } }; const ifTags = { parameterPath: ["options", "modifiedAccessConditions", "ifTags"], mapper: { serializedName: "x-ms-if-tags", xmlName: "x-ms-if-tags", type: { name: "String" } } }; const deleteSnapshots = { parameterPath: ["options", "deleteSnapshots"], mapper: { serializedName: "x-ms-delete-snapshots", xmlName: "x-ms-delete-snapshots", type: { name: "Enum", allowedValues: ["include", "only"] } } }; const blobDeleteType = { parameterPath: ["options", "blobDeleteType"], mapper: { serializedName: "deletetype", xmlName: "deletetype", type: { name: "String" } } }; const comp11 = { parameterPath: "comp", mapper: { defaultValue: "expiry", isConstant: true, serializedName: "comp", type: { name: "String" } } }; const expiryOptions = { parameterPath: "expiryOptions", mapper: { serializedName: "x-ms-expiry-option", required: true, xmlName: "x-ms-expiry-option", type: { name: "String" } } }; const expiresOn = { parameterPath: ["options", "expiresOn"], mapper: { serializedName: "x-ms-expiry-time", xmlName: "x-ms-expiry-time", type: { name: "String" } } }; const blobCacheControl = { parameterPath: ["options", "blobHttpHeaders", "blobCacheControl"], mapper: { serializedName: "x-ms-blob-cache-control", xmlName: "x-ms-blob-cache-control", type: { name: "String" } } }; const blobContentType = { parameterPath: ["options", "blobHttpHeaders", "blobContentType"], mapper: { serializedName: "x-ms-blob-content-type", xmlName: "x-ms-blob-content-type", type: { name: "String" } } }; const blobContentMD5 = { parameterPath: ["options", "blobHttpHeaders", "blobContentMD5"], mapper: { serializedName: "x-ms-blob-content-md5", xmlName: "x-ms-blob-content-md5", type: { name: "ByteArray" } } }; const blobContentEncoding = { parameterPath: ["options", "blobHttpHeaders", "blobContentEncoding"], mapper: { serializedName: "x-ms-blob-content-encoding", xmlName: "x-ms-blob-content-encoding", type: { name: "String" } } }; const blobContentLanguage = { parameterPath: ["options", "blobHttpHeaders", "blobContentLanguage"], mapper: { serializedName: "x-ms-blob-content-language", xmlName: "x-ms-blob-content-language", type: { name: "String" } } }; const blobContentDisposition = { parameterPath: ["options", "blobHttpHeaders", "blobContentDisposition"], mapper: { serializedName: "x-ms-blob-content-disposition", xmlName: "x-ms-blob-content-disposition", type: { name: "String" } } }; const comp12 = { parameterPath: "comp", mapper: { defaultValue: "immutabilityPolicies", isConstant: true, serializedName: "comp", type: { name: "String" } } }; const immutabilityPolicyExpiry = { parameterPath: ["options", "immutabilityPolicyExpiry"], mapper: { serializedName: "x-ms-immutability-policy-until-date", xmlName: "x-ms-immutability-policy-until-date", type: { name: "DateTimeRfc1123" } } }; const immutabilityPolicyMode = { parameterPath: ["options", "immutabilityPolicyMode"], mapper: { serializedName: "x-ms-immutability-policy-mode", xmlName: "x-ms-immutability-policy-mode", type: { name: "Enum", allowedValues: ["Mutable", "Unlocked", "Locked"] } } }; const comp13 = { parameterPath: "comp", mapper: { defaultValue: "legalhold", isConstant: true, serializedName: "comp", type: { name: "String" } } }; const legalHold = { parameterPath: "legalHold", mapper: { serializedName: "x-ms-legal-hold", required: true, xmlName: "x-ms-legal-hold", type: { name: "Boolean" } } }; const encryptionScope = { parameterPath: ["options", "encryptionScope"], mapper: { serializedName: "x-ms-encryption-scope", xmlName: "x-ms-encryption-scope", type: { name: "String" } } }; const comp14 = { parameterPath: "comp", mapper: { defaultValue: "snapshot", isConstant: true, serializedName: "comp", type: { name: "String" } } }; const tier = { parameterPath: ["options", "tier"], mapper: { serializedName: "x-ms-access-tier", xmlName: "x-ms-access-tier", type: { name: "Enum", allowedValues: [ "P4", "P6", "P10", "P15", "P20", "P30", "P40", "P50", "P60", "P70", "P80", "Hot", "Cool", "Archive", "Cold" ] } } }; const rehydratePriority = { parameterPath: ["options", "rehydratePriority"], mapper: { serializedName: "x-ms-rehydrate-priority", xmlName: "x-ms-rehydrate-priority", type: { name: "Enum", allowedValues: ["High", "Standard"] } } }; const sourceIfModifiedSince = { parameterPath: [ "options", "sourceModifiedAccessConditions", "sourceIfModifiedSince" ], mapper: { serializedName: "x-ms-source-if-modified-since", xmlName: "x-ms-source-if-modified-since", type: { name: "DateTimeRfc1123" } } }; const sourceIfUnmodifiedSince = { parameterPath: [ "options", "sourceModifiedAccessConditions", "sourceIfUnmodifiedSince" ], mapper: { serializedName: "x-ms-source-if-unmodified-since", xmlName: "x-ms-source-if-unmodified-since", type: { name: "DateTimeRfc1123" } } }; const sourceIfMatch = { parameterPath: ["options", "sourceModifiedAccessConditions", "sourceIfMatch"], mapper: { serializedName: "x-ms-source-if-match", xmlName: "x-ms-source-if-match", type: { name: "String" } } }; const sourceIfNoneMatch = { parameterPath: [ "options", "sourceModifiedAccessConditions", "sourceIfNoneMatch" ], mapper: { serializedName: "x-ms-source-if-none-match", xmlName: "x-ms-source-if-none-match", type: { name: "String" } } }; const sourceIfTags = { parameterPath: ["options", "sourceModifiedAccessConditions", "sourceIfTags"], mapper: { serializedName: "x-ms-source-if-tags", xmlName: "x-ms-source-if-tags", type: { name: "String" } } }; const copySource = { parameterPath: "copySource", mapper: { serializedName: "x-ms-copy-source", required: true, xmlName: "x-ms-copy-source", type: { name: "String" } } }; const blobTagsString = { parameterPath: ["options", "blobTagsString"], mapper: { serializedName: "x-ms-tags", xmlName: "x-ms-tags", type: { name: "String" } } }; const sealBlob = { parameterPath: ["options", "sealBlob"], mapper: { serializedName: "x-ms-seal-blob", xmlName: "x-ms-seal-blob", type: { name: "Boolean" } } }; const legalHold1 = { parameterPath: ["options", "legalHold"], mapper: { serializedName: "x-ms-legal-hold", xmlName: "x-ms-legal-hold", type: { name: "Boolean" } } }; const xMsRequiresSync = { parameterPath: "xMsRequiresSync", mapper: { defaultValue: "true", isConstant: true, serializedName: "x-ms-requires-sync", type: { name: "String" } } }; const sourceContentMD5 = { parameterPath: ["options", "sourceContentMD5"], mapper: { serializedName: "x-ms-source-content-md5", xmlName: "x-ms-source-content-md5", type: { name: "ByteArray" } } }; const copySourceAuthorization = { parameterPath: ["options", "copySourceAuthorization"], mapper: { serializedName: "x-ms-copy-source-authorization", xmlName: "x-ms-copy-source-authorization", type: { name: "String" } } }; const copySourceTags = { parameterPath: ["options", "copySourceTags"], mapper: { serializedName: "x-ms-copy-source-tag-option", xmlName: "x-ms-copy-source-tag-option", type: { name: "Enum", allowedValues: ["REPLACE", "COPY"] } } }; const comp15 = { parameterPath: "comp", mapper: { defaultValue: "copy", isConstant: true, serializedName: "comp", type: { name: "String" } } }; const copyActionAbortConstant = { parameterPath: "copyActionAbortConstant", mapper: { defaultValue: "abort", isConstant: true, serializedName: "x-ms-copy-action", type: { name: "String" } } }; const copyId = { parameterPath: "copyId", mapper: { serializedName: "copyid", required: true, xmlName: "copyid", type: { name: "String" } } }; const comp16 = { parameterPath: "comp", mapper: { defaultValue: "tier", isConstant: true, serializedName: "comp", type: { name: "String" } } }; const tier1 = { parameterPath: "tier", mapper: { serializedName: "x-ms-access-tier", required: true, xmlName: "x-ms-access-tier", type: { name: "Enum", allowedValues: [ "P4", "P6", "P10", "P15", "P20", "P30", "P40", "P50", "P60", "P70", "P80", "Hot", "Cool", "Archive", "Cold" ] } } }; const queryRequest = { parameterPath: ["options", "queryRequest"], mapper: QueryRequest }; const comp17 = { parameterPath: "comp", mapper: { defaultValue: "query", isConstant: true, serializedName: "comp", type: { name: "String" } } }; const comp18 = { parameterPath: "comp", mapper: { defaultValue: "tags", isConstant: true, serializedName: "comp", type: { name: "String" } } }; const tags = { parameterPath: ["options", "tags"], mapper: BlobTags }; const transactionalContentMD5 = { parameterPath: ["options", "transactionalContentMD5"], mapper: { serializedName: "Content-MD5", xmlName: "Content-MD5", type: { name: "ByteArray" } } }; const transactionalContentCrc64 = { parameterPath: ["options", "transactionalContentCrc64"], mapper: { serializedName: "x-ms-content-crc64", xmlName: "x-ms-content-crc64", type: { name: "ByteArray" } } }; const blobType = { parameterPath: "blobType", mapper: { defaultValue: "PageBlob", isConstant: true, serializedName: "x-ms-blob-type", type: { name: "String" } } }; const blobContentLength = { parameterPath: "blobContentLength", mapper: { serializedName: "x-ms-blob-content-length", required: true, xmlName: "x-ms-blob-content-length", type: { name: "Number" } } }; const blobSequenceNumber = { parameterPath: ["options", "blobSequenceNumber"], mapper: { serializedName: "x-ms-blob-sequence-number", xmlName: "x-ms-blob-sequence-number", type: { name: "Number" } } }; const contentType1 = { parameterPath: ["options", "contentType"], mapper: { defaultValue: "application/octet-stream", isConstant: true, serializedName: "Content-Type", type: { name: "String" } } }; const body1 = { parameterPath: "body", mapper: { serializedName: "body", required: true, xmlName: "body", type: { name: "Stream" } } }; const accept2 = { parameterPath: "accept", mapper: { defaultValue: "application/xml", isConstant: true, serializedName: "Accept", type: { name: "String" } } }; const comp19 = { parameterPath: "comp", mapper: { defaultValue: "page", isConstant: true, serializedName: "comp", type: { name: "String" } } }; const pageWrite = { parameterPath: "pageWrite", mapper: { defaultValue: "update", isConstant: true, serializedName: "x-ms-page-write", type: { name: "String" } } }; const ifSequenceNumberLessThanOrEqualTo = { parameterPath: [ "options", "sequenceNumberAccessConditions", "ifSequenceNumberLessThanOrEqualTo" ], mapper: { serializedName: "x-ms-if-sequence-number-le", xmlName: "x-ms-if-sequence-number-le", type: { name: "Number" } } }; const ifSequenceNumberLessThan = { parameterPath: [ "options", "sequenceNumberAccessConditions", "ifSequenceNumberLessThan" ], mapper: { serializedName: "x-ms-if-sequence-number-lt", xmlName: "x-ms-if-sequence-number-lt", type: { name: "Number" } } }; const ifSequenceNumberEqualTo = { parameterPath: [ "options", "sequenceNumberAccessConditions", "ifSequenceNumberEqualTo" ], mapper: { serializedName: "x-ms-if-sequence-number-eq", xmlName: "x-ms-if-sequence-number-eq", type: { name: "Number" } } }; const pageWrite1 = { parameterPath: "pageWrite", mapper: { defaultValue: "clear", isConstant: true, serializedName: "x-ms-page-write", type: { name: "String" } } }; const sourceUrl = { parameterPath: "sourceUrl", mapper: { serializedName: "x-ms-copy-source", required: true, xmlName: "x-ms-copy-source", type: { name: "String" } } }; const sourceRange = { parameterPath: "sourceRange", mapper: { serializedName: "x-ms-source-range", required: true, xmlName: "x-ms-source-range", type: { name: "String" } } }; const sourceContentCrc64 = { parameterPath: ["options", "sourceContentCrc64"], mapper: { serializedName: "x-ms-source-content-crc64", xmlName: "x-ms-source-content-crc64", type: { name: "ByteArray" } } }; const range1 = { parameterPath: "range", mapper: { serializedName: "x-ms-range", required: true, xmlName: "x-ms-range", type: { name: "String" } } }; const comp20 = { parameterPath: "comp", mapper: { defaultValue: "pagelist", isConstant: true, serializedName: "comp", type: { name: "String" } } }; const prevsnapshot = { parameterPath: ["options", "prevsnapshot"], mapper: { serializedName: "prevsnapshot", xmlName: "prevsnapshot", type: { name: "String" } } }; const prevSnapshotUrl = { parameterPath: ["options", "prevSnapshotUrl"], mapper: { serializedName: "x-ms-previous-snapshot-url", xmlName: "x-ms-previous-snapshot-url", type: { name: "String" } } }; const sequenceNumberAction = { parameterPath: "sequenceNumberAction", mapper: { serializedName: "x-ms-sequence-number-action", required: true, xmlName: "x-ms-sequence-number-action", type: { name: "Enum", allowedValues: ["max", "update", "increment"] } } }; const comp21 = { parameterPath: "comp", mapper: { defaultValue: "incrementalcopy", isConstant: true, serializedName: "comp", type: { name: "String" } } }; const blobType1 = { parameterPath: "blobType", mapper: { defaultValue: "AppendBlob", isConstant: true, serializedName: "x-ms-blob-type", type: { name: "String" } } }; const comp22 = { parameterPath: "comp", mapper: { defaultValue: "appendblock", isConstant: true, serializedName: "comp", type: { name: "String" } } }; const maxSize = { parameterPath: ["options", "appendPositionAccessConditions", "maxSize"], mapper: { serializedName: "x-ms-blob-condition-maxsize", xmlName: "x-ms-blob-condition-maxsize", type: { name: "Number" } } }; const appendPosition = { parameterPath: [ "options", "appendPositionAccessConditions", "appendPosition" ], mapper: { serializedName: "x-ms-blob-condition-appendpos", xmlName: "x-ms-blob-condition-appendpos", type: { name: "Number" } } }; const sourceRange1 = { parameterPath: ["options", "sourceRange"], mapper: { serializedName: "x-ms-source-range", xmlName: "x-ms-source-range", type: { name: "String" } } }; const comp23 = { parameterPath: "comp", mapper: { defaultValue: "seal", isConstant: true, serializedName: "comp", type: { name: "String" } } }; const blobType2 = { parameterPath: "blobType", mapper: { defaultValue: "BlockBlob", isConstant: true, serializedName: "x-ms-blob-type", type: { name: "String" } } }; const copySourceBlobProperties = { parameterPath: ["options", "copySourceBlobProperties"], mapper: { serializedName: "x-ms-copy-source-blob-properties", xmlName: "x-ms-copy-source-blob-properties", type: { name: "Boolean" } } }; const comp24 = { parameterPath: "comp", mapper: { defaultValue: "block", isConstant: true, serializedName: "comp", type: { name: "String" } } }; const blockId = { parameterPath: "blockId", mapper: { serializedName: "blockid", required: true, xmlName: "blockid", type: { name: "String" } } }; const blocks = { parameterPath: "blocks", mapper: BlockLookupList }; const comp25 = { parameterPath: "comp", mapper: { defaultValue: "blocklist", isConstant: true, serializedName: "comp", type: { name: "String" } } }; const listType = { parameterPath: "listType", mapper: { defaultValue: "committed", serializedName: "blocklisttype", required: true, xmlName: "blocklisttype", type: { name: "Enum", allowedValues: ["committed", "uncommitted", "all"] } } }; /* * 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. */ /** Class representing a Service. */ class Service { /** * Initialize a new instance of the class Service class. * @param client Reference to the service client */ constructor(client) { this.client = client; } /** * Sets properties for a storage account's Blob service endpoint, including properties for Storage * Analytics and CORS (Cross-Origin Resource Sharing) rules * @param blobServiceProperties The StorageService properties. * @param options The options parameters. */ setProperties(blobServiceProperties, options) { const operationArguments = { blobServiceProperties, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, setPropertiesOperationSpec); } /** * gets the properties of a storage account's Blob service, including properties for Storage Analytics * and CORS (Cross-Origin Resource Sharing) rules. * @param options The options parameters. */ getProperties(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getPropertiesOperationSpec$2); } /** * Retrieves statistics related to replication for the Blob service. It is only available on the * secondary location endpoint when read-access geo-redundant replication is enabled for the storage * account. * @param options The options parameters. */ getStatistics(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getStatisticsOperationSpec); } /** * The List Containers Segment operation returns a list of the containers under the specified account * @param options The options parameters. */ listContainersSegment(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, listContainersSegmentOperationSpec); } /** * Retrieves a user delegation key for the Blob service. This is only a valid operation when using * bearer token authentication. * @param keyInfo Key information * @param options The options parameters. */ getUserDelegationKey(keyInfo, options) { const operationArguments = { keyInfo, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getUserDelegationKeyOperationSpec); } /** * Returns the sku name and account kind * @param options The options parameters. */ getAccountInfo(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getAccountInfoOperationSpec$2); } /** * The Batch operation allows multiple API calls to be embedded into a single HTTP request. * @param contentLength The length of the request. * @param multipartContentType Required. The value of this header must be multipart/mixed with a batch * boundary. Example header value: multipart/mixed; boundary=batch_ * @param body Initial data * @param options The options parameters. */ submitBatch(contentLength, multipartContentType, body, options) { const operationArguments = { contentLength, multipartContentType, body, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, submitBatchOperationSpec$1); } /** * The Filter Blobs operation enables callers to list blobs across all containers whose tags match a * given search expression. Filter blobs searches across all containers within a storage account but * can be scoped within the expression to a single container. * @param options The options parameters. */ filterBlobs(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, filterBlobsOperationSpec$1); } } // Operation Specifications const xmlSerializer$5 = new coreHttp__namespace.Serializer(Mappers, /* isXml */ true); const setPropertiesOperationSpec = { path: "/", httpMethod: "PUT", responses: { 202: { headersMapper: ServiceSetPropertiesHeaders }, default: { bodyMapper: StorageError, headersMapper: ServiceSetPropertiesExceptionHeaders } }, requestBody: blobServiceProperties, queryParameters: [ restype, comp, timeoutInSeconds ], urlParameters: [url], headerParameters: [ contentType, accept, version, requestId ], isXML: true, contentType: "application/xml; charset=utf-8", mediaType: "xml", serializer: xmlSerializer$5 }; const getPropertiesOperationSpec$2 = { path: "/", httpMethod: "GET", responses: { 200: { bodyMapper: BlobServiceProperties, headersMapper: ServiceGetPropertiesHeaders }, default: { bodyMapper: StorageError, headersMapper: ServiceGetPropertiesExceptionHeaders } }, queryParameters: [ restype, comp, timeoutInSeconds ], urlParameters: [url], headerParameters: [ version, requestId, accept1 ], isXML: true, serializer: xmlSerializer$5 }; const getStatisticsOperationSpec = { path: "/", httpMethod: "GET", responses: { 200: { bodyMapper: BlobServiceStatistics, headersMapper: ServiceGetStatisticsHeaders }, default: { bodyMapper: StorageError, headersMapper: ServiceGetStatisticsExceptionHeaders } }, queryParameters: [ restype, timeoutInSeconds, comp1 ], urlParameters: [url], headerParameters: [ version, requestId, accept1 ], isXML: true, serializer: xmlSerializer$5 }; const listContainersSegmentOperationSpec = { path: "/", httpMethod: "GET", responses: { 200: { bodyMapper: ListContainersSegmentResponse, headersMapper: ServiceListContainersSegmentHeaders }, default: { bodyMapper: StorageError, headersMapper: ServiceListContainersSegmentExceptionHeaders } }, queryParameters: [ timeoutInSeconds, comp2, prefix, marker, maxPageSize, include ], urlParameters: [url], headerParameters: [ version, requestId, accept1 ], isXML: true, serializer: xmlSerializer$5 }; const getUserDelegationKeyOperationSpec = { path: "/", httpMethod: "POST", responses: { 200: { bodyMapper: UserDelegationKey, headersMapper: ServiceGetUserDelegationKeyHeaders }, default: { bodyMapper: StorageError, headersMapper: ServiceGetUserDelegationKeyExceptionHeaders } }, requestBody: keyInfo, queryParameters: [ restype, timeoutInSeconds, comp3 ], urlParameters: [url], headerParameters: [ contentType, accept, version, requestId ], isXML: true, contentType: "application/xml; charset=utf-8", mediaType: "xml", serializer: xmlSerializer$5 }; const getAccountInfoOperationSpec$2 = { path: "/", httpMethod: "GET", responses: { 200: { headersMapper: ServiceGetAccountInfoHeaders }, default: { bodyMapper: StorageError, headersMapper: ServiceGetAccountInfoExceptionHeaders } }, queryParameters: [comp, restype1], urlParameters: [url], headerParameters: [version, accept1], isXML: true, serializer: xmlSerializer$5 }; const submitBatchOperationSpec$1 = { path: "/", httpMethod: "POST", responses: { 202: { bodyMapper: { type: { name: "Stream" }, serializedName: "parsedResponse" }, headersMapper: ServiceSubmitBatchHeaders }, default: { bodyMapper: StorageError, headersMapper: ServiceSubmitBatchExceptionHeaders } }, requestBody: body, queryParameters: [timeoutInSeconds, comp4], urlParameters: [url], headerParameters: [ contentType, accept, version, requestId, contentLength, multipartContentType ], isXML: true, contentType: "application/xml; charset=utf-8", mediaType: "xml", serializer: xmlSerializer$5 }; const filterBlobsOperationSpec$1 = { path: "/", httpMethod: "GET", responses: { 200: { bodyMapper: FilterBlobSegment, headersMapper: ServiceFilterBlobsHeaders }, default: { bodyMapper: StorageError, headersMapper: ServiceFilterBlobsExceptionHeaders } }, queryParameters: [ timeoutInSeconds, marker, maxPageSize, comp5, where ], urlParameters: [url], headerParameters: [ version, requestId, accept1 ], isXML: true, serializer: xmlSerializer$5 }; /* * 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. */ /** Class representing a Container. */ class Container { /** * Initialize a new instance of the class Container class. * @param client Reference to the service client */ constructor(client) { this.client = client; } /** * creates a new container under the specified account. If the container with the same name already * exists, the operation fails * @param options The options parameters. */ create(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, createOperationSpec$2); } /** * returns all user-defined metadata and system properties for the specified container. The data * returned does not include the container's list of blobs * @param options The options parameters. */ getProperties(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getPropertiesOperationSpec$1); } /** * operation marks the specified container for deletion. The container and any blobs contained within * it are later deleted during garbage collection * @param options The options parameters. */ delete(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, deleteOperationSpec$1); } /** * operation sets one or more user-defined name-value pairs for the specified container. * @param options The options parameters. */ setMetadata(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, setMetadataOperationSpec$1); } /** * gets the permissions for the specified container. The permissions indicate whether container data * may be accessed publicly. * @param options The options parameters. */ getAccessPolicy(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getAccessPolicyOperationSpec); } /** * sets the permissions for the specified container. The permissions indicate whether blobs in a * container may be accessed publicly. * @param options The options parameters. */ setAccessPolicy(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, setAccessPolicyOperationSpec); } /** * Restores a previously-deleted container. * @param options The options parameters. */ restore(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, restoreOperationSpec); } /** * Renames an existing container. * @param sourceContainerName Required. Specifies the name of the container to rename. * @param options The options parameters. */ rename(sourceContainerName, options) { const operationArguments = { sourceContainerName, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, renameOperationSpec); } /** * The Batch operation allows multiple API calls to be embedded into a single HTTP request. * @param contentLength The length of the request. * @param multipartContentType Required. The value of this header must be multipart/mixed with a batch * boundary. Example header value: multipart/mixed; boundary=batch_ * @param body Initial data * @param options The options parameters. */ submitBatch(contentLength, multipartContentType, body, options) { const operationArguments = { contentLength, multipartContentType, body, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, submitBatchOperationSpec); } /** * The Filter Blobs operation enables callers to list blobs in a container whose tags match a given * search expression. Filter blobs searches within the given container. * @param options The options parameters. */ filterBlobs(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, filterBlobsOperationSpec); } /** * [Update] establishes and manages a lock on a container for delete operations. The lock duration can * be 15 to 60 seconds, or can be infinite * @param options The options parameters. */ acquireLease(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, acquireLeaseOperationSpec$1); } /** * [Update] establishes and manages a lock on a container for delete operations. The lock duration can * be 15 to 60 seconds, or can be infinite * @param leaseId Specifies the current lease ID on the resource. * @param options The options parameters. */ releaseLease(leaseId, options) { const operationArguments = { leaseId, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, releaseLeaseOperationSpec$1); } /** * [Update] establishes and manages a lock on a container for delete operations. The lock duration can * be 15 to 60 seconds, or can be infinite * @param leaseId Specifies the current lease ID on the resource. * @param options The options parameters. */ renewLease(leaseId, options) { const operationArguments = { leaseId, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, renewLeaseOperationSpec$1); } /** * [Update] establishes and manages a lock on a container for delete operations. The lock duration can * be 15 to 60 seconds, or can be infinite * @param options The options parameters. */ breakLease(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, breakLeaseOperationSpec$1); } /** * [Update] establishes and manages a lock on a container for delete operations. The lock duration can * be 15 to 60 seconds, or can be infinite * @param leaseId Specifies the current lease ID on the resource. * @param proposedLeaseId Proposed lease ID, in a GUID string format. The Blob service returns 400 * (Invalid request) if the proposed lease ID is not in the correct format. See Guid Constructor * (String) for a list of valid GUID string formats. * @param options The options parameters. */ changeLease(leaseId, proposedLeaseId, options) { const operationArguments = { leaseId, proposedLeaseId, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, changeLeaseOperationSpec$1); } /** * [Update] The List Blobs operation returns a list of the blobs under the specified container * @param options The options parameters. */ listBlobFlatSegment(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, listBlobFlatSegmentOperationSpec); } /** * [Update] The List Blobs operation returns a list of the blobs under the specified container * @param delimiter When the request includes this parameter, the operation returns a BlobPrefix * element in the response body that acts as a placeholder for all blobs whose names begin with the * same substring up to the appearance of the delimiter character. The delimiter may be a single * character or a string. * @param options The options parameters. */ listBlobHierarchySegment(delimiter, options) { const operationArguments = { delimiter, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, listBlobHierarchySegmentOperationSpec); } /** * Returns the sku name and account kind * @param options The options parameters. */ getAccountInfo(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getAccountInfoOperationSpec$1); } } // Operation Specifications const xmlSerializer$4 = new coreHttp__namespace.Serializer(Mappers, /* isXml */ true); const createOperationSpec$2 = { path: "/{containerName}", httpMethod: "PUT", responses: { 201: { headersMapper: ContainerCreateHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerCreateExceptionHeaders } }, queryParameters: [timeoutInSeconds, restype2], urlParameters: [url], headerParameters: [ version, requestId, accept1, metadata, access, defaultEncryptionScope, preventEncryptionScopeOverride ], isXML: true, serializer: xmlSerializer$4 }; const getPropertiesOperationSpec$1 = { path: "/{containerName}", httpMethod: "GET", responses: { 200: { headersMapper: ContainerGetPropertiesHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerGetPropertiesExceptionHeaders } }, queryParameters: [timeoutInSeconds, restype2], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId ], isXML: true, serializer: xmlSerializer$4 }; const deleteOperationSpec$1 = { path: "/{containerName}", httpMethod: "DELETE", responses: { 202: { headersMapper: ContainerDeleteHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerDeleteExceptionHeaders } }, queryParameters: [timeoutInSeconds, restype2], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ifModifiedSince, ifUnmodifiedSince ], isXML: true, serializer: xmlSerializer$4 }; const setMetadataOperationSpec$1 = { path: "/{containerName}", httpMethod: "PUT", responses: { 200: { headersMapper: ContainerSetMetadataHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerSetMetadataExceptionHeaders } }, queryParameters: [ timeoutInSeconds, restype2, comp6 ], urlParameters: [url], headerParameters: [ version, requestId, accept1, metadata, leaseId, ifModifiedSince ], isXML: true, serializer: xmlSerializer$4 }; const getAccessPolicyOperationSpec = { path: "/{containerName}", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Composite", className: "SignedIdentifier" } } }, serializedName: "SignedIdentifiers", xmlName: "SignedIdentifiers", xmlIsWrapped: true, xmlElementName: "SignedIdentifier" }, headersMapper: ContainerGetAccessPolicyHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerGetAccessPolicyExceptionHeaders } }, queryParameters: [ timeoutInSeconds, restype2, comp7 ], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId ], isXML: true, serializer: xmlSerializer$4 }; const setAccessPolicyOperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { 200: { headersMapper: ContainerSetAccessPolicyHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerSetAccessPolicyExceptionHeaders } }, requestBody: containerAcl, queryParameters: [ timeoutInSeconds, restype2, comp7 ], urlParameters: [url], headerParameters: [ contentType, accept, version, requestId, access, leaseId, ifModifiedSince, ifUnmodifiedSince ], isXML: true, contentType: "application/xml; charset=utf-8", mediaType: "xml", serializer: xmlSerializer$4 }; const restoreOperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { 201: { headersMapper: ContainerRestoreHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerRestoreExceptionHeaders } }, queryParameters: [ timeoutInSeconds, restype2, comp8 ], urlParameters: [url], headerParameters: [ version, requestId, accept1, deletedContainerName, deletedContainerVersion ], isXML: true, serializer: xmlSerializer$4 }; const renameOperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { 200: { headersMapper: ContainerRenameHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerRenameExceptionHeaders } }, queryParameters: [ timeoutInSeconds, restype2, comp9 ], urlParameters: [url], headerParameters: [ version, requestId, accept1, sourceContainerName, sourceLeaseId ], isXML: true, serializer: xmlSerializer$4 }; const submitBatchOperationSpec = { path: "/{containerName}", httpMethod: "POST", responses: { 202: { bodyMapper: { type: { name: "Stream" }, serializedName: "parsedResponse" }, headersMapper: ContainerSubmitBatchHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerSubmitBatchExceptionHeaders } }, requestBody: body, queryParameters: [ timeoutInSeconds, comp4, restype2 ], urlParameters: [url], headerParameters: [ contentType, accept, version, requestId, contentLength, multipartContentType ], isXML: true, contentType: "application/xml; charset=utf-8", mediaType: "xml", serializer: xmlSerializer$4 }; const filterBlobsOperationSpec = { path: "/{containerName}", httpMethod: "GET", responses: { 200: { bodyMapper: FilterBlobSegment, headersMapper: ContainerFilterBlobsHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerFilterBlobsExceptionHeaders } }, queryParameters: [ timeoutInSeconds, marker, maxPageSize, comp5, where, restype2 ], urlParameters: [url], headerParameters: [ version, requestId, accept1 ], isXML: true, serializer: xmlSerializer$4 }; const acquireLeaseOperationSpec$1 = { path: "/{containerName}", httpMethod: "PUT", responses: { 201: { headersMapper: ContainerAcquireLeaseHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerAcquireLeaseExceptionHeaders } }, queryParameters: [ timeoutInSeconds, restype2, comp10 ], urlParameters: [url], headerParameters: [ version, requestId, accept1, ifModifiedSince, ifUnmodifiedSince, action, duration, proposedLeaseId ], isXML: true, serializer: xmlSerializer$4 }; const releaseLeaseOperationSpec$1 = { path: "/{containerName}", httpMethod: "PUT", responses: { 200: { headersMapper: ContainerReleaseLeaseHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerReleaseLeaseExceptionHeaders } }, queryParameters: [ timeoutInSeconds, restype2, comp10 ], urlParameters: [url], headerParameters: [ version, requestId, accept1, ifModifiedSince, ifUnmodifiedSince, action1, leaseId1 ], isXML: true, serializer: xmlSerializer$4 }; const renewLeaseOperationSpec$1 = { path: "/{containerName}", httpMethod: "PUT", responses: { 200: { headersMapper: ContainerRenewLeaseHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerRenewLeaseExceptionHeaders } }, queryParameters: [ timeoutInSeconds, restype2, comp10 ], urlParameters: [url], headerParameters: [ version, requestId, accept1, ifModifiedSince, ifUnmodifiedSince, leaseId1, action2 ], isXML: true, serializer: xmlSerializer$4 }; const breakLeaseOperationSpec$1 = { path: "/{containerName}", httpMethod: "PUT", responses: { 202: { headersMapper: ContainerBreakLeaseHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerBreakLeaseExceptionHeaders } }, queryParameters: [ timeoutInSeconds, restype2, comp10 ], urlParameters: [url], headerParameters: [ version, requestId, accept1, ifModifiedSince, ifUnmodifiedSince, action3, breakPeriod ], isXML: true, serializer: xmlSerializer$4 }; const changeLeaseOperationSpec$1 = { path: "/{containerName}", httpMethod: "PUT", responses: { 200: { headersMapper: ContainerChangeLeaseHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerChangeLeaseExceptionHeaders } }, queryParameters: [ timeoutInSeconds, restype2, comp10 ], urlParameters: [url], headerParameters: [ version, requestId, accept1, ifModifiedSince, ifUnmodifiedSince, leaseId1, action4, proposedLeaseId1 ], isXML: true, serializer: xmlSerializer$4 }; const listBlobFlatSegmentOperationSpec = { path: "/{containerName}", httpMethod: "GET", responses: { 200: { bodyMapper: ListBlobsFlatSegmentResponse, headersMapper: ContainerListBlobFlatSegmentHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerListBlobFlatSegmentExceptionHeaders } }, queryParameters: [ timeoutInSeconds, comp2, prefix, marker, maxPageSize, restype2, include1 ], urlParameters: [url], headerParameters: [ version, requestId, accept1 ], isXML: true, serializer: xmlSerializer$4 }; const listBlobHierarchySegmentOperationSpec = { path: "/{containerName}", httpMethod: "GET", responses: { 200: { bodyMapper: ListBlobsHierarchySegmentResponse, headersMapper: ContainerListBlobHierarchySegmentHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerListBlobHierarchySegmentExceptionHeaders } }, queryParameters: [ timeoutInSeconds, comp2, prefix, marker, maxPageSize, restype2, include1, delimiter ], urlParameters: [url], headerParameters: [ version, requestId, accept1 ], isXML: true, serializer: xmlSerializer$4 }; const getAccountInfoOperationSpec$1 = { path: "/{containerName}", httpMethod: "GET", responses: { 200: { headersMapper: ContainerGetAccountInfoHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerGetAccountInfoExceptionHeaders } }, queryParameters: [comp, restype1], urlParameters: [url], headerParameters: [version, accept1], isXML: true, serializer: xmlSerializer$4 }; /* * 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. */ /** Class representing a Blob. */ class Blob$1 { /** * Initialize a new instance of the class Blob class. * @param client Reference to the service client */ constructor(client) { this.client = client; } /** * The Download operation reads or downloads a blob from the system, including its metadata and * properties. You can also call Download to read a snapshot. * @param options The options parameters. */ download(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, downloadOperationSpec); } /** * The Get Properties operation returns all user-defined metadata, standard HTTP properties, and system * properties for the blob. It does not return the content of the blob. * @param options The options parameters. */ getProperties(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getPropertiesOperationSpec); } /** * If the storage account's soft delete feature is disabled then, when a blob is deleted, it is * permanently removed from the storage account. If the storage account's soft delete feature is * enabled, then, when a blob is deleted, it is marked for deletion and becomes inaccessible * immediately. However, the blob service retains the blob or snapshot for the number of days specified * by the DeleteRetentionPolicy section of [Storage service properties] * (Set-Blob-Service-Properties.md). After the specified number of days has passed, the blob's data is * permanently removed from the storage account. Note that you continue to be charged for the * soft-deleted blob's storage until it is permanently removed. Use the List Blobs API and specify the * "include=deleted" query parameter to discover which blobs and snapshots have been soft deleted. You * can then use the Undelete Blob API to restore a soft-deleted blob. All other operations on a * soft-deleted blob or snapshot causes the service to return an HTTP status code of 404 * (ResourceNotFound). * @param options The options parameters. */ delete(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, deleteOperationSpec); } /** * Undelete a blob that was previously soft deleted * @param options The options parameters. */ undelete(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, undeleteOperationSpec); } /** * Sets the time a blob will expire and be deleted. * @param expiryOptions Required. Indicates mode of the expiry time * @param options The options parameters. */ setExpiry(expiryOptions, options) { const operationArguments = { expiryOptions, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, setExpiryOperationSpec); } /** * The Set HTTP Headers operation sets system properties on the blob * @param options The options parameters. */ setHttpHeaders(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, setHttpHeadersOperationSpec); } /** * The Set Immutability Policy operation sets the immutability policy on the blob * @param options The options parameters. */ setImmutabilityPolicy(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, setImmutabilityPolicyOperationSpec); } /** * The Delete Immutability Policy operation deletes the immutability policy on the blob * @param options The options parameters. */ deleteImmutabilityPolicy(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, deleteImmutabilityPolicyOperationSpec); } /** * The Set Legal Hold operation sets a legal hold on the blob. * @param legalHold Specified if a legal hold should be set on the blob. * @param options The options parameters. */ setLegalHold(legalHold, options) { const operationArguments = { legalHold, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, setLegalHoldOperationSpec); } /** * The Set Blob Metadata operation sets user-defined metadata for the specified blob as one or more * name-value pairs * @param options The options parameters. */ setMetadata(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, setMetadataOperationSpec); } /** * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete * operations * @param options The options parameters. */ acquireLease(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, acquireLeaseOperationSpec); } /** * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete * operations * @param leaseId Specifies the current lease ID on the resource. * @param options The options parameters. */ releaseLease(leaseId, options) { const operationArguments = { leaseId, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, releaseLeaseOperationSpec); } /** * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete * operations * @param leaseId Specifies the current lease ID on the resource. * @param options The options parameters. */ renewLease(leaseId, options) { const operationArguments = { leaseId, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, renewLeaseOperationSpec); } /** * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete * operations * @param leaseId Specifies the current lease ID on the resource. * @param proposedLeaseId Proposed lease ID, in a GUID string format. The Blob service returns 400 * (Invalid request) if the proposed lease ID is not in the correct format. See Guid Constructor * (String) for a list of valid GUID string formats. * @param options The options parameters. */ changeLease(leaseId, proposedLeaseId, options) { const operationArguments = { leaseId, proposedLeaseId, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, changeLeaseOperationSpec); } /** * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete * operations * @param options The options parameters. */ breakLease(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, breakLeaseOperationSpec); } /** * The Create Snapshot operation creates a read-only snapshot of a blob * @param options The options parameters. */ createSnapshot(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, createSnapshotOperationSpec); } /** * The Start Copy From URL operation copies a blob or an internet resource to a new blob. * @param copySource Specifies the name of the source page blob snapshot. This value is a URL of up to * 2 KB in length that specifies a page blob snapshot. The value should be URL-encoded as it would * appear in a request URI. The source blob must either be public or must be authenticated via a shared * access signature. * @param options The options parameters. */ startCopyFromURL(copySource, options) { const operationArguments = { copySource, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, startCopyFromURLOperationSpec); } /** * The Copy From URL operation copies a blob or an internet resource to a new blob. It will not return * a response until the copy is complete. * @param copySource Specifies the name of the source page blob snapshot. This value is a URL of up to * 2 KB in length that specifies a page blob snapshot. The value should be URL-encoded as it would * appear in a request URI. The source blob must either be public or must be authenticated via a shared * access signature. * @param options The options parameters. */ copyFromURL(copySource, options) { const operationArguments = { copySource, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, copyFromURLOperationSpec); } /** * The Abort Copy From URL operation aborts a pending Copy From URL operation, and leaves a destination * blob with zero length and full metadata. * @param copyId The copy identifier provided in the x-ms-copy-id header of the original Copy Blob * operation. * @param options The options parameters. */ abortCopyFromURL(copyId, options) { const operationArguments = { copyId, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, abortCopyFromURLOperationSpec); } /** * The Set Tier operation sets the tier on a blob. The operation is allowed on a page blob in a premium * storage account and on a block blob in a blob storage account (locally redundant storage only). A * premium page blob's tier determines the allowed size, IOPS, and bandwidth of the blob. A block * blob's tier determines Hot/Cool/Archive storage type. This operation does not update the blob's * ETag. * @param tier Indicates the tier to be set on the blob. * @param options The options parameters. */ setTier(tier, options) { const operationArguments = { tier, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, setTierOperationSpec); } /** * Returns the sku name and account kind * @param options The options parameters. */ getAccountInfo(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getAccountInfoOperationSpec); } /** * The Query operation enables users to select/project on blob data by providing simple query * expressions. * @param options The options parameters. */ query(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, queryOperationSpec); } /** * The Get Tags operation enables users to get the tags associated with a blob. * @param options The options parameters. */ getTags(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getTagsOperationSpec); } /** * The Set Tags operation enables users to set tags on a blob. * @param options The options parameters. */ setTags(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, setTagsOperationSpec); } } // Operation Specifications const xmlSerializer$3 = new coreHttp__namespace.Serializer(Mappers, /* isXml */ true); const downloadOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Stream" }, serializedName: "parsedResponse" }, headersMapper: BlobDownloadHeaders }, 206: { bodyMapper: { type: { name: "Stream" }, serializedName: "parsedResponse" }, headersMapper: BlobDownloadHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobDownloadExceptionHeaders } }, queryParameters: [ timeoutInSeconds, snapshot, versionId ], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ifModifiedSince, ifUnmodifiedSince, range, rangeGetContentMD5, rangeGetContentCRC64, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags ], isXML: true, serializer: xmlSerializer$3 }; const getPropertiesOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "HEAD", responses: { 200: { headersMapper: BlobGetPropertiesHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobGetPropertiesExceptionHeaders } }, queryParameters: [ timeoutInSeconds, snapshot, versionId ], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ifModifiedSince, ifUnmodifiedSince, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags ], isXML: true, serializer: xmlSerializer$3 }; const deleteOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "DELETE", responses: { 202: { headersMapper: BlobDeleteHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobDeleteExceptionHeaders } }, queryParameters: [ timeoutInSeconds, snapshot, versionId, blobDeleteType ], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags, deleteSnapshots ], isXML: true, serializer: xmlSerializer$3 }; const undeleteOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 200: { headersMapper: BlobUndeleteHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobUndeleteExceptionHeaders } }, queryParameters: [timeoutInSeconds, comp8], urlParameters: [url], headerParameters: [ version, requestId, accept1 ], isXML: true, serializer: xmlSerializer$3 }; const setExpiryOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 200: { headersMapper: BlobSetExpiryHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobSetExpiryExceptionHeaders } }, queryParameters: [timeoutInSeconds, comp11], urlParameters: [url], headerParameters: [ version, requestId, accept1, expiryOptions, expiresOn ], isXML: true, serializer: xmlSerializer$3 }; const setHttpHeadersOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 200: { headersMapper: BlobSetHttpHeadersHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobSetHttpHeadersExceptionHeaders } }, queryParameters: [comp, timeoutInSeconds], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags, blobCacheControl, blobContentType, blobContentMD5, blobContentEncoding, blobContentLanguage, blobContentDisposition ], isXML: true, serializer: xmlSerializer$3 }; const setImmutabilityPolicyOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 200: { headersMapper: BlobSetImmutabilityPolicyHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobSetImmutabilityPolicyExceptionHeaders } }, queryParameters: [timeoutInSeconds, comp12], urlParameters: [url], headerParameters: [ version, requestId, accept1, ifUnmodifiedSince, immutabilityPolicyExpiry, immutabilityPolicyMode ], isXML: true, serializer: xmlSerializer$3 }; const deleteImmutabilityPolicyOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "DELETE", responses: { 200: { headersMapper: BlobDeleteImmutabilityPolicyHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobDeleteImmutabilityPolicyExceptionHeaders } }, queryParameters: [timeoutInSeconds, comp12], urlParameters: [url], headerParameters: [ version, requestId, accept1 ], isXML: true, serializer: xmlSerializer$3 }; const setLegalHoldOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 200: { headersMapper: BlobSetLegalHoldHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobSetLegalHoldExceptionHeaders } }, queryParameters: [timeoutInSeconds, comp13], urlParameters: [url], headerParameters: [ version, requestId, accept1, legalHold ], isXML: true, serializer: xmlSerializer$3 }; const setMetadataOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 200: { headersMapper: BlobSetMetadataHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobSetMetadataExceptionHeaders } }, queryParameters: [timeoutInSeconds, comp6], urlParameters: [url], headerParameters: [ version, requestId, accept1, metadata, leaseId, ifModifiedSince, ifUnmodifiedSince, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, encryptionScope ], isXML: true, serializer: xmlSerializer$3 }; const acquireLeaseOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: BlobAcquireLeaseHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobAcquireLeaseExceptionHeaders } }, queryParameters: [timeoutInSeconds, comp10], urlParameters: [url], headerParameters: [ version, requestId, accept1, ifModifiedSince, ifUnmodifiedSince, action, duration, proposedLeaseId, ifMatch, ifNoneMatch, ifTags ], isXML: true, serializer: xmlSerializer$3 }; const releaseLeaseOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 200: { headersMapper: BlobReleaseLeaseHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobReleaseLeaseExceptionHeaders } }, queryParameters: [timeoutInSeconds, comp10], urlParameters: [url], headerParameters: [ version, requestId, accept1, ifModifiedSince, ifUnmodifiedSince, action1, leaseId1, ifMatch, ifNoneMatch, ifTags ], isXML: true, serializer: xmlSerializer$3 }; const renewLeaseOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 200: { headersMapper: BlobRenewLeaseHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobRenewLeaseExceptionHeaders } }, queryParameters: [timeoutInSeconds, comp10], urlParameters: [url], headerParameters: [ version, requestId, accept1, ifModifiedSince, ifUnmodifiedSince, leaseId1, action2, ifMatch, ifNoneMatch, ifTags ], isXML: true, serializer: xmlSerializer$3 }; const changeLeaseOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 200: { headersMapper: BlobChangeLeaseHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobChangeLeaseExceptionHeaders } }, queryParameters: [timeoutInSeconds, comp10], urlParameters: [url], headerParameters: [ version, requestId, accept1, ifModifiedSince, ifUnmodifiedSince, leaseId1, action4, proposedLeaseId1, ifMatch, ifNoneMatch, ifTags ], isXML: true, serializer: xmlSerializer$3 }; const breakLeaseOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 202: { headersMapper: BlobBreakLeaseHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobBreakLeaseExceptionHeaders } }, queryParameters: [timeoutInSeconds, comp10], urlParameters: [url], headerParameters: [ version, requestId, accept1, ifModifiedSince, ifUnmodifiedSince, action3, breakPeriod, ifMatch, ifNoneMatch, ifTags ], isXML: true, serializer: xmlSerializer$3 }; const createSnapshotOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: BlobCreateSnapshotHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobCreateSnapshotExceptionHeaders } }, queryParameters: [timeoutInSeconds, comp14], urlParameters: [url], headerParameters: [ version, requestId, accept1, metadata, leaseId, ifModifiedSince, ifUnmodifiedSince, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, encryptionScope ], isXML: true, serializer: xmlSerializer$3 }; const startCopyFromURLOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 202: { headersMapper: BlobStartCopyFromURLHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobStartCopyFromURLExceptionHeaders } }, queryParameters: [timeoutInSeconds], urlParameters: [url], headerParameters: [ version, requestId, accept1, metadata, leaseId, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags, immutabilityPolicyExpiry, immutabilityPolicyMode, tier, rehydratePriority, sourceIfModifiedSince, sourceIfUnmodifiedSince, sourceIfMatch, sourceIfNoneMatch, sourceIfTags, copySource, blobTagsString, sealBlob, legalHold1 ], isXML: true, serializer: xmlSerializer$3 }; const copyFromURLOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 202: { headersMapper: BlobCopyFromURLHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobCopyFromURLExceptionHeaders } }, queryParameters: [timeoutInSeconds], urlParameters: [url], headerParameters: [ version, requestId, accept1, metadata, leaseId, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags, immutabilityPolicyExpiry, immutabilityPolicyMode, encryptionScope, tier, sourceIfModifiedSince, sourceIfUnmodifiedSince, sourceIfMatch, sourceIfNoneMatch, copySource, blobTagsString, legalHold1, xMsRequiresSync, sourceContentMD5, copySourceAuthorization, copySourceTags ], isXML: true, serializer: xmlSerializer$3 }; const abortCopyFromURLOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 204: { headersMapper: BlobAbortCopyFromURLHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobAbortCopyFromURLExceptionHeaders } }, queryParameters: [ timeoutInSeconds, comp15, copyId ], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, copyActionAbortConstant ], isXML: true, serializer: xmlSerializer$3 }; const setTierOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 200: { headersMapper: BlobSetTierHeaders }, 202: { headersMapper: BlobSetTierHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobSetTierExceptionHeaders } }, queryParameters: [ timeoutInSeconds, snapshot, versionId, comp16 ], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ifTags, rehydratePriority, tier1 ], isXML: true, serializer: xmlSerializer$3 }; const getAccountInfoOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "GET", responses: { 200: { headersMapper: BlobGetAccountInfoHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobGetAccountInfoExceptionHeaders } }, queryParameters: [comp, restype1], urlParameters: [url], headerParameters: [version, accept1], isXML: true, serializer: xmlSerializer$3 }; const queryOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "POST", responses: { 200: { bodyMapper: { type: { name: "Stream" }, serializedName: "parsedResponse" }, headersMapper: BlobQueryHeaders }, 206: { bodyMapper: { type: { name: "Stream" }, serializedName: "parsedResponse" }, headersMapper: BlobQueryHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobQueryExceptionHeaders } }, requestBody: queryRequest, queryParameters: [ timeoutInSeconds, snapshot, comp17 ], urlParameters: [url], headerParameters: [ contentType, accept, version, requestId, leaseId, ifModifiedSince, ifUnmodifiedSince, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags ], isXML: true, contentType: "application/xml; charset=utf-8", mediaType: "xml", serializer: xmlSerializer$3 }; const getTagsOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "GET", responses: { 200: { bodyMapper: BlobTags, headersMapper: BlobGetTagsHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobGetTagsExceptionHeaders } }, queryParameters: [ timeoutInSeconds, snapshot, versionId, comp18 ], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ifTags ], isXML: true, serializer: xmlSerializer$3 }; const setTagsOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 204: { headersMapper: BlobSetTagsHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobSetTagsExceptionHeaders } }, requestBody: tags, queryParameters: [ timeoutInSeconds, versionId, comp18 ], urlParameters: [url], headerParameters: [ contentType, accept, version, requestId, leaseId, ifTags, transactionalContentMD5, transactionalContentCrc64 ], isXML: true, contentType: "application/xml; charset=utf-8", mediaType: "xml", serializer: xmlSerializer$3 }; /* * 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. */ /** Class representing a PageBlob. */ class PageBlob { /** * Initialize a new instance of the class PageBlob class. * @param client Reference to the service client */ constructor(client) { this.client = client; } /** * The Create operation creates a new page blob. * @param contentLength The length of the request. * @param blobContentLength This header specifies the maximum size for the page blob, up to 1 TB. The * page blob size must be aligned to a 512-byte boundary. * @param options The options parameters. */ create(contentLength, blobContentLength, options) { const operationArguments = { contentLength, blobContentLength, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, createOperationSpec$1); } /** * The Upload Pages operation writes a range of pages to a page blob * @param contentLength The length of the request. * @param body Initial data * @param options The options parameters. */ uploadPages(contentLength, body, options) { const operationArguments = { contentLength, body, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, uploadPagesOperationSpec); } /** * The Clear Pages operation clears a set of pages from a page blob * @param contentLength The length of the request. * @param options The options parameters. */ clearPages(contentLength, options) { const operationArguments = { contentLength, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, clearPagesOperationSpec); } /** * The Upload Pages operation writes a range of pages to a page blob where the contents are read from a * URL * @param sourceUrl Specify a URL to the copy source. * @param sourceRange Bytes of source data in the specified range. The length of this range should * match the ContentLength header and x-ms-range/Range destination range header. * @param contentLength The length of the request. * @param range The range of bytes to which the source range would be written. The range should be 512 * aligned and range-end is required. * @param options The options parameters. */ uploadPagesFromURL(sourceUrl, sourceRange, contentLength, range, options) { const operationArguments = { sourceUrl, sourceRange, contentLength, range, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, uploadPagesFromURLOperationSpec); } /** * The Get Page Ranges operation returns the list of valid page ranges for a page blob or snapshot of a * page blob * @param options The options parameters. */ getPageRanges(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getPageRangesOperationSpec); } /** * The Get Page Ranges Diff operation returns the list of valid page ranges for a page blob that were * changed between target blob and previous snapshot. * @param options The options parameters. */ getPageRangesDiff(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getPageRangesDiffOperationSpec); } /** * Resize the Blob * @param blobContentLength This header specifies the maximum size for the page blob, up to 1 TB. The * page blob size must be aligned to a 512-byte boundary. * @param options The options parameters. */ resize(blobContentLength, options) { const operationArguments = { blobContentLength, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, resizeOperationSpec); } /** * Update the sequence number of the blob * @param sequenceNumberAction Required if the x-ms-blob-sequence-number header is set for the request. * This property applies to page blobs only. This property indicates how the service should modify the * blob's sequence number * @param options The options parameters. */ updateSequenceNumber(sequenceNumberAction, options) { const operationArguments = { sequenceNumberAction, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, updateSequenceNumberOperationSpec); } /** * The Copy Incremental operation copies a snapshot of the source page blob to a destination page blob. * The snapshot is copied such that only the differential changes between the previously copied * snapshot are transferred to the destination. The copied snapshots are complete copies of the * original snapshot and can be read or copied from as usual. This API is supported since REST version * 2016-05-31. * @param copySource Specifies the name of the source page blob snapshot. This value is a URL of up to * 2 KB in length that specifies a page blob snapshot. The value should be URL-encoded as it would * appear in a request URI. The source blob must either be public or must be authenticated via a shared * access signature. * @param options The options parameters. */ copyIncremental(copySource, options) { const operationArguments = { copySource, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, copyIncrementalOperationSpec); } } // Operation Specifications const xmlSerializer$2 = new coreHttp__namespace.Serializer(Mappers, /* isXml */ true); const serializer$2 = new coreHttp__namespace.Serializer(Mappers, /* isXml */ false); const createOperationSpec$1 = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: PageBlobCreateHeaders }, default: { bodyMapper: StorageError, headersMapper: PageBlobCreateExceptionHeaders } }, queryParameters: [timeoutInSeconds], urlParameters: [url], headerParameters: [ version, requestId, accept1, contentLength, metadata, leaseId, ifModifiedSince, ifUnmodifiedSince, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, blobCacheControl, blobContentType, blobContentMD5, blobContentEncoding, blobContentLanguage, blobContentDisposition, immutabilityPolicyExpiry, immutabilityPolicyMode, encryptionScope, tier, blobTagsString, legalHold1, blobType, blobContentLength, blobSequenceNumber ], isXML: true, serializer: xmlSerializer$2 }; const uploadPagesOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: PageBlobUploadPagesHeaders }, default: { bodyMapper: StorageError, headersMapper: PageBlobUploadPagesExceptionHeaders } }, requestBody: body1, queryParameters: [timeoutInSeconds, comp19], urlParameters: [url], headerParameters: [ version, requestId, contentLength, leaseId, ifModifiedSince, ifUnmodifiedSince, range, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, encryptionScope, transactionalContentMD5, transactionalContentCrc64, contentType1, accept2, pageWrite, ifSequenceNumberLessThanOrEqualTo, ifSequenceNumberLessThan, ifSequenceNumberEqualTo ], mediaType: "binary", serializer: serializer$2 }; const clearPagesOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: PageBlobClearPagesHeaders }, default: { bodyMapper: StorageError, headersMapper: PageBlobClearPagesExceptionHeaders } }, queryParameters: [timeoutInSeconds, comp19], urlParameters: [url], headerParameters: [ version, requestId, accept1, contentLength, leaseId, ifModifiedSince, ifUnmodifiedSince, range, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, encryptionScope, ifSequenceNumberLessThanOrEqualTo, ifSequenceNumberLessThan, ifSequenceNumberEqualTo, pageWrite1 ], isXML: true, serializer: xmlSerializer$2 }; const uploadPagesFromURLOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: PageBlobUploadPagesFromURLHeaders }, default: { bodyMapper: StorageError, headersMapper: PageBlobUploadPagesFromURLExceptionHeaders } }, queryParameters: [timeoutInSeconds, comp19], urlParameters: [url], headerParameters: [ version, requestId, accept1, contentLength, leaseId, ifModifiedSince, ifUnmodifiedSince, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, encryptionScope, sourceIfModifiedSince, sourceIfUnmodifiedSince, sourceIfMatch, sourceIfNoneMatch, sourceContentMD5, copySourceAuthorization, pageWrite, ifSequenceNumberLessThanOrEqualTo, ifSequenceNumberLessThan, ifSequenceNumberEqualTo, sourceUrl, sourceRange, sourceContentCrc64, range1 ], isXML: true, serializer: xmlSerializer$2 }; const getPageRangesOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "GET", responses: { 200: { bodyMapper: PageList, headersMapper: PageBlobGetPageRangesHeaders }, default: { bodyMapper: StorageError, headersMapper: PageBlobGetPageRangesExceptionHeaders } }, queryParameters: [ timeoutInSeconds, marker, maxPageSize, snapshot, comp20 ], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ifModifiedSince, ifUnmodifiedSince, range, ifMatch, ifNoneMatch, ifTags ], isXML: true, serializer: xmlSerializer$2 }; const getPageRangesDiffOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "GET", responses: { 200: { bodyMapper: PageList, headersMapper: PageBlobGetPageRangesDiffHeaders }, default: { bodyMapper: StorageError, headersMapper: PageBlobGetPageRangesDiffExceptionHeaders } }, queryParameters: [ timeoutInSeconds, marker, maxPageSize, snapshot, comp20, prevsnapshot ], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ifModifiedSince, ifUnmodifiedSince, range, ifMatch, ifNoneMatch, ifTags, prevSnapshotUrl ], isXML: true, serializer: xmlSerializer$2 }; const resizeOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 200: { headersMapper: PageBlobResizeHeaders }, default: { bodyMapper: StorageError, headersMapper: PageBlobResizeExceptionHeaders } }, queryParameters: [comp, timeoutInSeconds], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ifModifiedSince, ifUnmodifiedSince, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, encryptionScope, blobContentLength ], isXML: true, serializer: xmlSerializer$2 }; const updateSequenceNumberOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 200: { headersMapper: PageBlobUpdateSequenceNumberHeaders }, default: { bodyMapper: StorageError, headersMapper: PageBlobUpdateSequenceNumberExceptionHeaders } }, queryParameters: [comp, timeoutInSeconds], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags, blobSequenceNumber, sequenceNumberAction ], isXML: true, serializer: xmlSerializer$2 }; const copyIncrementalOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 202: { headersMapper: PageBlobCopyIncrementalHeaders }, default: { bodyMapper: StorageError, headersMapper: PageBlobCopyIncrementalExceptionHeaders } }, queryParameters: [timeoutInSeconds, comp21], urlParameters: [url], headerParameters: [ version, requestId, accept1, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags, copySource ], isXML: true, serializer: xmlSerializer$2 }; /* * 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. */ /** Class representing a AppendBlob. */ class AppendBlob { /** * Initialize a new instance of the class AppendBlob class. * @param client Reference to the service client */ constructor(client) { this.client = client; } /** * The Create Append Blob operation creates a new append blob. * @param contentLength The length of the request. * @param options The options parameters. */ create(contentLength, options) { const operationArguments = { contentLength, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, createOperationSpec); } /** * The Append Block operation commits a new block of data to the end of an existing append blob. The * Append Block operation is permitted only if the blob was created with x-ms-blob-type set to * AppendBlob. Append Block is supported only on version 2015-02-21 version or later. * @param contentLength The length of the request. * @param body Initial data * @param options The options parameters. */ appendBlock(contentLength, body, options) { const operationArguments = { contentLength, body, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, appendBlockOperationSpec); } /** * The Append Block operation commits a new block of data to the end of an existing append blob where * the contents are read from a source url. The Append Block operation is permitted only if the blob * was created with x-ms-blob-type set to AppendBlob. Append Block is supported only on version * 2015-02-21 version or later. * @param sourceUrl Specify a URL to the copy source. * @param contentLength The length of the request. * @param options The options parameters. */ appendBlockFromUrl(sourceUrl, contentLength, options) { const operationArguments = { sourceUrl, contentLength, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, appendBlockFromUrlOperationSpec); } /** * The Seal operation seals the Append Blob to make it read-only. Seal is supported only on version * 2019-12-12 version or later. * @param options The options parameters. */ seal(options) { const operationArguments = { options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, sealOperationSpec); } } // Operation Specifications const xmlSerializer$1 = new coreHttp__namespace.Serializer(Mappers, /* isXml */ true); const serializer$1 = new coreHttp__namespace.Serializer(Mappers, /* isXml */ false); const createOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: AppendBlobCreateHeaders }, default: { bodyMapper: StorageError, headersMapper: AppendBlobCreateExceptionHeaders } }, queryParameters: [timeoutInSeconds], urlParameters: [url], headerParameters: [ version, requestId, accept1, contentLength, metadata, leaseId, ifModifiedSince, ifUnmodifiedSince, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, blobCacheControl, blobContentType, blobContentMD5, blobContentEncoding, blobContentLanguage, blobContentDisposition, immutabilityPolicyExpiry, immutabilityPolicyMode, encryptionScope, blobTagsString, legalHold1, blobType1 ], isXML: true, serializer: xmlSerializer$1 }; const appendBlockOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: AppendBlobAppendBlockHeaders }, default: { bodyMapper: StorageError, headersMapper: AppendBlobAppendBlockExceptionHeaders } }, requestBody: body1, queryParameters: [timeoutInSeconds, comp22], urlParameters: [url], headerParameters: [ version, requestId, contentLength, leaseId, ifModifiedSince, ifUnmodifiedSince, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, encryptionScope, transactionalContentMD5, transactionalContentCrc64, contentType1, accept2, maxSize, appendPosition ], mediaType: "binary", serializer: serializer$1 }; const appendBlockFromUrlOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: AppendBlobAppendBlockFromUrlHeaders }, default: { bodyMapper: StorageError, headersMapper: AppendBlobAppendBlockFromUrlExceptionHeaders } }, queryParameters: [timeoutInSeconds, comp22], urlParameters: [url], headerParameters: [ version, requestId, accept1, contentLength, leaseId, ifModifiedSince, ifUnmodifiedSince, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, encryptionScope, sourceIfModifiedSince, sourceIfUnmodifiedSince, sourceIfMatch, sourceIfNoneMatch, sourceContentMD5, copySourceAuthorization, transactionalContentMD5, sourceUrl, sourceContentCrc64, maxSize, appendPosition, sourceRange1 ], isXML: true, serializer: xmlSerializer$1 }; const sealOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 200: { headersMapper: AppendBlobSealHeaders }, default: { bodyMapper: StorageError, headersMapper: AppendBlobSealExceptionHeaders } }, queryParameters: [timeoutInSeconds, comp23], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, appendPosition ], isXML: true, serializer: xmlSerializer$1 }; /* * 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. */ /** Class representing a BlockBlob. */ class BlockBlob { /** * Initialize a new instance of the class BlockBlob class. * @param client Reference to the service client */ constructor(client) { this.client = client; } /** * The Upload Block Blob operation updates the content of an existing block blob. Updating an existing * block blob overwrites any existing metadata on the blob. Partial updates are not supported with Put * Blob; the content of the existing blob is overwritten with the content of the new blob. To perform a * partial update of the content of a block blob, use the Put Block List operation. * @param contentLength The length of the request. * @param body Initial data * @param options The options parameters. */ upload(contentLength, body, options) { const operationArguments = { contentLength, body, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, uploadOperationSpec); } /** * The Put Blob from URL operation creates a new Block Blob where the contents of the blob are read * from a given URL. This API is supported beginning with the 2020-04-08 version. Partial updates are * not supported with Put Blob from URL; the content of an existing blob is overwritten with the * content of the new blob. To perform partial updates to a block blob’s contents using a source URL, * use the Put Block from URL API in conjunction with Put Block List. * @param contentLength The length of the request. * @param copySource Specifies the name of the source page blob snapshot. This value is a URL of up to * 2 KB in length that specifies a page blob snapshot. The value should be URL-encoded as it would * appear in a request URI. The source blob must either be public or must be authenticated via a shared * access signature. * @param options The options parameters. */ putBlobFromUrl(contentLength, copySource, options) { const operationArguments = { contentLength, copySource, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, putBlobFromUrlOperationSpec); } /** * The Stage Block operation creates a new block to be committed as part of a blob * @param blockId A valid Base64 string value that identifies the block. Prior to encoding, the string * must be less than or equal to 64 bytes in size. For a given blob, the length of the value specified * for the blockid parameter must be the same size for each block. * @param contentLength The length of the request. * @param body Initial data * @param options The options parameters. */ stageBlock(blockId, contentLength, body, options) { const operationArguments = { blockId, contentLength, body, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, stageBlockOperationSpec); } /** * The Stage Block operation creates a new block to be committed as part of a blob where the contents * are read from a URL. * @param blockId A valid Base64 string value that identifies the block. Prior to encoding, the string * must be less than or equal to 64 bytes in size. For a given blob, the length of the value specified * for the blockid parameter must be the same size for each block. * @param contentLength The length of the request. * @param sourceUrl Specify a URL to the copy source. * @param options The options parameters. */ stageBlockFromURL(blockId, contentLength, sourceUrl, options) { const operationArguments = { blockId, contentLength, sourceUrl, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, stageBlockFromURLOperationSpec); } /** * The Commit Block List operation writes a blob by specifying the list of block IDs that make up the * blob. In order to be written as part of a blob, a block must have been successfully written to the * server in a prior Put Block operation. You can call Put Block List to update a blob by uploading * only those blocks that have changed, then committing the new and existing blocks together. You can * do this by specifying whether to commit a block from the committed block list or from the * uncommitted block list, or to commit the most recently uploaded version of the block, whichever list * it may belong to. * @param blocks Blob Blocks. * @param options The options parameters. */ commitBlockList(blocks, options) { const operationArguments = { blocks, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, commitBlockListOperationSpec); } /** * The Get Block List operation retrieves the list of blocks that have been uploaded as part of a block * blob * @param listType Specifies whether to return the list of committed blocks, the list of uncommitted * blocks, or both lists together. * @param options The options parameters. */ getBlockList(listType, options) { const operationArguments = { listType, options: coreHttp__namespace.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getBlockListOperationSpec); } } // Operation Specifications const xmlSerializer = new coreHttp__namespace.Serializer(Mappers, /* isXml */ true); const serializer = new coreHttp__namespace.Serializer(Mappers, /* isXml */ false); const uploadOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: BlockBlobUploadHeaders }, default: { bodyMapper: StorageError, headersMapper: BlockBlobUploadExceptionHeaders } }, requestBody: body1, queryParameters: [timeoutInSeconds], urlParameters: [url], headerParameters: [ version, requestId, contentLength, metadata, leaseId, ifModifiedSince, ifUnmodifiedSince, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, blobCacheControl, blobContentType, blobContentMD5, blobContentEncoding, blobContentLanguage, blobContentDisposition, immutabilityPolicyExpiry, immutabilityPolicyMode, encryptionScope, tier, blobTagsString, legalHold1, transactionalContentMD5, transactionalContentCrc64, contentType1, accept2, blobType2 ], mediaType: "binary", serializer }; const putBlobFromUrlOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: BlockBlobPutBlobFromUrlHeaders }, default: { bodyMapper: StorageError, headersMapper: BlockBlobPutBlobFromUrlExceptionHeaders } }, queryParameters: [timeoutInSeconds], urlParameters: [url], headerParameters: [ version, requestId, accept1, contentLength, metadata, leaseId, ifModifiedSince, ifUnmodifiedSince, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, blobCacheControl, blobContentType, blobContentMD5, blobContentEncoding, blobContentLanguage, blobContentDisposition, encryptionScope, tier, sourceIfModifiedSince, sourceIfUnmodifiedSince, sourceIfMatch, sourceIfNoneMatch, sourceIfTags, copySource, blobTagsString, sourceContentMD5, copySourceAuthorization, copySourceTags, transactionalContentMD5, blobType2, copySourceBlobProperties ], isXML: true, serializer: xmlSerializer }; const stageBlockOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: BlockBlobStageBlockHeaders }, default: { bodyMapper: StorageError, headersMapper: BlockBlobStageBlockExceptionHeaders } }, requestBody: body1, queryParameters: [ timeoutInSeconds, comp24, blockId ], urlParameters: [url], headerParameters: [ version, requestId, contentLength, leaseId, encryptionKey, encryptionKeySha256, encryptionAlgorithm, encryptionScope, transactionalContentMD5, transactionalContentCrc64, contentType1, accept2 ], mediaType: "binary", serializer }; const stageBlockFromURLOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: BlockBlobStageBlockFromURLHeaders }, default: { bodyMapper: StorageError, headersMapper: BlockBlobStageBlockFromURLExceptionHeaders } }, queryParameters: [ timeoutInSeconds, comp24, blockId ], urlParameters: [url], headerParameters: [ version, requestId, accept1, contentLength, leaseId, encryptionKey, encryptionKeySha256, encryptionAlgorithm, encryptionScope, sourceIfModifiedSince, sourceIfUnmodifiedSince, sourceIfMatch, sourceIfNoneMatch, sourceContentMD5, copySourceAuthorization, sourceUrl, sourceContentCrc64, sourceRange1 ], isXML: true, serializer: xmlSerializer }; const commitBlockListOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { 201: { headersMapper: BlockBlobCommitBlockListHeaders }, default: { bodyMapper: StorageError, headersMapper: BlockBlobCommitBlockListExceptionHeaders } }, requestBody: blocks, queryParameters: [timeoutInSeconds, comp25], urlParameters: [url], headerParameters: [ contentType, accept, version, requestId, metadata, leaseId, ifModifiedSince, ifUnmodifiedSince, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifMatch, ifNoneMatch, ifTags, blobCacheControl, blobContentType, blobContentMD5, blobContentEncoding, blobContentLanguage, blobContentDisposition, immutabilityPolicyExpiry, immutabilityPolicyMode, encryptionScope, tier, blobTagsString, legalHold1, transactionalContentMD5, transactionalContentCrc64 ], isXML: true, contentType: "application/xml; charset=utf-8", mediaType: "xml", serializer: xmlSerializer }; const getBlockListOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "GET", responses: { 200: { bodyMapper: BlockList, headersMapper: BlockBlobGetBlockListHeaders }, default: { bodyMapper: StorageError, headersMapper: BlockBlobGetBlockListExceptionHeaders } }, queryParameters: [ timeoutInSeconds, snapshot, comp25, listType ], urlParameters: [url], headerParameters: [ version, requestId, accept1, leaseId, ifTags ], isXML: true, serializer: xmlSerializer }; // Copyright (c) Microsoft Corporation. /** * The `@azure/logger` configuration for this package. */ const logger = logger$1.createClientLogger("storage-blob"); // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. const SDK_VERSION = "12.13.0"; const SERVICE_VERSION = "2021-12-02"; 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. */ const StorageOAuthScopes = "https://storage.azure.com/.default"; const URLConstants = { Parameters: { FORCE_BROWSER_NO_CACHE: "_", SIGNATURE: "sig", SNAPSHOT: "snapshot", VERSIONID: "versionid", TIMEOUT: "timeout", }, }; const HTTPURLConnection = { HTTP_ACCEPTED: 202, HTTP_CONFLICT: 409, HTTP_NOT_FOUND: 404, HTTP_PRECON_FAILED: 412, HTTP_RANGE_NOT_SATISFIABLE: 416, }; const HeaderConstants = { AUTHORIZATION: "Authorization", AUTHORIZATION_SCHEME: "Bearer", CONTENT_ENCODING: "Content-Encoding", CONTENT_ID: "Content-ID", CONTENT_LANGUAGE: "Content-Language", CONTENT_LENGTH: "Content-Length", CONTENT_MD5: "Content-Md5", CONTENT_TRANSFER_ENCODING: "Content-Transfer-Encoding", CONTENT_TYPE: "Content-Type", COOKIE: "Cookie", DATE: "date", IF_MATCH: "if-match", IF_MODIFIED_SINCE: "if-modified-since", IF_NONE_MATCH: "if-none-match", IF_UNMODIFIED_SINCE: "if-unmodified-since", PREFIX_FOR_STORAGE: "x-ms-", RANGE: "Range", USER_AGENT: "User-Agent", X_MS_CLIENT_REQUEST_ID: "x-ms-client-request-id", X_MS_COPY_SOURCE: "x-ms-copy-source", X_MS_DATE: "x-ms-date", X_MS_ERROR_CODE: "x-ms-error-code", X_MS_VERSION: "x-ms-version", }; const ETagNone = ""; const ETagAny = "*"; const SIZE_1_MB = 1 * 1024 * 1024; const BATCH_MAX_REQUEST = 256; const BATCH_MAX_PAYLOAD_IN_BYTES = 4 * SIZE_1_MB; const HTTP_LINE_ENDING = "\r\n"; const HTTP_VERSION_1_1 = "HTTP/1.1"; const EncryptionAlgorithmAES25 = "AES256"; const DevelopmentConnectionString = `DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;`; const StorageBlobLoggingAllowedHeaderNames = [ "Access-Control-Allow-Origin", "Cache-Control", "Content-Length", "Content-Type", "Date", "Request-Id", "traceparent", "Transfer-Encoding", "User-Agent", "x-ms-client-request-id", "x-ms-date", "x-ms-error-code", "x-ms-request-id", "x-ms-return-client-request-id", "x-ms-version", "Accept-Ranges", "Content-Disposition", "Content-Encoding", "Content-Language", "Content-MD5", "Content-Range", "ETag", "Last-Modified", "Server", "Vary", "x-ms-content-crc64", "x-ms-copy-action", "x-ms-copy-completion-time", "x-ms-copy-id", "x-ms-copy-progress", "x-ms-copy-status", "x-ms-has-immutability-policy", "x-ms-has-legal-hold", "x-ms-lease-state", "x-ms-lease-status", "x-ms-range", "x-ms-request-server-encrypted", "x-ms-server-encrypted", "x-ms-snapshot", "x-ms-source-range", "If-Match", "If-Modified-Since", "If-None-Match", "If-Unmodified-Since", "x-ms-access-tier", "x-ms-access-tier-change-time", "x-ms-access-tier-inferred", "x-ms-account-kind", "x-ms-archive-status", "x-ms-blob-append-offset", "x-ms-blob-cache-control", "x-ms-blob-committed-block-count", "x-ms-blob-condition-appendpos", "x-ms-blob-condition-maxsize", "x-ms-blob-content-disposition", "x-ms-blob-content-encoding", "x-ms-blob-content-language", "x-ms-blob-content-length", "x-ms-blob-content-md5", "x-ms-blob-content-type", "x-ms-blob-public-access", "x-ms-blob-sequence-number", "x-ms-blob-type", "x-ms-copy-destination-snapshot", "x-ms-creation-time", "x-ms-default-encryption-scope", "x-ms-delete-snapshots", "x-ms-delete-type-permanent", "x-ms-deny-encryption-scope-override", "x-ms-encryption-algorithm", "x-ms-if-sequence-number-eq", "x-ms-if-sequence-number-le", "x-ms-if-sequence-number-lt", "x-ms-incremental-copy", "x-ms-lease-action", "x-ms-lease-break-period", "x-ms-lease-duration", "x-ms-lease-id", "x-ms-lease-time", "x-ms-page-write", "x-ms-proposed-lease-id", "x-ms-range-get-content-md5", "x-ms-rehydrate-priority", "x-ms-sequence-number-action", "x-ms-sku-name", "x-ms-source-content-md5", "x-ms-source-if-match", "x-ms-source-if-modified-since", "x-ms-source-if-none-match", "x-ms-source-if-unmodified-since", "x-ms-tag-count", "x-ms-encryption-key-sha256", "x-ms-if-tags", "x-ms-source-if-tags", ]; const StorageBlobLoggingAllowedQueryParameters = [ "comp", "maxresults", "rscc", "rscd", "rsce", "rscl", "rsct", "se", "si", "sip", "sp", "spr", "sr", "srt", "ss", "st", "sv", "include", "marker", "prefix", "copyid", "restype", "blockid", "blocklisttype", "delimiter", "prevsnapshot", "ske", "skoid", "sks", "skt", "sktid", "skv", "snapshot", ]; 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. /** * Reserved URL characters must be properly escaped for Storage services like Blob or File. * * ## URL encode and escape strategy for JS SDKs * * When customers pass a URL string into XxxClient classes constructor, the URL string may already be URL encoded or not. * But before sending to Azure Storage server, the URL must be encoded. However, it's hard for a SDK to guess whether the URL * string has been encoded or not. We have 2 potential strategies, and chose strategy two for the XxxClient constructors. * * ### Strategy One: Assume the customer URL string is not encoded, and always encode URL string in SDK. * * This is what legacy V2 SDK does, simple and works for most of the cases. * - When customer URL string is "http://account.blob.core.windows.net/con/b:", * SDK will encode it to "http://account.blob.core.windows.net/con/b%3A" and send to server. A blob named "b:" will be created. * - When customer URL string is "http://account.blob.core.windows.net/con/b%3A", * SDK will encode it to "http://account.blob.core.windows.net/con/b%253A" and send to server. A blob named "b%3A" will be created. * * But this strategy will make it not possible to create a blob with "?" in it's name. Because when customer URL string is * "http://account.blob.core.windows.net/con/blob?name", the "?name" will be treated as URL paramter instead of blob name. * If customer URL string is "http://account.blob.core.windows.net/con/blob%3Fname", a blob named "blob%3Fname" will be created. * V2 SDK doesn't have this issue because it doesn't allow customer pass in a full URL, it accepts a separate blob name and encodeURIComponent for it. * We cannot accept a SDK cannot create a blob name with "?". So we implement strategy two: * * ### Strategy Two: SDK doesn't assume the URL has been encoded or not. It will just escape the special characters. * * This is what V10 Blob Go SDK does. It accepts a URL type in Go, and call url.EscapedPath() to escape the special chars unescaped. * - When customer URL string is "http://account.blob.core.windows.net/con/b:", * SDK will escape ":" like "http://account.blob.core.windows.net/con/b%3A" and send to server. A blob named "b:" will be created. * - When customer URL string is "http://account.blob.core.windows.net/con/b%3A", * There is no special characters, so send "http://account.blob.core.windows.net/con/b%3A" to server. A blob named "b:" will be created. * - When customer URL string is "http://account.blob.core.windows.net/con/b%253A", * There is no special characters, so send "http://account.blob.core.windows.net/con/b%253A" to server. A blob named "b%3A" will be created. * * This strategy gives us flexibility to create with any special characters. But "%" will be treated as a special characters, if the URL string * is not encoded, there shouldn't a "%" in the URL string, otherwise the URL is not a valid URL. * If customer needs to create a blob with "%" in it's blob name, use "%25" instead of "%". Just like above 3rd sample. * And following URL strings are invalid: * - "http://account.blob.core.windows.net/con/b%" * - "http://account.blob.core.windows.net/con/b%2" * - "http://account.blob.core.windows.net/con/b%G" * * Another special character is "?", use "%2F" to represent a blob name with "?" in a URL string. * * ### Strategy for containerName, blobName or other specific XXXName parameters in methods such as `containerClient.getBlobClient(blobName)` * * We will apply strategy one, and call encodeURIComponent for these parameters like blobName. Because what customers passes in is a plain name instead of a URL. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata * @see https://docs.microsoft.com/en-us/rest/api/storageservices/naming-and-referencing-shares--directories--files--and-metadata * * @param url - */ function escapeURLPath(url) { const urlParsed = coreHttp.URLBuilder.parse(url); let path = urlParsed.getPath(); path = path || "/"; path = escape(path); urlParsed.setPath(path); return urlParsed.toString(); } function getProxyUriFromDevConnString(connectionString) { // Development Connection String // https://docs.microsoft.com/en-us/azure/storage/common/storage-configure-connection-string#connect-to-the-emulator-account-using-the-well-known-account-name-and-key let proxyUri = ""; if (connectionString.search("DevelopmentStorageProxyUri=") !== -1) { // CONNECTION_STRING=UseDevelopmentStorage=true;DevelopmentStorageProxyUri=http://myProxyUri const matchCredentials = connectionString.split(";"); for (const element of matchCredentials) { if (element.trim().startsWith("DevelopmentStorageProxyUri=")) { proxyUri = element.trim().match("DevelopmentStorageProxyUri=(.*)")[1]; } } } return proxyUri; } function getValueInConnString(connectionString, argument) { const elements = connectionString.split(";"); for (const element of elements) { if (element.trim().startsWith(argument)) { return element.trim().match(argument + "=(.*)")[1]; } } return ""; } /** * Extracts the parts of an Azure Storage account connection string. * * @param connectionString - Connection string. * @returns String key value pairs of the storage account's url and credentials. */ function extractConnectionStringParts(connectionString) { let proxyUri = ""; if (connectionString.startsWith("UseDevelopmentStorage=true")) { // Development connection string proxyUri = getProxyUriFromDevConnString(connectionString); connectionString = DevelopmentConnectionString; } // Matching BlobEndpoint in the Account connection string let blobEndpoint = getValueInConnString(connectionString, "BlobEndpoint"); // Slicing off '/' at the end if exists // (The methods that use `extractConnectionStringParts` expect the url to not have `/` at the end) blobEndpoint = blobEndpoint.endsWith("/") ? blobEndpoint.slice(0, -1) : blobEndpoint; if (connectionString.search("DefaultEndpointsProtocol=") !== -1 && connectionString.search("AccountKey=") !== -1) { // Account connection string let defaultEndpointsProtocol = ""; let accountName = ""; let accountKey = Buffer.from("accountKey", "base64"); let endpointSuffix = ""; // Get account name and key accountName = getValueInConnString(connectionString, "AccountName"); accountKey = Buffer.from(getValueInConnString(connectionString, "AccountKey"), "base64"); if (!blobEndpoint) { // BlobEndpoint is not present in the Account connection string // Can be obtained from `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}` defaultEndpointsProtocol = getValueInConnString(connectionString, "DefaultEndpointsProtocol"); const protocol = defaultEndpointsProtocol.toLowerCase(); if (protocol !== "https" && protocol !== "http") { throw new Error("Invalid DefaultEndpointsProtocol in the provided Connection String. Expecting 'https' or 'http'"); } endpointSuffix = getValueInConnString(connectionString, "EndpointSuffix"); if (!endpointSuffix) { throw new Error("Invalid EndpointSuffix in the provided Connection String"); } blobEndpoint = `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`; } if (!accountName) { throw new Error("Invalid AccountName in the provided Connection String"); } else if (accountKey.length === 0) { throw new Error("Invalid AccountKey in the provided Connection String"); } return { kind: "AccountConnString", url: blobEndpoint, accountName, accountKey, proxyUri, }; } else { // SAS connection string const accountSas = getValueInConnString(connectionString, "SharedAccessSignature"); const accountName = getAccountNameFromUrl(blobEndpoint); if (!blobEndpoint) { throw new Error("Invalid BlobEndpoint in the provided SAS Connection String"); } else if (!accountSas) { throw new Error("Invalid SharedAccessSignature in the provided SAS Connection String"); } return { kind: "SASConnString", url: blobEndpoint, accountName, accountSas }; } } /** * Internal escape method implemented Strategy Two mentioned in escapeURL() description. * * @param text - */ function escape(text) { return encodeURIComponent(text) .replace(/%2F/g, "/") // Don't escape for "/" .replace(/'/g, "%27") // Escape for "'" .replace(/\+/g, "%20") .replace(/%25/g, "%"); // Revert encoded "%" } /** * Append a string to URL path. Will remove duplicated "/" in front of the string * when URL path ends with a "/". * * @param url - Source URL string * @param name - String to be appended to URL * @returns An updated URL string */ function appendToURLPath(url, name) { const urlParsed = coreHttp.URLBuilder.parse(url); let path = urlParsed.getPath(); path = path ? (path.endsWith("/") ? `${path}${name}` : `${path}/${name}`) : name; urlParsed.setPath(path); const normalizedUrl = new URL(urlParsed.toString()); return normalizedUrl.toString(); } /** * Set URL parameter name and value. If name exists in URL parameters, old value * will be replaced by name key. If not provide value, the parameter will be deleted. * * @param url - Source URL string * @param name - Parameter name * @param value - Parameter value * @returns An updated URL string */ function setURLParameter(url, name, value) { const urlParsed = coreHttp.URLBuilder.parse(url); urlParsed.setQueryParameter(name, value); return urlParsed.toString(); } /** * Get URL parameter by name. * * @param url - * @param name - */ function getURLParameter(url, name) { const urlParsed = coreHttp.URLBuilder.parse(url); return urlParsed.getQueryParameterValue(name); } /** * Set URL host. * * @param url - Source URL string * @param host - New host string * @returns An updated URL string */ function setURLHost(url, host) { const urlParsed = coreHttp.URLBuilder.parse(url); urlParsed.setHost(host); return urlParsed.toString(); } /** * Get URL path from an URL string. * * @param url - Source URL string */ function getURLPath(url) { const urlParsed = coreHttp.URLBuilder.parse(url); return urlParsed.getPath(); } /** * Get URL scheme from an URL string. * * @param url - Source URL string */ function getURLScheme(url) { const urlParsed = coreHttp.URLBuilder.parse(url); return urlParsed.getScheme(); } /** * Get URL path and query from an URL string. * * @param url - Source URL string */ function getURLPathAndQuery(url) { const urlParsed = coreHttp.URLBuilder.parse(url); const pathString = urlParsed.getPath(); if (!pathString) { throw new RangeError("Invalid url without valid path."); } let queryString = urlParsed.getQuery() || ""; queryString = queryString.trim(); if (queryString !== "") { queryString = queryString.startsWith("?") ? queryString : `?${queryString}`; // Ensure query string start with '?' } return `${pathString}${queryString}`; } /** * Get URL query key value pairs from an URL string. * * @param url - */ function getURLQueries(url) { let queryString = coreHttp.URLBuilder.parse(url).getQuery(); if (!queryString) { return {}; } queryString = queryString.trim(); queryString = queryString.startsWith("?") ? queryString.substr(1) : queryString; let querySubStrings = queryString.split("&"); querySubStrings = querySubStrings.filter((value) => { const indexOfEqual = value.indexOf("="); const lastIndexOfEqual = value.lastIndexOf("="); return (indexOfEqual > 0 && indexOfEqual === lastIndexOfEqual && lastIndexOfEqual < value.length - 1); }); const queries = {}; for (const querySubString of querySubStrings) { const splitResults = querySubString.split("="); const key = splitResults[0]; const value = splitResults[1]; queries[key] = value; } return queries; } /** * Append a string to URL query. * * @param url - Source URL string. * @param queryParts - String to be appended to the URL query. * @returns An updated URL string. */ function appendToURLQuery(url, queryParts) { const urlParsed = coreHttp.URLBuilder.parse(url); let query = urlParsed.getQuery(); if (query) { query += "&" + queryParts; } else { query = queryParts; } urlParsed.setQuery(query); return urlParsed.toString(); } /** * Rounds a date off to seconds. * * @param date - * @param withMilliseconds - If true, YYYY-MM-DDThh:mm:ss.fffffffZ will be returned; * If false, YYYY-MM-DDThh:mm:ssZ will be returned. * @returns Date string in ISO8061 format, with or without 7 milliseconds component */ function truncatedISO8061Date(date, withMilliseconds = true) { // Date.toISOString() will return like "2018-10-29T06:34:36.139Z" const dateString = date.toISOString(); return withMilliseconds ? dateString.substring(0, dateString.length - 1) + "0000" + "Z" : dateString.substring(0, dateString.length - 5) + "Z"; } /** * Base64 encode. * * @param content - */ function base64encode(content) { return !coreHttp.isNode ? btoa(content) : Buffer.from(content).toString("base64"); } /** * Generate a 64 bytes base64 block ID string. * * @param blockIndex - */ function generateBlockID(blockIDPrefix, blockIndex) { // To generate a 64 bytes base64 string, source string should be 48 const maxSourceStringLength = 48; // A blob can have a maximum of 100,000 uncommitted blocks at any given time const maxBlockIndexLength = 6; const maxAllowedBlockIDPrefixLength = maxSourceStringLength - maxBlockIndexLength; if (blockIDPrefix.length > maxAllowedBlockIDPrefixLength) { blockIDPrefix = blockIDPrefix.slice(0, maxAllowedBlockIDPrefixLength); } const res = blockIDPrefix + padStart(blockIndex.toString(), maxSourceStringLength - blockIDPrefix.length, "0"); return base64encode(res); } /** * Delay specified time interval. * * @param timeInMs - * @param aborter - * @param abortError - */ async function delay(timeInMs, aborter, abortError) { return new Promise((resolve, reject) => { /* eslint-disable-next-line prefer-const */ let timeout; const abortHandler = () => { if (timeout !== undefined) { clearTimeout(timeout); } reject(abortError); }; const resolveHandler = () => { if (aborter !== undefined) { aborter.removeEventListener("abort", abortHandler); } resolve(); }; timeout = setTimeout(resolveHandler, timeInMs); if (aborter !== undefined) { aborter.addEventListener("abort", abortHandler); } }); } /** * String.prototype.padStart() * * @param currentString - * @param targetLength - * @param padString - */ function padStart(currentString, targetLength, padString = " ") { // @ts-expect-error: TS doesn't know this code needs to run downlevel sometimes if (String.prototype.padStart) { return currentString.padStart(targetLength, padString); } padString = padString || " "; if (currentString.length > targetLength) { return currentString; } else { targetLength = targetLength - currentString.length; if (targetLength > padString.length) { padString += padString.repeat(targetLength / padString.length); } return padString.slice(0, targetLength) + currentString; } } /** * If two strings are equal when compared case insensitive. * * @param str1 - * @param str2 - */ function iEqual(str1, str2) { return str1.toLocaleLowerCase() === str2.toLocaleLowerCase(); } /** * Extracts account name from the url * @param url - url to extract the account name from * @returns with the account name */ function getAccountNameFromUrl(url) { const parsedUrl = coreHttp.URLBuilder.parse(url); let accountName; try { if (parsedUrl.getHost().split(".")[1] === "blob") { // `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`; accountName = parsedUrl.getHost().split(".")[0]; } else if (isIpEndpointStyle(parsedUrl)) { // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/ // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/ // .getPath() -> /devstoreaccount1/ accountName = parsedUrl.getPath().split("/")[1]; } else { // Custom domain case: "https://customdomain.com/containername/blob". accountName = ""; } return accountName; } catch (error) { throw new Error("Unable to extract accountName with provided information."); } } function isIpEndpointStyle(parsedUrl) { if (parsedUrl.getHost() === undefined) { return false; } 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 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) || (parsedUrl.getPort() !== undefined && PathStylePorts.includes(parsedUrl.getPort()))); } /** * Convert Tags to encoded string. * * @param tags - */ function toBlobTagsString(tags) { if (tags === undefined) { return undefined; } const tagPairs = []; for (const key in tags) { if (Object.prototype.hasOwnProperty.call(tags, key)) { const value = tags[key]; tagPairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`); } } return tagPairs.join("&"); } /** * Convert Tags type to BlobTags. * * @param tags - */ function toBlobTags(tags) { if (tags === undefined) { return undefined; } const res = { blobTagSet: [], }; for (const key in tags) { if (Object.prototype.hasOwnProperty.call(tags, key)) { const value = tags[key]; res.blobTagSet.push({ key, value, }); } } return res; } /** * Covert BlobTags to Tags type. * * @param tags - */ function toTags(tags) { if (tags === undefined) { return undefined; } const res = {}; for (const blobTag of tags.blobTagSet) { res[blobTag.key] = blobTag.value; } return res; } /** * Convert BlobQueryTextConfiguration to QuerySerialization type. * * @param textConfiguration - */ function toQuerySerialization(textConfiguration) { if (textConfiguration === undefined) { return undefined; } switch (textConfiguration.kind) { case "csv": return { format: { type: "delimited", delimitedTextConfiguration: { columnSeparator: textConfiguration.columnSeparator || ",", fieldQuote: textConfiguration.fieldQuote || "", recordSeparator: textConfiguration.recordSeparator, escapeChar: textConfiguration.escapeCharacter || "", headersPresent: textConfiguration.hasHeaders || false, }, }, }; case "json": return { format: { type: "json", jsonTextConfiguration: { recordSeparator: textConfiguration.recordSeparator, }, }, }; case "arrow": return { format: { type: "arrow", arrowConfiguration: { schema: textConfiguration.schema, }, }, }; case "parquet": return { format: { type: "parquet", }, }; default: throw Error("Invalid BlobQueryTextConfiguration."); } } function parseObjectReplicationRecord(objectReplicationRecord) { if (!objectReplicationRecord) { return undefined; } if ("policy-id" in objectReplicationRecord) { // If the dictionary contains a key with policy id, we are not required to do any parsing since // the policy id should already be stored in the ObjectReplicationDestinationPolicyId. return undefined; } const orProperties = []; for (const key in objectReplicationRecord) { const ids = key.split("_"); const policyPrefix = "or-"; if (ids[0].startsWith(policyPrefix)) { ids[0] = ids[0].substring(policyPrefix.length); } const rule = { ruleId: ids[1], replicationStatus: objectReplicationRecord[key], }; const policyIndex = orProperties.findIndex((policy) => policy.policyId === ids[0]); if (policyIndex > -1) { orProperties[policyIndex].rules.push(rule); } else { orProperties.push({ policyId: ids[0], rules: [rule], }); } } return orProperties; } /** * Attach a TokenCredential to an object. * * @param thing - * @param credential - */ function attachCredential(thing, credential) { thing.credential = credential; return thing; } function httpAuthorizationToString(httpAuthorization) { return httpAuthorization ? httpAuthorization.scheme + " " + httpAuthorization.value : undefined; } function BlobNameToString(name) { if (name.encoded) { return decodeURIComponent(name.content); } else { return name.content; } } function ConvertInternalResponseOfListBlobFlat(internalResponse) { return Object.assign(Object.assign({}, internalResponse), { segment: { blobItems: internalResponse.segment.blobItems.map((blobItemInteral) => { const blobItem = Object.assign(Object.assign({}, blobItemInteral), { name: BlobNameToString(blobItemInteral.name) }); return blobItem; }), } }); } 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), }; return blobPrefix; }), blobItems: internalResponse.segment.blobItems.map((blobItemInteral) => { const blobItem = Object.assign(Object.assign({}, blobItemInteral), { name: BlobNameToString(blobItemInteral.name) }); return blobItem; }), } }); } function* ExtractPageRangeInfoItems(getPageRangesSegment) { let pageRange = []; let clearRange = []; if (getPageRangesSegment.pageRange) pageRange = getPageRangesSegment.pageRange; if (getPageRangesSegment.clearRange) clearRange = getPageRangesSegment.clearRange; let pageRangeIndex = 0; let clearRangeIndex = 0; while (pageRangeIndex < pageRange.length && clearRangeIndex < clearRange.length) { if (pageRange[pageRangeIndex].start < clearRange[clearRangeIndex].start) { yield { start: pageRange[pageRangeIndex].start, end: pageRange[pageRangeIndex].end, isClear: false, }; ++pageRangeIndex; } else { yield { start: clearRange[clearRangeIndex].start, end: clearRange[clearRangeIndex].end, isClear: true, }; ++clearRangeIndex; } } for (; pageRangeIndex < pageRange.length; ++pageRangeIndex) { yield { start: pageRange[pageRangeIndex].start, end: pageRange[pageRangeIndex].end, isClear: false, }; } for (; clearRangeIndex < clearRange.length; ++clearRangeIndex) { yield { start: clearRange[clearRangeIndex].start, end: clearRange[clearRangeIndex].end, isClear: true, }; } } /** * 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. /** * StorageBrowserPolicy will handle differences between Node.js and browser runtime, including: * * 1. Browsers cache GET/HEAD requests by adding conditional headers such as 'IF_MODIFIED_SINCE'. * StorageBrowserPolicy is a policy used to add a timestamp query to GET/HEAD request URL * thus avoid the browser cache. * * 2. Remove cookie header for security * * 3. Remove content-length header to avoid browsers warning */ class StorageBrowserPolicy extends coreHttp.BaseRequestPolicy { /** * Creates an instance of StorageBrowserPolicy. * @param nextPolicy - * @param options - */ // The base class has a protected constructor. Adding a public one to enable constructing of this class. /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/ constructor(nextPolicy, options) { super(nextPolicy, options); } /** * Sends out request. * * @param request - */ async sendRequest(request) { if (coreHttp.isNode) { return this._nextPolicy.sendRequest(request); } if (request.method.toUpperCase() === "GET" || request.method.toUpperCase() === "HEAD") { request.url = setURLParameter(request.url, URLConstants.Parameters.FORCE_BROWSER_NO_CACHE, new Date().getTime().toString()); } request.headers.remove(HeaderConstants.COOKIE); // According to XHR standards, content-length should be fully controlled by browsers request.headers.remove(HeaderConstants.CONTENT_LENGTH); return this._nextPolicy.sendRequest(request); } } // Copyright (c) Microsoft Corporation. /** * StorageBrowserPolicyFactory is a factory class helping generating StorageBrowserPolicy objects. */ class StorageBrowserPolicyFactory { /** * Creates a StorageBrowserPolicyFactory object. * * @param nextPolicy - * @param options - */ create(nextPolicy, options) { return new StorageBrowserPolicy(nextPolicy, options); } } // Copyright (c) Microsoft Corporation. /** * RetryPolicy types. */ exports.StorageRetryPolicyType = void 0; (function (StorageRetryPolicyType) { /** * Exponential retry. Retry time delay grows exponentially. */ StorageRetryPolicyType[StorageRetryPolicyType["EXPONENTIAL"] = 0] = "EXPONENTIAL"; /** * Linear retry. Retry time delay grows linearly. */ StorageRetryPolicyType[StorageRetryPolicyType["FIXED"] = 1] = "FIXED"; })(exports.StorageRetryPolicyType || (exports.StorageRetryPolicyType = {})); // Default values of StorageRetryOptions const DEFAULT_RETRY_OPTIONS = { maxRetryDelayInMs: 120 * 1000, maxTries: 4, retryDelayInMs: 4 * 1000, retryPolicyType: exports.StorageRetryPolicyType.EXPONENTIAL, secondaryHost: "", tryTimeoutInMs: undefined, // Use server side default timeout strategy }; const RETRY_ABORT_ERROR = new abortController.AbortError("The operation was aborted."); /** * Retry policy with exponential retry and linear retry implemented. */ class StorageRetryPolicy extends coreHttp.BaseRequestPolicy { /** * Creates an instance of RetryPolicy. * * @param nextPolicy - * @param options - * @param retryOptions - */ constructor(nextPolicy, options, retryOptions = DEFAULT_RETRY_OPTIONS) { super(nextPolicy, options); // Initialize retry options this.retryOptions = { retryPolicyType: retryOptions.retryPolicyType ? retryOptions.retryPolicyType : DEFAULT_RETRY_OPTIONS.retryPolicyType, maxTries: retryOptions.maxTries && retryOptions.maxTries >= 1 ? Math.floor(retryOptions.maxTries) : DEFAULT_RETRY_OPTIONS.maxTries, tryTimeoutInMs: retryOptions.tryTimeoutInMs && retryOptions.tryTimeoutInMs >= 0 ? retryOptions.tryTimeoutInMs : DEFAULT_RETRY_OPTIONS.tryTimeoutInMs, retryDelayInMs: retryOptions.retryDelayInMs && retryOptions.retryDelayInMs >= 0 ? Math.min(retryOptions.retryDelayInMs, retryOptions.maxRetryDelayInMs ? retryOptions.maxRetryDelayInMs : DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs) : DEFAULT_RETRY_OPTIONS.retryDelayInMs, maxRetryDelayInMs: retryOptions.maxRetryDelayInMs && retryOptions.maxRetryDelayInMs >= 0 ? retryOptions.maxRetryDelayInMs : DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs, secondaryHost: retryOptions.secondaryHost ? retryOptions.secondaryHost : DEFAULT_RETRY_OPTIONS.secondaryHost, }; } /** * Sends request. * * @param request - */ async sendRequest(request) { return this.attemptSendRequest(request, false, 1); } /** * Decide and perform next retry. Won't mutate request parameter. * * @param request - * @param secondaryHas404 - If attempt was against the secondary & it returned a StatusNotFound (404), then * the resource was not found. This may be due to replication delay. So, in this * case, we'll never try the secondary again for this operation. * @param attempt - How many retries has been attempted to performed, starting from 1, which includes * the attempt will be performed by this method call. */ async attemptSendRequest(request, secondaryHas404, attempt) { const newRequest = request.clone(); const isPrimaryRetry = secondaryHas404 || !this.retryOptions.secondaryHost || !(request.method === "GET" || request.method === "HEAD" || request.method === "OPTIONS") || attempt % 2 === 1; if (!isPrimaryRetry) { newRequest.url = setURLHost(newRequest.url, this.retryOptions.secondaryHost); } // Set the server-side timeout query parameter "timeout=[seconds]" if (this.retryOptions.tryTimeoutInMs) { newRequest.url = setURLParameter(newRequest.url, URLConstants.Parameters.TIMEOUT, Math.floor(this.retryOptions.tryTimeoutInMs / 1000).toString()); } let response; try { logger.info(`RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}`); response = await this._nextPolicy.sendRequest(newRequest); if (!this.shouldRetry(isPrimaryRetry, attempt, response)) { return response; } secondaryHas404 = secondaryHas404 || (!isPrimaryRetry && response.status === 404); } catch (err) { logger.error(`RetryPolicy: Caught error, message: ${err.message}, code: ${err.code}`); if (!this.shouldRetry(isPrimaryRetry, attempt, response, err)) { throw err; } } await this.delay(isPrimaryRetry, attempt, request.abortSignal); return this.attemptSendRequest(request, secondaryHas404, ++attempt); } /** * Decide whether to retry according to last HTTP response and retry counters. * * @param isPrimaryRetry - * @param attempt - * @param response - * @param err - */ shouldRetry(isPrimaryRetry, attempt, response, err) { if (attempt >= this.retryOptions.maxTries) { logger.info(`RetryPolicy: Attempt(s) ${attempt} >= maxTries ${this.retryOptions .maxTries}, no further try.`); return false; } // Handle network failures, you may need to customize the list when you implement // your own http client const retriableErrors = [ "ETIMEDOUT", "ESOCKETTIMEDOUT", "ECONNREFUSED", "ECONNRESET", "ENOENT", "ENOTFOUND", "TIMEOUT", "EPIPE", "REQUEST_SEND_ERROR", // For default xhr based http client provided in ms-rest-js ]; if (err) { for (const retriableError of retriableErrors) { if (err.name.toUpperCase().includes(retriableError) || err.message.toUpperCase().includes(retriableError) || (err.code && err.code.toString().toUpperCase() === retriableError)) { logger.info(`RetryPolicy: Network error ${retriableError} found, will retry.`); return true; } } } // If attempt was against the secondary & it returned a StatusNotFound (404), then // the resource was not found. This may be due to replication delay. So, in this // case, we'll never try the secondary again for this operation. if (response || err) { const statusCode = response ? response.status : err ? err.statusCode : 0; if (!isPrimaryRetry && statusCode === 404) { logger.info(`RetryPolicy: Secondary access with 404, will retry.`); return true; } // Server internal error or server timeout if (statusCode === 503 || statusCode === 500) { logger.info(`RetryPolicy: Will retry for status code ${statusCode}.`); return true; } } if ((err === null || err === void 0 ? void 0 : err.code) === "PARSE_ERROR" && (err === null || err === void 0 ? void 0 : err.message.startsWith(`Error "Error: Unclosed root tag`))) { logger.info("RetryPolicy: Incomplete XML response likely due to service timeout, will retry."); return true; } return false; } /** * Delay a calculated time between retries. * * @param isPrimaryRetry - * @param attempt - * @param abortSignal - */ async delay(isPrimaryRetry, attempt, abortSignal) { let delayTimeInMs = 0; if (isPrimaryRetry) { switch (this.retryOptions.retryPolicyType) { case exports.StorageRetryPolicyType.EXPONENTIAL: delayTimeInMs = Math.min((Math.pow(2, attempt - 1) - 1) * this.retryOptions.retryDelayInMs, this.retryOptions.maxRetryDelayInMs); break; case exports.StorageRetryPolicyType.FIXED: delayTimeInMs = this.retryOptions.retryDelayInMs; break; } } else { delayTimeInMs = Math.random() * 1000; } logger.info(`RetryPolicy: Delay for ${delayTimeInMs}ms`); return delay(delayTimeInMs, abortSignal, RETRY_ABORT_ERROR); } } // Copyright (c) Microsoft Corporation. /** * StorageRetryPolicyFactory is a factory class helping generating {@link StorageRetryPolicy} objects. */ class StorageRetryPolicyFactory { /** * Creates an instance of StorageRetryPolicyFactory. * @param retryOptions - */ constructor(retryOptions) { this.retryOptions = retryOptions; } /** * Creates a StorageRetryPolicy object. * * @param nextPolicy - * @param options - */ create(nextPolicy, options) { return new StorageRetryPolicy(nextPolicy, options, this.retryOptions); } } // Copyright (c) Microsoft Corporation. /** * Credential policy used to sign HTTP(S) requests before sending. This is an * abstract class. */ class CredentialPolicy extends coreHttp.BaseRequestPolicy { /** * Sends out request. * * @param request - */ sendRequest(request) { return this._nextPolicy.sendRequest(this.signRequest(request)); } /** * Child classes must implement this method with request signing. This method * will be executed in {@link sendRequest}. * * @param request - */ signRequest(request) { // Child classes must override this method with request signing. This method // will be executed in sendRequest(). return request; } } // Copyright (c) Microsoft Corporation. /** * AnonymousCredentialPolicy is used with HTTP(S) requests that read public resources * or for use with Shared Access Signatures (SAS). */ class AnonymousCredentialPolicy extends CredentialPolicy { /** * Creates an instance of AnonymousCredentialPolicy. * @param nextPolicy - * @param options - */ // The base class has a protected constructor. Adding a public one to enable constructing of this class. /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/ constructor(nextPolicy, options) { super(nextPolicy, options); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * Credential is an abstract class for Azure Storage HTTP requests signing. This * class will host an credentialPolicyCreator factory which generates CredentialPolicy. */ class Credential { /** * Creates a RequestPolicy object. * * @param _nextPolicy - * @param _options - */ create(_nextPolicy, _options) { throw new Error("Method should be implemented in children classes."); } } // Copyright (c) Microsoft Corporation. /** * AnonymousCredential provides a credentialPolicyCreator member used to create * AnonymousCredentialPolicy objects. AnonymousCredentialPolicy is used with * HTTP(S) requests that read public resources or for use with Shared Access * Signatures (SAS). */ class AnonymousCredential extends Credential { /** * Creates an {@link AnonymousCredentialPolicy} object. * * @param nextPolicy - * @param options - */ create(nextPolicy, options) { return new AnonymousCredentialPolicy(nextPolicy, options); } } // Copyright (c) Microsoft Corporation. /** * TelemetryPolicy is a policy used to tag user-agent header for every requests. */ class TelemetryPolicy extends coreHttp.BaseRequestPolicy { /** * Creates an instance of TelemetryPolicy. * @param nextPolicy - * @param options - * @param telemetry - */ constructor(nextPolicy, options, telemetry) { super(nextPolicy, options); this.telemetry = telemetry; } /** * Sends out request. * * @param request - */ async sendRequest(request) { if (coreHttp.isNode) { if (!request.headers) { request.headers = new coreHttp.HttpHeaders(); } if (!request.headers.get(HeaderConstants.USER_AGENT)) { request.headers.set(HeaderConstants.USER_AGENT, this.telemetry); } } return this._nextPolicy.sendRequest(request); } } // Copyright (c) Microsoft Corporation. /** * TelemetryPolicyFactory is a factory class helping generating {@link TelemetryPolicy} objects. */ class TelemetryPolicyFactory { /** * Creates an instance of TelemetryPolicyFactory. * @param telemetry - */ constructor(telemetry) { const userAgentInfo = []; if (coreHttp.isNode) { if (telemetry) { const telemetryString = telemetry.userAgentPrefix || ""; if (telemetryString.length > 0 && userAgentInfo.indexOf(telemetryString) === -1) { userAgentInfo.push(telemetryString); } } // e.g. azsdk-js-storageblob/10.0.0 const libInfo = `azsdk-js-storageblob/${SDK_VERSION}`; if (userAgentInfo.indexOf(libInfo) === -1) { userAgentInfo.push(libInfo); } // e.g. (NODE-VERSION 4.9.1; Windows_NT 10.0.16299) let runtimeInfo = `(NODE-VERSION ${process.version})`; if (os__namespace) { runtimeInfo = `(NODE-VERSION ${process.version}; ${os__namespace.type()} ${os__namespace.release()})`; } if (userAgentInfo.indexOf(runtimeInfo) === -1) { userAgentInfo.push(runtimeInfo); } } this.telemetryString = userAgentInfo.join(" "); } /** * Creates a TelemetryPolicy object. * * @param nextPolicy - * @param options - */ create(nextPolicy, options) { return new TelemetryPolicy(nextPolicy, options, this.telemetryString); } } // Copyright (c) Microsoft Corporation. const _defaultHttpClient = new coreHttp.DefaultHttpClient(); function getCachedDefaultHttpClient() { return _defaultHttpClient; } // Copyright (c) Microsoft Corporation. /** * A set of constants used internally when processing requests. */ const Constants = { DefaultScope: "/.default", /** * Defines constants for use with HTTP headers. */ HeaderConstants: { /** * The Authorization header. */ AUTHORIZATION: "authorization", }, }; // Default options for the cycler if none are provided const DEFAULT_CYCLER_OPTIONS = { forcedRefreshWindowInMs: 1000, retryIntervalInMs: 3000, refreshWindowInMs: 1000 * 60 * 2, // Start refreshing 2m before expiry }; /** * Converts an an unreliable access token getter (which may resolve with null) * into an AccessTokenGetter by retrying the unreliable getter in a regular * interval. * * @param getAccessToken - a function that produces a promise of an access * token that may fail by returning null * @param retryIntervalInMs - the time (in milliseconds) to wait between retry * attempts * @param timeoutInMs - the timestamp after which the refresh attempt will fail, * throwing an exception * @returns - a promise that, if it resolves, will resolve with an access token */ async function beginRefresh(getAccessToken, retryIntervalInMs, timeoutInMs) { // This wrapper handles exceptions gracefully as long as we haven't exceeded // the timeout. async function tryGetAccessToken() { if (Date.now() < timeoutInMs) { try { return await getAccessToken(); } catch (_a) { return null; } } else { const finalToken = await getAccessToken(); // Timeout is up, so throw if it's still null if (finalToken === null) { throw new Error("Failed to refresh access token."); } return finalToken; } } let token = await tryGetAccessToken(); while (token === null) { await coreHttp.delay(retryIntervalInMs); token = await tryGetAccessToken(); } return token; } /** * Creates a token cycler from a credential, scopes, and optional settings. * * A token cycler represents a way to reliably retrieve a valid access token * from a TokenCredential. It will handle initializing the token, refreshing it * when it nears expiration, and synchronizes refresh attempts to avoid * concurrency hazards. * * @param credential - the underlying TokenCredential that provides the access * token * @param scopes - the scopes to request authorization for * @param tokenCyclerOptions - optionally override default settings for the cycler * * @returns - a function that reliably produces a valid access token */ function createTokenCycler(credential, scopes, tokenCyclerOptions) { let refreshWorker = null; let token = null; const options = Object.assign(Object.assign({}, DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions); /** * This little holder defines several predicates that we use to construct * the rules of refreshing the token. */ const cycler = { /** * Produces true if a refresh job is currently in progress. */ get isRefreshing() { return refreshWorker !== null; }, /** * Produces true if the cycler SHOULD refresh (we are within the refresh * window and not already refreshing) */ get shouldRefresh() { var _a; return (!cycler.isRefreshing && ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now()); }, /** * Produces true if the cycler MUST refresh (null or nearly-expired * token). */ get mustRefresh() { return (token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now()); }, }; /** * Starts a refresh job or returns the existing job if one is already * running. */ function refresh(getTokenOptions) { var _a; if (!cycler.isRefreshing) { // We bind `scopes` here to avoid passing it around a lot const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions); // Take advantage of promise chaining to insert an assignment to `token` // before the refresh can be considered done. refreshWorker = beginRefresh(tryGetAccessToken, options.retryIntervalInMs, // If we don't have a token, then we should timeout immediately (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now()) .then((_token) => { refreshWorker = null; token = _token; return token; }) .catch((reason) => { // We also should reset the refresher if we enter a failed state. All // existing awaiters will throw, but subsequent requests will start a // new retry chain. refreshWorker = null; token = null; throw reason; }); } return refreshWorker; } return async (tokenOptions) => { // // Simple rules: // - If we MUST refresh, then return the refresh task, blocking // the pipeline until a token is available. // - If we SHOULD refresh, then run refresh but don't return it // (we can still use the cached token). // - Return the token, since it's fine if we didn't return in // step 1. // if (cycler.mustRefresh) return refresh(tokenOptions); if (cycler.shouldRefresh) { refresh(tokenOptions); } return token; }; } /** * We will retrieve the challenge only if the response status code was 401, * and if the response contained the header "WWW-Authenticate" with a non-empty value. */ function getChallenge(response) { const challenge = response.headers.get("WWW-Authenticate"); if (response.status === 401 && challenge) { return challenge; } return; } /** * Converts: `Bearer a="b" c="d"`. * Into: `[ { a: 'b', c: 'd' }]`. * * @internal */ function parseChallenge(challenge) { const bearerChallenge = challenge.slice("Bearer ".length); const challengeParts = `${bearerChallenge.trim()} `.split(" ").filter((x) => x); const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split("="))); // Key-value pairs to plain object: return keyValuePairs.reduce((a, b) => (Object.assign(Object.assign({}, a), b)), {}); } // #endregion /** * Creates a new factory for a RequestPolicy that applies a bearer token to * the requests' `Authorization` headers. * * @param credential - The TokenCredential implementation that can supply the bearer token. * @param scopes - The scopes for which the bearer token applies. */ function storageBearerTokenChallengeAuthenticationPolicy(credential, scopes) { // This simple function encapsulates the entire process of reliably retrieving the token let getToken = createTokenCycler(credential, scopes); class StorageBearerTokenChallengeAuthenticationPolicy extends coreHttp.BaseRequestPolicy { constructor(nextPolicy, options) { super(nextPolicy, options); } async sendRequest(webResource) { if (!webResource.url.toLowerCase().startsWith("https://")) { throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs."); } const getTokenInternal = getToken; const token = (await getTokenInternal({ abortSignal: webResource.abortSignal, tracingOptions: { tracingContext: webResource.tracingContext, }, })).token; webResource.headers.set(Constants.HeaderConstants.AUTHORIZATION, `Bearer ${token}`); const response = await this._nextPolicy.sendRequest(webResource); if ((response === null || response === void 0 ? void 0 : response.status) === 401) { const challenge = getChallenge(response); if (challenge) { const challengeInfo = parseChallenge(challenge); const challengeScopes = challengeInfo.resource_id + Constants.DefaultScope; const parsedAuthUri = coreHttp.URLBuilder.parse(challengeInfo.authorization_uri); const pathSegments = parsedAuthUri.getPath().split("/"); const tenantId = pathSegments[1]; const getTokenForChallenge = createTokenCycler(credential, challengeScopes); const tokenForChallenge = (await getTokenForChallenge({ abortSignal: webResource.abortSignal, tracingOptions: { tracingContext: webResource.tracingContext, }, tenantId: tenantId, })).token; getToken = getTokenForChallenge; webResource.headers.set(Constants.HeaderConstants.AUTHORIZATION, `Bearer ${tokenForChallenge}`); return this._nextPolicy.sendRequest(webResource); } } return response; } } return { create: (nextPolicy, options) => { return new StorageBearerTokenChallengeAuthenticationPolicy(nextPolicy, options); }, }; } // Copyright (c) Microsoft Corporation. /** * A helper to decide if a given argument satisfies the Pipeline contract * @param pipeline - An argument that may be a Pipeline * @returns true when the argument satisfies the Pipeline contract */ function isPipelineLike(pipeline) { if (!pipeline || typeof pipeline !== "object") { return false; } const castPipeline = pipeline; return (Array.isArray(castPipeline.factories) && typeof castPipeline.options === "object" && typeof castPipeline.toServiceClientOptions === "function"); } /** * A Pipeline class containing HTTP request policies. * You can create a default Pipeline by calling {@link newPipeline}. * Or you can create a Pipeline with your own policies by the constructor of Pipeline. * * Refer to {@link newPipeline} and provided policies before implementing your * customized Pipeline. */ class Pipeline { /** * Creates an instance of Pipeline. Customize HTTPClient by implementing IHttpClient interface. * * @param factories - * @param options - */ constructor(factories, options = {}) { this.factories = factories; // when options.httpClient is not specified, passing in a DefaultHttpClient instance to // avoid each client creating its own http client. this.options = Object.assign(Object.assign({}, options), { httpClient: options.httpClient || getCachedDefaultHttpClient() }); } /** * Transfer Pipeline object to ServiceClientOptions object which is required by * ServiceClient constructor. * * @returns The ServiceClientOptions object from this Pipeline. */ toServiceClientOptions() { return { httpClient: this.options.httpClient, requestPolicyFactories: this.factories, }; } } /** * Creates a new Pipeline object with Credential provided. * * @param credential - Such as AnonymousCredential, StorageSharedKeyCredential or any credential from the `@azure/identity` package to authenticate requests to the service. You can also provide an object that implements the TokenCredential interface. If not specified, AnonymousCredential is used. * @param pipelineOptions - Optional. Options. * @returns A new Pipeline object. */ function newPipeline(credential, pipelineOptions = {}) { var _a; if (credential === undefined) { credential = new AnonymousCredential(); } // Order is important. Closer to the API at the top & closer to the network at the bottom. // The credential's policy factory must appear close to the wire so it can sign any // changes made by other factories (like UniqueRequestIDPolicyFactory) const telemetryPolicy = new TelemetryPolicyFactory(pipelineOptions.userAgentOptions); const factories = [ coreHttp.tracingPolicy({ userAgent: telemetryPolicy.telemetryString }), coreHttp.keepAlivePolicy(pipelineOptions.keepAliveOptions), telemetryPolicy, coreHttp.generateClientRequestIdPolicy(), new StorageBrowserPolicyFactory(), new StorageRetryPolicyFactory(pipelineOptions.retryOptions), // Default deserializationPolicy is provided by protocol layer // Use customized XML char key of "#" so we could deserialize metadata // with "_" key coreHttp.deserializationPolicy(undefined, { xmlCharKey: "#" }), coreHttp.logPolicy({ logger: logger.info, allowedHeaderNames: StorageBlobLoggingAllowedHeaderNames, allowedQueryParameters: StorageBlobLoggingAllowedQueryParameters, }), ]; if (coreHttp.isNode) { // policies only available in Node.js runtime, not in browsers factories.push(coreHttp.proxyPolicy(pipelineOptions.proxyOptions)); factories.push(coreHttp.disableResponseDecompressionPolicy()); } factories.push(coreHttp.isTokenCredential(credential) ? attachCredential(storageBearerTokenChallengeAuthenticationPolicy(credential, (_a = pipelineOptions.audience) !== null && _a !== void 0 ? _a : StorageOAuthScopes), credential) : credential); return new Pipeline(factories, pipelineOptions); } // Copyright (c) Microsoft Corporation. /** * StorageSharedKeyCredentialPolicy is a policy used to sign HTTP request with a shared key. */ class StorageSharedKeyCredentialPolicy extends CredentialPolicy { /** * Creates an instance of StorageSharedKeyCredentialPolicy. * @param nextPolicy - * @param options - * @param factory - */ constructor(nextPolicy, options, factory) { super(nextPolicy, options); this.factory = factory; } /** * Signs request. * * @param request - */ signRequest(request) { request.headers.set(HeaderConstants.X_MS_DATE, new Date().toUTCString()); if (request.body && (typeof request.body === "string" || request.body !== undefined) && request.body.length > 0) { request.headers.set(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body)); } const stringToSign = [ request.method.toUpperCase(), this.getHeaderValueToSign(request, HeaderConstants.CONTENT_LANGUAGE), this.getHeaderValueToSign(request, HeaderConstants.CONTENT_ENCODING), this.getHeaderValueToSign(request, HeaderConstants.CONTENT_LENGTH), this.getHeaderValueToSign(request, HeaderConstants.CONTENT_MD5), this.getHeaderValueToSign(request, HeaderConstants.CONTENT_TYPE), this.getHeaderValueToSign(request, HeaderConstants.DATE), this.getHeaderValueToSign(request, HeaderConstants.IF_MODIFIED_SINCE), this.getHeaderValueToSign(request, HeaderConstants.IF_MATCH), this.getHeaderValueToSign(request, HeaderConstants.IF_NONE_MATCH), this.getHeaderValueToSign(request, HeaderConstants.IF_UNMODIFIED_SINCE), this.getHeaderValueToSign(request, HeaderConstants.RANGE), ].join("\n") + "\n" + this.getCanonicalizedHeadersString(request) + this.getCanonicalizedResourceString(request); const signature = this.factory.computeHMACSHA256(stringToSign); request.headers.set(HeaderConstants.AUTHORIZATION, `SharedKey ${this.factory.accountName}:${signature}`); // console.log(`[URL]:${request.url}`); // console.log(`[HEADERS]:${request.headers.toString()}`); // console.log(`[STRING TO SIGN]:${JSON.stringify(stringToSign)}`); // console.log(`[KEY]: ${request.headers.get(HeaderConstants.AUTHORIZATION)}`); return request; } /** * Retrieve header value according to shared key sign rules. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key * * @param request - * @param headerName - */ getHeaderValueToSign(request, headerName) { const value = request.headers.get(headerName); if (!value) { return ""; } // When using version 2015-02-21 or later, if Content-Length is zero, then // set the Content-Length part of the StringToSign to an empty string. // https://docs.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key if (headerName === HeaderConstants.CONTENT_LENGTH && value === "0") { return ""; } return value; } /** * To construct the CanonicalizedHeaders portion of the signature string, follow these steps: * 1. Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header. * 2. Convert each HTTP header name to lowercase. * 3. Sort the headers lexicographically by header name, in ascending order. * Each header may appear only once in the string. * 4. Replace any linear whitespace in the header value with a single space. * 5. Trim any whitespace around the colon in the header. * 6. Finally, append a new-line character to each canonicalized header in the resulting list. * Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string. * * @param request - */ getCanonicalizedHeadersString(request) { let headersArray = request.headers.headersArray().filter((value) => { return value.name.toLowerCase().startsWith(HeaderConstants.PREFIX_FOR_STORAGE); }); headersArray.sort((a, b) => { return a.name.toLowerCase().localeCompare(b.name.toLowerCase()); }); // Remove duplicate headers headersArray = headersArray.filter((value, index, array) => { if (index > 0 && value.name.toLowerCase() === array[index - 1].name.toLowerCase()) { return false; } return true; }); let canonicalizedHeadersStringToSign = ""; headersArray.forEach((header) => { canonicalizedHeadersStringToSign += `${header.name .toLowerCase() .trimRight()}:${header.value.trimLeft()}\n`; }); return canonicalizedHeadersStringToSign; } /** * Retrieves the webResource canonicalized resource string. * * @param request - */ getCanonicalizedResourceString(request) { const path = getURLPath(request.url) || "/"; let canonicalizedResourceString = ""; canonicalizedResourceString += `/${this.factory.accountName}${path}`; const queries = getURLQueries(request.url); const lowercaseQueries = {}; if (queries) { const queryKeys = []; for (const key in queries) { if (Object.prototype.hasOwnProperty.call(queries, key)) { const lowercaseKey = key.toLowerCase(); lowercaseQueries[lowercaseKey] = queries[key]; queryKeys.push(lowercaseKey); } } queryKeys.sort(); for (const key of queryKeys) { canonicalizedResourceString += `\n${key}:${decodeURIComponent(lowercaseQueries[key])}`; } } return canonicalizedResourceString; } } // Copyright (c) Microsoft Corporation. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * StorageSharedKeyCredential for account key authorization of Azure Storage service. */ class StorageSharedKeyCredential extends Credential { /** * Creates an instance of StorageSharedKeyCredential. * @param accountName - * @param accountKey - */ constructor(accountName, accountKey) { super(); this.accountName = accountName; this.accountKey = Buffer.from(accountKey, "base64"); } /** * Creates a StorageSharedKeyCredentialPolicy object. * * @param nextPolicy - * @param options - */ create(nextPolicy, options) { return new StorageSharedKeyCredentialPolicy(nextPolicy, options, this); } /** * Generates a hash signature for an HTTP request or for a SAS. * * @param stringToSign - */ computeHMACSHA256(stringToSign) { return crypto.createHmac("sha256", this.accountKey).update(stringToSign, "utf8").digest("base64"); } } /* * 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 packageName = "azure-storage-blob"; const packageVersion = "12.13.0"; class StorageClientContext extends coreHttp__namespace.ServiceClient { /** * Initializes a new instance of the StorageClientContext class. * @param url The URL of the service account, container, or blob that is the target of the desired * operation. * @param options The parameter options */ constructor(url, options) { if (url === undefined) { throw new Error("'url' cannot be null"); } // Initializing default values for options if (!options) { options = {}; } if (!options.userAgent) { const defaultUserAgent = coreHttp__namespace.getDefaultUserAgentValue(); options.userAgent = `${packageName}/${packageVersion} ${defaultUserAgent}`; } super(undefined, options); this.requestContentType = "application/json; charset=utf-8"; this.baseUri = options.endpoint || "{url}"; // Parameter assignments this.url = url; // Assigning values to Constant parameters this.version = options.version || "2021-12-02"; } } // Copyright (c) Microsoft Corporation. /** * A StorageClient represents a based URL class for {@link BlobServiceClient}, {@link ContainerClient} * and etc. */ class StorageClient { /** * Creates an instance of StorageClient. * @param url - url to resource * @param pipeline - request policy pipeline. */ constructor(url, pipeline) { // URL should be encoded and only once, protocol layer shouldn't encode URL again this.url = escapeURLPath(url); this.accountName = getAccountNameFromUrl(url); this.pipeline = pipeline; this.storageClientContext = new StorageClientContext(this.url, pipeline.toServiceClientOptions()); this.isHttps = iEqual(getURLScheme(this.url) || "", "https"); this.credential = new AnonymousCredential(); for (const factory of this.pipeline.factories) { if ((coreHttp.isNode && factory instanceof StorageSharedKeyCredential) || factory instanceof AnonymousCredential) { this.credential = factory; } else if (coreHttp.isTokenCredential(factory.credential)) { // Only works if the factory has been attached a "credential" property. // We do that in newPipeline() when using TokenCredential. this.credential = factory.credential; } } // Override protocol layer's default content-type const storageClientContext = this.storageClientContext; storageClientContext.requestContentType = undefined; } } // Copyright (c) Microsoft Corporation. /** * Creates a span using the global tracer. * @internal */ const createSpan = coreTracing.createSpanFunction({ packagePrefix: "Azure.Storage.Blob", namespace: "Microsoft.Storage", }); /** * @internal * * Adapt the tracing options from OperationOptions to what they need to be for * RequestOptionsBase (when we update to later OpenTelemetry versions this is now * two separate fields, not just one). */ function convertTracingToRequestOptionsBase(options) { var _a, _b; return { // By passing spanOptions if they exist at runtime, we're backwards compatible with @azure/core-tracing@preview.13 and earlier. spanOptions: (_a = options === null || options === void 0 ? void 0 : options.tracingOptions) === null || _a === void 0 ? void 0 : _a.spanOptions, tracingContext: (_b = options === null || options === void 0 ? void 0 : options.tracingOptions) === null || _b === void 0 ? void 0 : _b.tracingContext, }; } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * This is a helper class to construct a string representing the permissions granted by a ServiceSAS to a blob. Setting * a value to true means that any SAS which uses these permissions will grant permissions for that operation. Once all * the values are set, this should be serialized with toString and set as the permissions field on a * {@link BlobSASSignatureValues} object. It is possible to construct the permissions string without this class, but * the order of the permissions is particular and this class guarantees correctness. */ class BlobSASPermissions { constructor() { /** * Specifies Read access granted. */ this.read = false; /** * Specifies Add access granted. */ this.add = false; /** * Specifies Create access granted. */ this.create = false; /** * Specifies Write access granted. */ this.write = false; /** * Specifies Delete access granted. */ this.delete = false; /** * Specifies Delete version access granted. */ this.deleteVersion = false; /** * Specfies Tag access granted. */ this.tag = false; /** * Specifies Move access granted. */ this.move = false; /** * Specifies Execute access granted. */ this.execute = false; /** * Specifies SetImmutabilityPolicy access granted. */ this.setImmutabilityPolicy = false; /** * Specifies that Permanent Delete is permitted. */ this.permanentDelete = false; } /** * Creates a {@link BlobSASPermissions} from the specified permissions string. This method will throw an * Error if it encounters a character that does not correspond to a valid permission. * * @param permissions - */ static parse(permissions) { const blobSASPermissions = new BlobSASPermissions(); for (const char of permissions) { switch (char) { case "r": blobSASPermissions.read = true; break; case "a": blobSASPermissions.add = true; break; case "c": blobSASPermissions.create = true; break; case "w": blobSASPermissions.write = true; break; case "d": blobSASPermissions.delete = true; break; case "x": blobSASPermissions.deleteVersion = true; break; case "t": blobSASPermissions.tag = true; break; case "m": blobSASPermissions.move = true; break; case "e": blobSASPermissions.execute = true; break; case "i": blobSASPermissions.setImmutabilityPolicy = true; break; case "y": blobSASPermissions.permanentDelete = true; break; default: throw new RangeError(`Invalid permission: ${char}`); } } return blobSASPermissions; } /** * Creates a {@link BlobSASPermissions} from a raw object which contains same keys as it * and boolean values for them. * * @param permissionLike - */ static from(permissionLike) { const blobSASPermissions = new BlobSASPermissions(); if (permissionLike.read) { blobSASPermissions.read = true; } if (permissionLike.add) { blobSASPermissions.add = true; } if (permissionLike.create) { blobSASPermissions.create = true; } if (permissionLike.write) { blobSASPermissions.write = true; } if (permissionLike.delete) { blobSASPermissions.delete = true; } if (permissionLike.deleteVersion) { blobSASPermissions.deleteVersion = true; } if (permissionLike.tag) { blobSASPermissions.tag = true; } if (permissionLike.move) { blobSASPermissions.move = true; } if (permissionLike.execute) { blobSASPermissions.execute = true; } if (permissionLike.setImmutabilityPolicy) { blobSASPermissions.setImmutabilityPolicy = true; } if (permissionLike.permanentDelete) { blobSASPermissions.permanentDelete = true; } return blobSASPermissions; } /** * Converts the given permissions to a string. Using this method will guarantee the permissions are in an * order accepted by the service. * * @returns A string which represents the BlobSASPermissions */ toString() { const permissions = []; if (this.read) { permissions.push("r"); } if (this.add) { permissions.push("a"); } if (this.create) { permissions.push("c"); } if (this.write) { permissions.push("w"); } if (this.delete) { permissions.push("d"); } if (this.deleteVersion) { permissions.push("x"); } if (this.tag) { permissions.push("t"); } if (this.move) { permissions.push("m"); } if (this.execute) { permissions.push("e"); } if (this.setImmutabilityPolicy) { permissions.push("i"); } if (this.permanentDelete) { permissions.push("y"); } return permissions.join(""); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * This is a helper class to construct a string representing the permissions granted by a ServiceSAS to a container. * Setting a value to true means that any SAS which uses these permissions will grant permissions for that operation. * Once all the values are set, this should be serialized with toString and set as the permissions field on a * {@link BlobSASSignatureValues} object. It is possible to construct the permissions string without this class, but * the order of the permissions is particular and this class guarantees correctness. */ class ContainerSASPermissions { constructor() { /** * Specifies Read access granted. */ this.read = false; /** * Specifies Add access granted. */ this.add = false; /** * Specifies Create access granted. */ this.create = false; /** * Specifies Write access granted. */ this.write = false; /** * Specifies Delete access granted. */ this.delete = false; /** * Specifies Delete version access granted. */ this.deleteVersion = false; /** * Specifies List access granted. */ this.list = false; /** * Specfies Tag access granted. */ this.tag = false; /** * Specifies Move access granted. */ this.move = false; /** * Specifies Execute access granted. */ this.execute = false; /** * Specifies SetImmutabilityPolicy access granted. */ this.setImmutabilityPolicy = false; /** * Specifies that Permanent Delete is permitted. */ this.permanentDelete = false; /** * Specifies that Filter Blobs by Tags is permitted. */ this.filterByTags = false; } /** * Creates an {@link ContainerSASPermissions} from the specified permissions string. This method will throw an * Error if it encounters a character that does not correspond to a valid permission. * * @param permissions - */ static parse(permissions) { const containerSASPermissions = new ContainerSASPermissions(); for (const char of permissions) { switch (char) { case "r": containerSASPermissions.read = true; break; case "a": containerSASPermissions.add = true; break; case "c": containerSASPermissions.create = true; break; case "w": containerSASPermissions.write = true; break; case "d": containerSASPermissions.delete = true; break; case "l": containerSASPermissions.list = true; break; case "t": containerSASPermissions.tag = true; break; case "x": containerSASPermissions.deleteVersion = true; break; case "m": containerSASPermissions.move = true; break; case "e": containerSASPermissions.execute = true; break; case "i": containerSASPermissions.setImmutabilityPolicy = true; break; case "y": containerSASPermissions.permanentDelete = true; break; case "f": containerSASPermissions.filterByTags = true; break; default: throw new RangeError(`Invalid permission ${char}`); } } return containerSASPermissions; } /** * Creates a {@link ContainerSASPermissions} from a raw object which contains same keys as it * and boolean values for them. * * @param permissionLike - */ static from(permissionLike) { const containerSASPermissions = new ContainerSASPermissions(); if (permissionLike.read) { containerSASPermissions.read = true; } if (permissionLike.add) { containerSASPermissions.add = true; } if (permissionLike.create) { containerSASPermissions.create = true; } if (permissionLike.write) { containerSASPermissions.write = true; } if (permissionLike.delete) { containerSASPermissions.delete = true; } if (permissionLike.list) { containerSASPermissions.list = true; } if (permissionLike.deleteVersion) { containerSASPermissions.deleteVersion = true; } if (permissionLike.tag) { containerSASPermissions.tag = true; } if (permissionLike.move) { containerSASPermissions.move = true; } if (permissionLike.execute) { containerSASPermissions.execute = true; } if (permissionLike.setImmutabilityPolicy) { containerSASPermissions.setImmutabilityPolicy = true; } if (permissionLike.permanentDelete) { containerSASPermissions.permanentDelete = true; } if (permissionLike.filterByTags) { containerSASPermissions.filterByTags = true; } return containerSASPermissions; } /** * Converts the given permissions to a string. Using this method will guarantee the permissions are in an * order accepted by the service. * * The order of the characters should be as specified here to ensure correctness. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas * */ toString() { const permissions = []; if (this.read) { permissions.push("r"); } if (this.add) { permissions.push("a"); } if (this.create) { permissions.push("c"); } if (this.write) { permissions.push("w"); } if (this.delete) { permissions.push("d"); } if (this.deleteVersion) { permissions.push("x"); } if (this.list) { permissions.push("l"); } if (this.tag) { permissions.push("t"); } if (this.move) { permissions.push("m"); } if (this.execute) { permissions.push("e"); } if (this.setImmutabilityPolicy) { permissions.push("i"); } if (this.permanentDelete) { permissions.push("y"); } if (this.filterByTags) { permissions.push("f"); } return permissions.join(""); } } // Copyright (c) Microsoft Corporation. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * UserDelegationKeyCredential is only used for generation of user delegation SAS. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-user-delegation-sas */ class UserDelegationKeyCredential { /** * Creates an instance of UserDelegationKeyCredential. * @param accountName - * @param userDelegationKey - */ constructor(accountName, userDelegationKey) { this.accountName = accountName; this.userDelegationKey = userDelegationKey; this.key = Buffer.from(userDelegationKey.value, "base64"); } /** * Generates a hash signature for an HTTP request or for a SAS. * * @param stringToSign - */ computeHMACSHA256(stringToSign) { // console.log(`stringToSign: ${JSON.stringify(stringToSign)}`); return crypto.createHmac("sha256", this.key).update(stringToSign, "utf8").digest("base64"); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * Generate SasIPRange format string. For example: * * "8.8.8.8" or "1.1.1.1-255.255.255.255" * * @param ipRange - */ function ipRangeToString(ipRange) { return ipRange.end ? `${ipRange.start}-${ipRange.end}` : ipRange.start; } // Copyright (c) Microsoft Corporation. /** * Protocols for generated SAS. */ exports.SASProtocol = void 0; (function (SASProtocol) { /** * Protocol that allows HTTPS only */ SASProtocol["Https"] = "https"; /** * Protocol that allows both HTTPS and HTTP */ SASProtocol["HttpsAndHttp"] = "https,http"; })(exports.SASProtocol || (exports.SASProtocol = {})); /** * Represents the components that make up an Azure Storage SAS' query parameters. This type is not constructed directly * by the user; it is only generated by the {@link AccountSASSignatureValues} and {@link BlobSASSignatureValues} * types. Once generated, it can be encoded into a {@link String} and appended to a URL directly (though caution should * be taken here in case there are existing query parameters, which might affect the appropriate means of appending * these query parameters). * * NOTE: Instances of this class are immutable. */ class SASQueryParameters { constructor(version, signature, permissionsOrOptions, services, resourceTypes, protocol, startsOn, expiresOn, ipRange, identifier, resource, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType, userDelegationKey, preauthorizedAgentObjectId, correlationId, encryptionScope) { this.version = version; this.signature = signature; if (permissionsOrOptions !== undefined && typeof permissionsOrOptions !== "string") { // SASQueryParametersOptions this.permissions = permissionsOrOptions.permissions; this.services = permissionsOrOptions.services; this.resourceTypes = permissionsOrOptions.resourceTypes; this.protocol = permissionsOrOptions.protocol; this.startsOn = permissionsOrOptions.startsOn; this.expiresOn = permissionsOrOptions.expiresOn; this.ipRangeInner = permissionsOrOptions.ipRange; this.identifier = permissionsOrOptions.identifier; this.encryptionScope = permissionsOrOptions.encryptionScope; this.resource = permissionsOrOptions.resource; this.cacheControl = permissionsOrOptions.cacheControl; this.contentDisposition = permissionsOrOptions.contentDisposition; this.contentEncoding = permissionsOrOptions.contentEncoding; this.contentLanguage = permissionsOrOptions.contentLanguage; this.contentType = permissionsOrOptions.contentType; if (permissionsOrOptions.userDelegationKey) { this.signedOid = permissionsOrOptions.userDelegationKey.signedObjectId; this.signedTenantId = permissionsOrOptions.userDelegationKey.signedTenantId; this.signedStartsOn = permissionsOrOptions.userDelegationKey.signedStartsOn; this.signedExpiresOn = permissionsOrOptions.userDelegationKey.signedExpiresOn; this.signedService = permissionsOrOptions.userDelegationKey.signedService; this.signedVersion = permissionsOrOptions.userDelegationKey.signedVersion; this.preauthorizedAgentObjectId = permissionsOrOptions.preauthorizedAgentObjectId; this.correlationId = permissionsOrOptions.correlationId; } } else { this.services = services; this.resourceTypes = resourceTypes; this.expiresOn = expiresOn; this.permissions = permissionsOrOptions; this.protocol = protocol; this.startsOn = startsOn; this.ipRangeInner = ipRange; this.encryptionScope = encryptionScope; this.identifier = identifier; this.resource = resource; this.cacheControl = cacheControl; this.contentDisposition = contentDisposition; this.contentEncoding = contentEncoding; this.contentLanguage = contentLanguage; this.contentType = contentType; if (userDelegationKey) { this.signedOid = userDelegationKey.signedObjectId; this.signedTenantId = userDelegationKey.signedTenantId; this.signedStartsOn = userDelegationKey.signedStartsOn; this.signedExpiresOn = userDelegationKey.signedExpiresOn; this.signedService = userDelegationKey.signedService; this.signedVersion = userDelegationKey.signedVersion; this.preauthorizedAgentObjectId = preauthorizedAgentObjectId; this.correlationId = correlationId; } } } /** * Optional. IP range allowed for this SAS. * * @readonly */ get ipRange() { if (this.ipRangeInner) { return { end: this.ipRangeInner.end, start: this.ipRangeInner.start, }; } return undefined; } /** * Encodes all SAS query parameters into a string that can be appended to a URL. * */ toString() { const params = [ "sv", "ss", "srt", "spr", "st", "se", "sip", "si", "ses", "skoid", "sktid", "skt", "ske", "sks", "skv", "sr", "sp", "sig", "rscc", "rscd", "rsce", "rscl", "rsct", "saoid", "scid", ]; const queries = []; for (const param of params) { switch (param) { case "sv": this.tryAppendQueryParameter(queries, param, this.version); break; case "ss": this.tryAppendQueryParameter(queries, param, this.services); break; case "srt": this.tryAppendQueryParameter(queries, param, this.resourceTypes); break; case "spr": this.tryAppendQueryParameter(queries, param, this.protocol); break; case "st": this.tryAppendQueryParameter(queries, param, this.startsOn ? truncatedISO8061Date(this.startsOn, false) : undefined); break; case "se": this.tryAppendQueryParameter(queries, param, this.expiresOn ? truncatedISO8061Date(this.expiresOn, false) : undefined); break; case "sip": this.tryAppendQueryParameter(queries, param, this.ipRange ? ipRangeToString(this.ipRange) : undefined); break; case "si": this.tryAppendQueryParameter(queries, param, this.identifier); break; case "ses": this.tryAppendQueryParameter(queries, param, this.encryptionScope); break; case "skoid": // Signed object ID this.tryAppendQueryParameter(queries, param, this.signedOid); break; case "sktid": // Signed tenant ID this.tryAppendQueryParameter(queries, param, this.signedTenantId); break; case "skt": // Signed key start time this.tryAppendQueryParameter(queries, param, this.signedStartsOn ? truncatedISO8061Date(this.signedStartsOn, false) : undefined); break; case "ske": // Signed key expiry time this.tryAppendQueryParameter(queries, param, this.signedExpiresOn ? truncatedISO8061Date(this.signedExpiresOn, false) : undefined); break; case "sks": // Signed key service this.tryAppendQueryParameter(queries, param, this.signedService); break; case "skv": // Signed key version this.tryAppendQueryParameter(queries, param, this.signedVersion); break; case "sr": this.tryAppendQueryParameter(queries, param, this.resource); break; case "sp": this.tryAppendQueryParameter(queries, param, this.permissions); break; case "sig": this.tryAppendQueryParameter(queries, param, this.signature); break; case "rscc": this.tryAppendQueryParameter(queries, param, this.cacheControl); break; case "rscd": this.tryAppendQueryParameter(queries, param, this.contentDisposition); break; case "rsce": this.tryAppendQueryParameter(queries, param, this.contentEncoding); break; case "rscl": this.tryAppendQueryParameter(queries, param, this.contentLanguage); break; case "rsct": this.tryAppendQueryParameter(queries, param, this.contentType); break; case "saoid": this.tryAppendQueryParameter(queries, param, this.preauthorizedAgentObjectId); break; case "scid": this.tryAppendQueryParameter(queries, param, this.correlationId); break; } } return queries.join("&"); } /** * A private helper method used to filter and append query key/value pairs into an array. * * @param queries - * @param key - * @param value - */ tryAppendQueryParameter(queries, key, value) { if (!value) { return; } key = encodeURIComponent(key); value = encodeURIComponent(value); if (key.length > 0 && value.length > 0) { queries.push(`${key}=${value}`); } } } // Copyright (c) Microsoft Corporation. function generateBlobSASQueryParameters(blobSASSignatureValues, sharedKeyCredentialOrUserDelegationKey, accountName) { const version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; const sharedKeyCredential = sharedKeyCredentialOrUserDelegationKey instanceof StorageSharedKeyCredential ? sharedKeyCredentialOrUserDelegationKey : undefined; let userDelegationKeyCredential; if (sharedKeyCredential === undefined && accountName !== undefined) { userDelegationKeyCredential = new UserDelegationKeyCredential(accountName, sharedKeyCredentialOrUserDelegationKey); } if (sharedKeyCredential === undefined && userDelegationKeyCredential === undefined) { throw TypeError("Invalid sharedKeyCredential, userDelegationKey or accountName."); } // Version 2020-12-06 adds support for encryptionscope in SAS. if (version >= "2020-12-06") { if (sharedKeyCredential !== undefined) { return generateBlobSASQueryParameters20201206(blobSASSignatureValues, sharedKeyCredential); } else { return generateBlobSASQueryParametersUDK20201206(blobSASSignatureValues, userDelegationKeyCredential); } } // Version 2019-12-12 adds support for the blob tags permission. // Version 2018-11-09 adds support for the signed resource and signed blob snapshot time fields. // https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas#constructing-the-signature-string if (version >= "2018-11-09") { if (sharedKeyCredential !== undefined) { return generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential); } else { // Version 2020-02-10 delegation SAS signature construction includes preauthorizedAgentObjectId, agentObjectId, correlationId. if (version >= "2020-02-10") { return generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userDelegationKeyCredential); } else { return generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userDelegationKeyCredential); } } } if (version >= "2015-04-05") { if (sharedKeyCredential !== undefined) { return generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKeyCredential); } else { throw new RangeError("'version' must be >= '2018-11-09' when generating user delegation SAS using user delegation key."); } } throw new RangeError("'version' must be >= '2015-04-05'."); } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * IMPLEMENTATION FOR API VERSION FROM 2015-04-05 AND BEFORE 2018-11-09. * * Creates an instance of SASQueryParameters. * * Only accepts required settings needed to create a SAS. For optional settings please * set corresponding properties directly, such as permissions, startsOn and identifier. * * WARNING: When identifier is not provided, permissions and expiresOn are required. * You MUST assign value to identifier or expiresOn & permissions manually if you initial with * this constructor. * * @param blobSASSignatureValues - * @param sharedKeyCredential - */ function generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKeyCredential) { blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); if (!blobSASSignatureValues.identifier && !(blobSASSignatureValues.permissions && blobSASSignatureValues.expiresOn)) { throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); } let resource = "c"; if (blobSASSignatureValues.blobName) { resource = "b"; } // Calling parse and toString guarantees the proper ordering and throws on invalid characters. let verifiedPermissions; if (blobSASSignatureValues.permissions) { if (blobSASSignatureValues.blobName) { verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); } else { verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); } } // Signature is generated on the un-url-encoded values. const stringToSign = [ verifiedPermissions ? verifiedPermissions : "", blobSASSignatureValues.startsOn ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) : "", blobSASSignatureValues.expiresOn ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) : "", getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), blobSASSignatureValues.identifier, blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", blobSASSignatureValues.version, blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "", ].join("\n"); const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType); } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * IMPLEMENTATION FOR API VERSION FROM 2018-11-09. * * Creates an instance of SASQueryParameters. * * Only accepts required settings needed to create a SAS. For optional settings please * set corresponding properties directly, such as permissions, startsOn and identifier. * * WARNING: When identifier is not provided, permissions and expiresOn are required. * You MUST assign value to identifier or expiresOn & permissions manually if you initial with * this constructor. * * @param blobSASSignatureValues - * @param sharedKeyCredential - */ function generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential) { blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); if (!blobSASSignatureValues.identifier && !(blobSASSignatureValues.permissions && blobSASSignatureValues.expiresOn)) { throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); } let resource = "c"; let timestamp = blobSASSignatureValues.snapshotTime; if (blobSASSignatureValues.blobName) { resource = "b"; if (blobSASSignatureValues.snapshotTime) { resource = "bs"; } else if (blobSASSignatureValues.versionId) { resource = "bv"; timestamp = blobSASSignatureValues.versionId; } } // Calling parse and toString guarantees the proper ordering and throws on invalid characters. let verifiedPermissions; if (blobSASSignatureValues.permissions) { if (blobSASSignatureValues.blobName) { verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); } else { verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); } } // Signature is generated on the un-url-encoded values. const stringToSign = [ verifiedPermissions ? verifiedPermissions : "", blobSASSignatureValues.startsOn ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) : "", blobSASSignatureValues.expiresOn ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) : "", getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), blobSASSignatureValues.identifier, blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", blobSASSignatureValues.version, resource, timestamp, blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "", ].join("\n"); const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType); } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * IMPLEMENTATION FOR API VERSION FROM 2020-12-06. * * Creates an instance of SASQueryParameters. * * Only accepts required settings needed to create a SAS. For optional settings please * set corresponding properties directly, such as permissions, startsOn and identifier. * * WARNING: When identifier is not provided, permissions and expiresOn are required. * You MUST assign value to identifier or expiresOn & permissions manually if you initial with * this constructor. * * @param blobSASSignatureValues - * @param sharedKeyCredential - */ function generateBlobSASQueryParameters20201206(blobSASSignatureValues, sharedKeyCredential) { blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); if (!blobSASSignatureValues.identifier && !(blobSASSignatureValues.permissions && blobSASSignatureValues.expiresOn)) { throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); } let resource = "c"; let timestamp = blobSASSignatureValues.snapshotTime; if (blobSASSignatureValues.blobName) { resource = "b"; if (blobSASSignatureValues.snapshotTime) { resource = "bs"; } else if (blobSASSignatureValues.versionId) { resource = "bv"; timestamp = blobSASSignatureValues.versionId; } } // Calling parse and toString guarantees the proper ordering and throws on invalid characters. let verifiedPermissions; if (blobSASSignatureValues.permissions) { if (blobSASSignatureValues.blobName) { verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); } else { verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); } } // Signature is generated on the un-url-encoded values. const stringToSign = [ verifiedPermissions ? verifiedPermissions : "", blobSASSignatureValues.startsOn ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) : "", blobSASSignatureValues.expiresOn ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) : "", getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), blobSASSignatureValues.identifier, blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", blobSASSignatureValues.version, resource, timestamp, blobSASSignatureValues.encryptionScope, blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "", ].join("\n"); const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, undefined, undefined, undefined, blobSASSignatureValues.encryptionScope); } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * IMPLEMENTATION FOR API VERSION FROM 2018-11-09. * * Creates an instance of SASQueryParameters. * * Only accepts required settings needed to create a SAS. For optional settings please * set corresponding properties directly, such as permissions, startsOn. * * WARNING: identifier will be ignored, permissions and expiresOn are required. * * @param blobSASSignatureValues - * @param userDelegationKeyCredential - */ function generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userDelegationKeyCredential) { blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); // Stored access policies are not supported for a user delegation SAS. if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS."); } let resource = "c"; let timestamp = blobSASSignatureValues.snapshotTime; if (blobSASSignatureValues.blobName) { resource = "b"; if (blobSASSignatureValues.snapshotTime) { resource = "bs"; } else if (blobSASSignatureValues.versionId) { resource = "bv"; timestamp = blobSASSignatureValues.versionId; } } // Calling parse and toString guarantees the proper ordering and throws on invalid characters. let verifiedPermissions; if (blobSASSignatureValues.permissions) { if (blobSASSignatureValues.blobName) { verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); } else { verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); } } // Signature is generated on the un-url-encoded values. const stringToSign = [ verifiedPermissions ? verifiedPermissions : "", blobSASSignatureValues.startsOn ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) : "", blobSASSignatureValues.expiresOn ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) : "", getCanonicalName(userDelegationKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), userDelegationKeyCredential.userDelegationKey.signedObjectId, userDelegationKeyCredential.userDelegationKey.signedTenantId, userDelegationKeyCredential.userDelegationKey.signedStartsOn ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) : "", userDelegationKeyCredential.userDelegationKey.signedExpiresOn ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) : "", userDelegationKeyCredential.userDelegationKey.signedService, userDelegationKeyCredential.userDelegationKey.signedVersion, blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", blobSASSignatureValues.version, resource, timestamp, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, ].join("\n"); const signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey); } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * IMPLEMENTATION FOR API VERSION FROM 2020-02-10. * * Creates an instance of SASQueryParameters. * * Only accepts required settings needed to create a SAS. For optional settings please * set corresponding properties directly, such as permissions, startsOn. * * WARNING: identifier will be ignored, permissions and expiresOn are required. * * @param blobSASSignatureValues - * @param userDelegationKeyCredential - */ function generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userDelegationKeyCredential) { blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); // Stored access policies are not supported for a user delegation SAS. if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS."); } let resource = "c"; let timestamp = blobSASSignatureValues.snapshotTime; if (blobSASSignatureValues.blobName) { resource = "b"; if (blobSASSignatureValues.snapshotTime) { resource = "bs"; } else if (blobSASSignatureValues.versionId) { resource = "bv"; timestamp = blobSASSignatureValues.versionId; } } // Calling parse and toString guarantees the proper ordering and throws on invalid characters. let verifiedPermissions; if (blobSASSignatureValues.permissions) { if (blobSASSignatureValues.blobName) { verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); } else { verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); } } // Signature is generated on the un-url-encoded values. const stringToSign = [ verifiedPermissions ? verifiedPermissions : "", blobSASSignatureValues.startsOn ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) : "", blobSASSignatureValues.expiresOn ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) : "", getCanonicalName(userDelegationKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), userDelegationKeyCredential.userDelegationKey.signedObjectId, userDelegationKeyCredential.userDelegationKey.signedTenantId, userDelegationKeyCredential.userDelegationKey.signedStartsOn ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) : "", userDelegationKeyCredential.userDelegationKey.signedExpiresOn ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) : "", userDelegationKeyCredential.userDelegationKey.signedService, userDelegationKeyCredential.userDelegationKey.signedVersion, blobSASSignatureValues.preauthorizedAgentObjectId, undefined, blobSASSignatureValues.correlationId, blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", blobSASSignatureValues.version, resource, timestamp, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, ].join("\n"); const signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey, blobSASSignatureValues.preauthorizedAgentObjectId, blobSASSignatureValues.correlationId); } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * IMPLEMENTATION FOR API VERSION FROM 2020-12-06. * * Creates an instance of SASQueryParameters. * * Only accepts required settings needed to create a SAS. For optional settings please * set corresponding properties directly, such as permissions, startsOn. * * WARNING: identifier will be ignored, permissions and expiresOn are required. * * @param blobSASSignatureValues - * @param userDelegationKeyCredential - */ function generateBlobSASQueryParametersUDK20201206(blobSASSignatureValues, userDelegationKeyCredential) { blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); // Stored access policies are not supported for a user delegation SAS. if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS."); } let resource = "c"; let timestamp = blobSASSignatureValues.snapshotTime; if (blobSASSignatureValues.blobName) { resource = "b"; if (blobSASSignatureValues.snapshotTime) { resource = "bs"; } else if (blobSASSignatureValues.versionId) { resource = "bv"; timestamp = blobSASSignatureValues.versionId; } } // Calling parse and toString guarantees the proper ordering and throws on invalid characters. let verifiedPermissions; if (blobSASSignatureValues.permissions) { if (blobSASSignatureValues.blobName) { verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); } else { verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); } } // Signature is generated on the un-url-encoded values. const stringToSign = [ verifiedPermissions ? verifiedPermissions : "", blobSASSignatureValues.startsOn ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) : "", blobSASSignatureValues.expiresOn ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) : "", getCanonicalName(userDelegationKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), userDelegationKeyCredential.userDelegationKey.signedObjectId, userDelegationKeyCredential.userDelegationKey.signedTenantId, userDelegationKeyCredential.userDelegationKey.signedStartsOn ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) : "", userDelegationKeyCredential.userDelegationKey.signedExpiresOn ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) : "", userDelegationKeyCredential.userDelegationKey.signedService, userDelegationKeyCredential.userDelegationKey.signedVersion, blobSASSignatureValues.preauthorizedAgentObjectId, undefined, blobSASSignatureValues.correlationId, blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", blobSASSignatureValues.version, resource, timestamp, blobSASSignatureValues.encryptionScope, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, ].join("\n"); const signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey, blobSASSignatureValues.preauthorizedAgentObjectId, blobSASSignatureValues.correlationId, blobSASSignatureValues.encryptionScope); } function getCanonicalName(accountName, containerName, blobName) { // Container: "/blob/account/containerName" // Blob: "/blob/account/containerName/blobName" const elements = [`/blob/${accountName}/${containerName}`]; if (blobName) { elements.push(`/${blobName}`); } return elements.join(""); } function SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues) { const version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; if (blobSASSignatureValues.snapshotTime && version < "2018-11-09") { throw RangeError("'version' must be >= '2018-11-09' when providing 'snapshotTime'."); } if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.snapshotTime) { throw RangeError("Must provide 'blobName' when providing 'snapshotTime'."); } if (blobSASSignatureValues.versionId && version < "2019-10-10") { throw RangeError("'version' must be >= '2019-10-10' when providing 'versionId'."); } if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.versionId) { throw RangeError("Must provide 'blobName' when providing 'versionId'."); } if (blobSASSignatureValues.permissions && blobSASSignatureValues.permissions.setImmutabilityPolicy && version < "2020-08-04") { throw RangeError("'version' must be >= '2020-08-04' when provided 'i' permission."); } if (blobSASSignatureValues.permissions && blobSASSignatureValues.permissions.deleteVersion && version < "2019-10-10") { throw RangeError("'version' must be >= '2019-10-10' when providing 'x' permission."); } if (blobSASSignatureValues.permissions && blobSASSignatureValues.permissions.permanentDelete && version < "2019-10-10") { throw RangeError("'version' must be >= '2019-10-10' when providing 'y' permission."); } if (blobSASSignatureValues.permissions && blobSASSignatureValues.permissions.tag && version < "2019-12-12") { throw RangeError("'version' must be >= '2019-12-12' when providing 't' permission."); } if (version < "2020-02-10" && blobSASSignatureValues.permissions && (blobSASSignatureValues.permissions.move || blobSASSignatureValues.permissions.execute)) { throw RangeError("'version' must be >= '2020-02-10' when providing the 'm' or 'e' permission."); } if (version < "2021-04-10" && blobSASSignatureValues.permissions && blobSASSignatureValues.permissions.filterByTags) { throw RangeError("'version' must be >= '2021-04-10' when providing the 'f' permission."); } if (version < "2020-02-10" && (blobSASSignatureValues.preauthorizedAgentObjectId || blobSASSignatureValues.correlationId)) { throw RangeError("'version' must be >= '2020-02-10' when providing 'preauthorizedAgentObjectId' or 'correlationId'."); } if (blobSASSignatureValues.encryptionScope && version < "2020-12-06") { throw RangeError("'version' must be >= '2020-12-06' when provided 'encryptionScope' in SAS."); } blobSASSignatureValues.version = version; return blobSASSignatureValues; } // Copyright (c) Microsoft Corporation. /** * A client that manages leases for a {@link ContainerClient} or a {@link BlobClient}. */ class BlobLeaseClient { /** * Creates an instance of BlobLeaseClient. * @param client - The client to make the lease operation requests. * @param leaseId - Initial proposed lease id. */ constructor(client, leaseId) { const clientContext = new StorageClientContext(client.url, client.pipeline.toServiceClientOptions()); this._url = client.url; if (client.name === undefined) { this._isContainer = true; this._containerOrBlobOperation = new Container(clientContext); } else { this._isContainer = false; this._containerOrBlobOperation = new Blob$1(clientContext); } if (!leaseId) { leaseId = coreHttp.generateUuid(); } this._leaseId = leaseId; } /** * Gets the lease Id. * * @readonly */ get leaseId() { return this._leaseId; } /** * Gets the url. * * @readonly */ get url() { return this._url; } /** * Establishes and manages a lock on a container for delete operations, or on a blob * for write and delete operations. * The lock duration can be 15 to 60 seconds, or can be infinite. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container * and * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob * * @param duration - Must be between 15 to 60 seconds, or infinite (-1) * @param options - option to configure lease management operations. * @returns Response data for acquire lease operation. */ async acquireLease(duration, options = {}) { var _a, _b, _c, _d, _e, _f; const { span, updatedOptions } = createSpan("BlobLeaseClient-acquireLease", options); if (this._isContainer && ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); } try { return await this._containerOrBlobOperation.acquireLease(Object.assign({ abortSignal: options.abortSignal, duration, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), proposedLeaseId: this._leaseId }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * To change the ID of the lease. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container * and * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob * * @param proposedLeaseId - the proposed new lease Id. * @param options - option to configure lease management operations. * @returns Response data for change lease operation. */ async changeLease(proposedLeaseId, options = {}) { var _a, _b, _c, _d, _e, _f; const { span, updatedOptions } = createSpan("BlobLeaseClient-changeLease", options); if (this._isContainer && ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); } try { const response = await this._containerOrBlobOperation.changeLease(this._leaseId, proposedLeaseId, Object.assign({ abortSignal: options.abortSignal, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); this._leaseId = proposedLeaseId; return response; } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * To free the lease if it is no longer needed so that another client may * immediately acquire a lease against the container or the blob. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container * and * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob * * @param options - option to configure lease management operations. * @returns Response data for release lease operation. */ async releaseLease(options = {}) { var _a, _b, _c, _d, _e, _f; const { span, updatedOptions } = createSpan("BlobLeaseClient-releaseLease", options); if (this._isContainer && ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); } try { return await this._containerOrBlobOperation.releaseLease(this._leaseId, Object.assign({ abortSignal: options.abortSignal, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * To renew the lease. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container * and * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob * * @param options - Optional option to configure lease management operations. * @returns Response data for renew lease operation. */ async renewLease(options = {}) { var _a, _b, _c, _d, _e, _f; const { span, updatedOptions } = createSpan("BlobLeaseClient-renewLease", options); if (this._isContainer && ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); } try { return await this._containerOrBlobOperation.renewLease(this._leaseId, Object.assign({ abortSignal: options.abortSignal, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * To end the lease but ensure that another client cannot acquire a new lease * until the current lease period has expired. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container * and * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob * * @param breakPeriod - Break period * @param options - Optional options to configure lease management operations. * @returns Response data for break lease operation. */ async breakLease(breakPeriod, options = {}) { var _a, _b, _c, _d, _e, _f; const { span, updatedOptions } = createSpan("BlobLeaseClient-breakLease", options); if (this._isContainer && ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); } try { const operationOptions = Object.assign({ abortSignal: options.abortSignal, breakPeriod, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)); return await this._containerOrBlobOperation.breakLease(operationOptions); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } } // Copyright (c) Microsoft Corporation. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * A Node.js ReadableStream will internally retry when internal ReadableStream unexpected ends. */ class RetriableReadableStream extends stream.Readable { /** * Creates an instance of RetriableReadableStream. * * @param source - The current ReadableStream returned from getter * @param getter - A method calling downloading request returning * a new ReadableStream from specified offset * @param offset - Offset position in original data source to read * @param count - How much data in original data source to read * @param options - */ constructor(source, getter, offset, count, options = {}) { super({ highWaterMark: options.highWaterMark }); this.retries = 0; this.sourceDataHandler = (data) => { if (this.options.doInjectErrorOnce) { this.options.doInjectErrorOnce = undefined; this.source.pause(); this.source.removeAllListeners("data"); this.source.emit("end"); return; } // console.log( // `Offset: ${this.offset}, Received ${data.length} from internal stream` // ); this.offset += data.length; if (this.onProgress) { this.onProgress({ loadedBytes: this.offset - this.start }); } if (!this.push(data)) { this.source.pause(); } }; this.sourceErrorOrEndHandler = (err) => { if (err && err.name === "AbortError") { this.destroy(err); return; } // console.log( // `Source stream emits end or error, offset: ${ // this.offset // }, dest end : ${this.end}` // ); this.removeSourceEventHandlers(); if (this.offset - 1 === this.end) { this.push(null); } else if (this.offset <= this.end) { // console.log( // `retries: ${this.retries}, max retries: ${this.maxRetries}` // ); if (this.retries < this.maxRetryRequests) { this.retries += 1; this.getter(this.offset) .then((newSource) => { this.source = newSource; this.setSourceEventHandlers(); return; }) .catch((error) => { this.destroy(error); }); } else { this.destroy(new Error(`Data corruption failure: received less data than required and reached maxRetires limitation. Received data offset: ${this.offset - 1}, data needed offset: ${this.end}, retries: ${this.retries}, max retries: ${this.maxRetryRequests}`)); } } else { this.destroy(new Error(`Data corruption failure: Received more data than original request, data needed offset is ${this.end}, received offset: ${this.offset - 1}`)); } }; this.getter = getter; this.source = source; this.start = offset; this.offset = offset; this.end = offset + count - 1; this.maxRetryRequests = options.maxRetryRequests && options.maxRetryRequests >= 0 ? options.maxRetryRequests : 0; this.onProgress = options.onProgress; this.options = options; this.setSourceEventHandlers(); } _read() { this.source.resume(); } setSourceEventHandlers() { this.source.on("data", this.sourceDataHandler); this.source.on("end", this.sourceErrorOrEndHandler); this.source.on("error", this.sourceErrorOrEndHandler); } removeSourceEventHandlers() { this.source.removeListener("data", this.sourceDataHandler); this.source.removeListener("end", this.sourceErrorOrEndHandler); this.source.removeListener("error", this.sourceErrorOrEndHandler); } _destroy(error, callback) { // remove listener from source and release source this.removeSourceEventHandlers(); this.source.destroy(); callback(error === null ? undefined : error); } } // Copyright (c) Microsoft Corporation. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * BlobDownloadResponse implements BlobDownloadResponseParsed interface, and in Node.js runtime it will * automatically retry when internal read stream unexpected ends. (This kind of unexpected ends cannot * trigger retries defined in pipeline retry policy.) * * The {@link readableStreamBody} stream will retry underlayer, you can just use it as a normal Node.js * Readable stream. */ class BlobDownloadResponse { /** * Creates an instance of BlobDownloadResponse. * * @param originalResponse - * @param getter - * @param offset - * @param count - * @param options - */ constructor(originalResponse, getter, offset, count, options = {}) { this.originalResponse = originalResponse; this.blobDownloadStream = new RetriableReadableStream(this.originalResponse.readableStreamBody, getter, offset, count, options); } /** * Indicates that the service supports * requests for partial file content. * * @readonly */ get acceptRanges() { return this.originalResponse.acceptRanges; } /** * Returns if it was previously specified * for the file. * * @readonly */ get cacheControl() { return this.originalResponse.cacheControl; } /** * Returns the value that was specified * for the 'x-ms-content-disposition' header and specifies how to process the * response. * * @readonly */ get contentDisposition() { return this.originalResponse.contentDisposition; } /** * Returns the value that was specified * for the Content-Encoding request header. * * @readonly */ get contentEncoding() { return this.originalResponse.contentEncoding; } /** * Returns the value that was specified * for the Content-Language request header. * * @readonly */ get contentLanguage() { return this.originalResponse.contentLanguage; } /** * The current sequence number for a * page blob. This header is not returned for block blobs or append blobs. * * @readonly */ get blobSequenceNumber() { return this.originalResponse.blobSequenceNumber; } /** * The blob's type. Possible values include: * 'BlockBlob', 'PageBlob', 'AppendBlob'. * * @readonly */ get blobType() { return this.originalResponse.blobType; } /** * The number of bytes present in the * response body. * * @readonly */ get contentLength() { return this.originalResponse.contentLength; } /** * If the file has an MD5 hash and the * request is to read the full file, this response header is returned so that * the client can check for message content integrity. If the request is to * read a specified range and the 'x-ms-range-get-content-md5' is set to * true, then the request returns an MD5 hash for the range, as long as the * range size is less than or equal to 4 MB. If neither of these sets of * conditions is true, then no value is returned for the 'Content-MD5' * header. * * @readonly */ get contentMD5() { return this.originalResponse.contentMD5; } /** * Indicates the range of bytes returned if * the client requested a subset of the file by setting the Range request * header. * * @readonly */ get contentRange() { return this.originalResponse.contentRange; } /** * The content type specified for the file. * The default content type is 'application/octet-stream' * * @readonly */ get contentType() { return this.originalResponse.contentType; } /** * Conclusion time of the last attempted * Copy File operation where this file was the destination file. This value * can specify the time of a completed, aborted, or failed copy attempt. * * @readonly */ get copyCompletedOn() { return this.originalResponse.copyCompletedOn; } /** * String identifier for the last attempted Copy * File operation where this file was the destination file. * * @readonly */ get copyId() { return this.originalResponse.copyId; } /** * Contains the number of bytes copied and * the total bytes in the source in the last attempted Copy File operation * where this file was the destination file. Can show between 0 and * Content-Length bytes copied. * * @readonly */ get copyProgress() { return this.originalResponse.copyProgress; } /** * URL up to 2KB in length that specifies the * source file used in the last attempted Copy File operation where this file * was the destination file. * * @readonly */ get copySource() { return this.originalResponse.copySource; } /** * State of the copy operation * identified by 'x-ms-copy-id'. Possible values include: 'pending', * 'success', 'aborted', 'failed' * * @readonly */ get copyStatus() { return this.originalResponse.copyStatus; } /** * Only appears when * x-ms-copy-status is failed or pending. Describes cause of fatal or * non-fatal copy operation failure. * * @readonly */ get copyStatusDescription() { return this.originalResponse.copyStatusDescription; } /** * When a blob is leased, * specifies whether the lease is of infinite or fixed duration. Possible * values include: 'infinite', 'fixed'. * * @readonly */ get leaseDuration() { return this.originalResponse.leaseDuration; } /** * Lease state of the blob. Possible * values include: 'available', 'leased', 'expired', 'breaking', 'broken'. * * @readonly */ get leaseState() { return this.originalResponse.leaseState; } /** * The current lease status of the * blob. Possible values include: 'locked', 'unlocked'. * * @readonly */ get leaseStatus() { return this.originalResponse.leaseStatus; } /** * A UTC date/time value generated by the service that * indicates the time at which the response was initiated. * * @readonly */ get date() { return this.originalResponse.date; } /** * The number of committed blocks * present in the blob. This header is returned only for append blobs. * * @readonly */ get blobCommittedBlockCount() { return this.originalResponse.blobCommittedBlockCount; } /** * The ETag contains a value that you can use to * perform operations conditionally, in quotes. * * @readonly */ get etag() { return this.originalResponse.etag; } /** * The number of tags associated with the blob * * @readonly */ get tagCount() { return this.originalResponse.tagCount; } /** * The error code. * * @readonly */ get errorCode() { return this.originalResponse.errorCode; } /** * The value of this header is set to * true if the file data and application metadata are completely encrypted * using the specified algorithm. Otherwise, the value is set to false (when * the file is unencrypted, or if only parts of the file/application metadata * are encrypted). * * @readonly */ get isServerEncrypted() { return this.originalResponse.isServerEncrypted; } /** * If the blob has a MD5 hash, and if * request contains range header (Range or x-ms-range), this response header * is returned with the value of the whole blob's MD5 value. This value may * or may not be equal to the value returned in Content-MD5 header, with the * latter calculated from the requested range. * * @readonly */ get blobContentMD5() { return this.originalResponse.blobContentMD5; } /** * Returns the date and time the file was last * modified. Any operation that modifies the file or its properties updates * the last modified time. * * @readonly */ get lastModified() { return this.originalResponse.lastModified; } /** * Returns the UTC date and time generated by the service that indicates the time at which the blob was * last read or written to. * * @readonly */ 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. * * @readonly */ get metadata() { return this.originalResponse.metadata; } /** * This header uniquely identifies the request * that was made and can be used for troubleshooting the request. * * @readonly */ get requestId() { return this.originalResponse.requestId; } /** * If a client request id header is sent in the request, this header will be present in the * response with the same value. * * @readonly */ get clientRequestId() { return this.originalResponse.clientRequestId; } /** * Indicates the version of the Blob service used * to execute the request. * * @readonly */ get version() { return this.originalResponse.version; } /** * Indicates the versionId of the downloaded blob version. * * @readonly */ get versionId() { return this.originalResponse.versionId; } /** * Indicates whether version of this blob is a current version. * * @readonly */ get isCurrentVersion() { return this.originalResponse.isCurrentVersion; } /** * The SHA-256 hash of the encryption key used to encrypt the blob. This value is only returned * when the blob was encrypted with a customer-provided key. * * @readonly */ get encryptionKeySha256() { return this.originalResponse.encryptionKeySha256; } /** * If the request is to read a specified range and the x-ms-range-get-content-crc64 is set to * true, then the request returns a crc64 for the range, as long as the range size is less than * or equal to 4 MB. If both x-ms-range-get-content-crc64 & x-ms-range-get-content-md5 is * specified in the same request, it will fail with 400(Bad Request) */ get contentCrc64() { return this.originalResponse.contentCrc64; } /** * Object Replication Policy Id of the destination blob. * * @readonly */ get objectReplicationDestinationPolicyId() { return this.originalResponse.objectReplicationDestinationPolicyId; } /** * Parsed Object Replication Policy Id, Rule Id(s) and status of the source blob. * * @readonly */ get objectReplicationSourceProperties() { return this.originalResponse.objectReplicationSourceProperties; } /** * If this blob has been sealed. * * @readonly */ get isSealed() { return this.originalResponse.isSealed; } /** * UTC date/time value generated by the service that indicates the time at which the blob immutability policy will expire. * * @readonly */ get immutabilityPolicyExpiresOn() { return this.originalResponse.immutabilityPolicyExpiresOn; } /** * Indicates immutability policy mode. * * @readonly */ get immutabilityPolicyMode() { return this.originalResponse.immutabilityPolicyMode; } /** * Indicates if a legal hold is present on the blob. * * @readonly */ get legalHold() { return this.originalResponse.legalHold; } /** * The response body as a browser Blob. * Always undefined in node.js. * * @readonly */ get contentAsBlob() { return this.originalResponse.blobBody; } /** * The response body as a node.js Readable stream. * Always undefined in the browser. * * It will automatically retry when internal read stream unexpected ends. * * @readonly */ get readableStreamBody() { return coreHttp.isNode ? this.blobDownloadStream : undefined; } /** * The HTTP response. */ get _response() { return this.originalResponse._response; } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. const AVRO_SYNC_MARKER_SIZE = 16; const AVRO_INIT_BYTES = new Uint8Array([79, 98, 106, 1]); const AVRO_CODEC_KEY = "avro.codec"; const AVRO_SCHEMA_KEY = "avro.schema"; // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. class AvroParser { /** * Reads a fixed number of bytes from the stream. * * @param stream - * @param length - * @param options - */ static async readFixedBytes(stream, length, options = {}) { const bytes = await stream.read(length, { abortSignal: options.abortSignal }); if (bytes.length !== length) { throw new Error("Hit stream end."); } return bytes; } /** * Reads a single byte from the stream. * * @param stream - * @param options - */ static async readByte(stream, options = {}) { const buf = await AvroParser.readFixedBytes(stream, 1, options); return buf[0]; } // int and long are stored in variable-length zig-zag coding. // variable-length: https://lucene.apache.org/core/3_5_0/fileformats.html#VInt // zig-zag: https://developers.google.com/protocol-buffers/docs/encoding?csw=1#types static async readZigZagLong(stream, options = {}) { let zigZagEncoded = 0; let significanceInBit = 0; let byte, haveMoreByte, significanceInFloat; do { byte = await AvroParser.readByte(stream, options); haveMoreByte = byte & 0x80; zigZagEncoded |= (byte & 0x7f) << significanceInBit; significanceInBit += 7; } while (haveMoreByte && significanceInBit < 28); // bitwise operation only works for 32-bit integers if (haveMoreByte) { // Switch to float arithmetic // eslint-disable-next-line no-self-assign zigZagEncoded = zigZagEncoded; significanceInFloat = 268435456; // 2 ** 28. do { byte = await AvroParser.readByte(stream, options); zigZagEncoded += (byte & 0x7f) * significanceInFloat; significanceInFloat *= 128; // 2 ** 7 } while (byte & 0x80); const res = (zigZagEncoded % 2 ? -(zigZagEncoded + 1) : zigZagEncoded) / 2; if (res < Number.MIN_SAFE_INTEGER || res > Number.MAX_SAFE_INTEGER) { throw new Error("Integer overflow."); } return res; } return (zigZagEncoded >> 1) ^ -(zigZagEncoded & 1); } static async readLong(stream, options = {}) { return AvroParser.readZigZagLong(stream, options); } static async readInt(stream, options = {}) { return AvroParser.readZigZagLong(stream, options); } static async readNull() { return null; } static async readBoolean(stream, options = {}) { const b = await AvroParser.readByte(stream, options); if (b === 1) { return true; } else if (b === 0) { return false; } else { throw new Error("Byte was not a boolean."); } } static async readFloat(stream, options = {}) { const u8arr = await AvroParser.readFixedBytes(stream, 4, options); const view = new DataView(u8arr.buffer, u8arr.byteOffset, u8arr.byteLength); return view.getFloat32(0, true); // littleEndian = true } static async readDouble(stream, options = {}) { const u8arr = await AvroParser.readFixedBytes(stream, 8, options); const view = new DataView(u8arr.buffer, u8arr.byteOffset, u8arr.byteLength); return view.getFloat64(0, true); // littleEndian = true } static async readBytes(stream, options = {}) { const size = await AvroParser.readLong(stream, options); if (size < 0) { throw new Error("Bytes size was negative."); } return stream.read(size, { abortSignal: options.abortSignal }); } static async readString(stream, options = {}) { const u8arr = await AvroParser.readBytes(stream, options); const utf8decoder = new TextDecoder(); return utf8decoder.decode(u8arr); } static async readMapPair(stream, readItemMethod, options = {}) { const key = await AvroParser.readString(stream, options); // FUTURE: this won't work with readFixed (currently not supported) which needs a length as the parameter. const value = await readItemMethod(stream, options); return { key, value }; } static async readMap(stream, readItemMethod, options = {}) { const readPairMethod = (s, opts = {}) => { return AvroParser.readMapPair(s, readItemMethod, opts); }; const pairs = await AvroParser.readArray(stream, readPairMethod, options); const dict = {}; for (const pair of pairs) { dict[pair.key] = pair.value; } return dict; } static async readArray(stream, readItemMethod, options = {}) { const items = []; for (let count = await AvroParser.readLong(stream, options); count !== 0; count = await AvroParser.readLong(stream, options)) { if (count < 0) { // Ignore block sizes await AvroParser.readLong(stream, options); count = -count; } while (count--) { const item = await readItemMethod(stream, options); items.push(item); } } return items; } } var AvroComplex; (function (AvroComplex) { AvroComplex["RECORD"] = "record"; AvroComplex["ENUM"] = "enum"; AvroComplex["ARRAY"] = "array"; AvroComplex["MAP"] = "map"; AvroComplex["UNION"] = "union"; AvroComplex["FIXED"] = "fixed"; })(AvroComplex || (AvroComplex = {})); var AvroPrimitive; (function (AvroPrimitive) { AvroPrimitive["NULL"] = "null"; AvroPrimitive["BOOLEAN"] = "boolean"; AvroPrimitive["INT"] = "int"; AvroPrimitive["LONG"] = "long"; AvroPrimitive["FLOAT"] = "float"; AvroPrimitive["DOUBLE"] = "double"; AvroPrimitive["BYTES"] = "bytes"; AvroPrimitive["STRING"] = "string"; })(AvroPrimitive || (AvroPrimitive = {})); class AvroType { /** * Determines the AvroType from the Avro Schema. */ static fromSchema(schema) { if (typeof schema === "string") { return AvroType.fromStringSchema(schema); } else if (Array.isArray(schema)) { return AvroType.fromArraySchema(schema); } else { return AvroType.fromObjectSchema(schema); } } static fromStringSchema(schema) { switch (schema) { case AvroPrimitive.NULL: case AvroPrimitive.BOOLEAN: case AvroPrimitive.INT: case AvroPrimitive.LONG: case AvroPrimitive.FLOAT: case AvroPrimitive.DOUBLE: case AvroPrimitive.BYTES: case AvroPrimitive.STRING: return new AvroPrimitiveType(schema); default: throw new Error(`Unexpected Avro type ${schema}`); } } static fromArraySchema(schema) { return new AvroUnionType(schema.map(AvroType.fromSchema)); } static fromObjectSchema(schema) { const type = schema.type; // Primitives can be defined as strings or objects try { return AvroType.fromStringSchema(type); } catch (err) { // eslint-disable-line no-empty } switch (type) { case AvroComplex.RECORD: if (schema.aliases) { throw new Error(`aliases currently is not supported, schema: ${schema}`); } if (!schema.name) { throw new Error(`Required attribute 'name' doesn't exist on schema: ${schema}`); } // eslint-disable-next-line no-case-declarations const fields = {}; if (!schema.fields) { throw new Error(`Required attribute 'fields' doesn't exist on schema: ${schema}`); } for (const field of schema.fields) { fields[field.name] = AvroType.fromSchema(field.type); } return new AvroRecordType(fields, schema.name); case AvroComplex.ENUM: if (schema.aliases) { throw new Error(`aliases currently is not supported, schema: ${schema}`); } if (!schema.symbols) { throw new Error(`Required attribute 'symbols' doesn't exist on schema: ${schema}`); } return new AvroEnumType(schema.symbols); case AvroComplex.MAP: if (!schema.values) { throw new Error(`Required attribute 'values' doesn't exist on schema: ${schema}`); } return new AvroMapType(AvroType.fromSchema(schema.values)); case AvroComplex.ARRAY: // Unused today case AvroComplex.FIXED: // Unused today default: throw new Error(`Unexpected Avro type ${type} in ${schema}`); } } } class AvroPrimitiveType extends AvroType { constructor(primitive) { super(); this._primitive = primitive; } read(stream, options = {}) { switch (this._primitive) { case AvroPrimitive.NULL: return AvroParser.readNull(); case AvroPrimitive.BOOLEAN: return AvroParser.readBoolean(stream, options); case AvroPrimitive.INT: return AvroParser.readInt(stream, options); case AvroPrimitive.LONG: return AvroParser.readLong(stream, options); case AvroPrimitive.FLOAT: return AvroParser.readFloat(stream, options); case AvroPrimitive.DOUBLE: return AvroParser.readDouble(stream, options); case AvroPrimitive.BYTES: return AvroParser.readBytes(stream, options); case AvroPrimitive.STRING: return AvroParser.readString(stream, options); default: throw new Error("Unknown Avro Primitive"); } } } class AvroEnumType extends AvroType { constructor(symbols) { super(); this._symbols = symbols; } async read(stream, options = {}) { const value = await AvroParser.readInt(stream, options); return this._symbols[value]; } } class AvroUnionType extends AvroType { constructor(types) { super(); 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); } } class AvroMapType extends AvroType { constructor(itemType) { super(); this._itemType = itemType; } read(stream, options = {}) { const readItemMethod = (s, opts) => { return this._itemType.read(s, opts); }; return AvroParser.readMap(stream, readItemMethod, options); } } class AvroRecordType extends AvroType { constructor(fields, name) { super(); this._fields = fields; this._name = name; } async read(stream, options = {}) { const record = {}; record["$schema"] = this._name; for (const key in this._fields) { if (Object.prototype.hasOwnProperty.call(this._fields, key)) { record[key] = await this._fields[key].read(stream, options); } } return record; } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. function arraysEqual(a, b) { if (a === b) return true; // eslint-disable-next-line eqeqeq if (a == null || b == null) return false; if (a.length !== b.length) return false; for (let i = 0; i < a.length; ++i) { if (a[i] !== b[i]) return false; } return true; } // Copyright (c) Microsoft Corporation. class AvroReader { constructor(dataStream, headerStream, currentBlockOffset, indexWithinCurrentBlock) { this._dataStream = dataStream; this._headerStream = headerStream || dataStream; this._initialized = false; this._blockOffset = currentBlockOffset || 0; this._objectIndex = indexWithinCurrentBlock || 0; this._initialBlockOffset = currentBlockOffset || 0; } get blockOffset() { return this._blockOffset; } get objectIndex() { return this._objectIndex; } async initialize(options = {}) { const header = await AvroParser.readFixedBytes(this._headerStream, AVRO_INIT_BYTES.length, { abortSignal: options.abortSignal, }); if (!arraysEqual(header, AVRO_INIT_BYTES)) { throw new Error("Stream is not an Avro file."); } // File metadata is written as if defined by the following map schema: // { "type": "map", "values": "bytes"} this._metadata = await AvroParser.readMap(this._headerStream, AvroParser.readString, { abortSignal: options.abortSignal, }); // Validate codec const codec = this._metadata[AVRO_CODEC_KEY]; if (!(codec === undefined || codec === null || codec === "null")) { throw new Error("Codecs are not supported"); } // The 16-byte, randomly-generated sync marker for this file. this._syncMarker = await AvroParser.readFixedBytes(this._headerStream, AVRO_SYNC_MARKER_SIZE, { abortSignal: options.abortSignal, }); // Parse the schema const schema = JSON.parse(this._metadata[AVRO_SCHEMA_KEY]); this._itemType = AvroType.fromSchema(schema); if (this._blockOffset === 0) { this._blockOffset = this._initialBlockOffset + this._dataStream.position; } this._itemsRemainingInBlock = await AvroParser.readLong(this._dataStream, { abortSignal: options.abortSignal, }); // skip block length await AvroParser.readLong(this._dataStream, { abortSignal: options.abortSignal }); this._initialized = true; if (this._objectIndex && this._objectIndex > 0) { for (let i = 0; i < this._objectIndex; i++) { await this._itemType.read(this._dataStream, { abortSignal: options.abortSignal }); this._itemsRemainingInBlock--; } } } hasNext() { return !this._initialized || this._itemsRemainingInBlock > 0; } parseObjects(options = {}) { return tslib.__asyncGenerator(this, arguments, function* parseObjects_1() { if (!this._initialized) { yield tslib.__await(this.initialize(options)); } while (this.hasNext()) { const result = yield tslib.__await(this._itemType.read(this._dataStream, { abortSignal: options.abortSignal, })); this._itemsRemainingInBlock--; this._objectIndex++; if (this._itemsRemainingInBlock === 0) { const marker = yield tslib.__await(AvroParser.readFixedBytes(this._dataStream, AVRO_SYNC_MARKER_SIZE, { abortSignal: options.abortSignal, })); this._blockOffset = this._initialBlockOffset + this._dataStream.position; this._objectIndex = 0; if (!arraysEqual(this._syncMarker, marker)) { throw new Error("Stream is not a valid Avro file."); } try { this._itemsRemainingInBlock = yield tslib.__await(AvroParser.readLong(this._dataStream, { abortSignal: options.abortSignal, })); } catch (err) { // We hit the end of the stream. this._itemsRemainingInBlock = 0; } if (this._itemsRemainingInBlock > 0) { // Ignore block size yield tslib.__await(AvroParser.readLong(this._dataStream, { abortSignal: options.abortSignal })); } } yield yield tslib.__await(result); } }); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. class AvroReadable { } // Copyright (c) Microsoft Corporation. const ABORT_ERROR = new abortController.AbortError("Reading from the avro stream was aborted."); class AvroReadableFromStream extends AvroReadable { constructor(readable) { super(); this._readable = readable; this._position = 0; } toUint8Array(data) { if (typeof data === "string") { return Buffer.from(data); } return data; } get position() { return this._position; } async read(size, options = {}) { var _a; if ((_a = options.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { throw ABORT_ERROR; } if (size < 0) { throw new Error(`size parameter should be positive: ${size}`); } if (size === 0) { return new Uint8Array(); } if (!this._readable.readable) { throw new Error("Stream no longer readable."); } // See if there is already enough data. const chunk = this._readable.read(size); if (chunk) { this._position += chunk.length; // chunk.length maybe less than desired size if the stream ends. return this.toUint8Array(chunk); } else { // register callback to wait for enough data to read return new Promise((resolve, reject) => { /* eslint-disable @typescript-eslint/no-use-before-define */ const cleanUp = () => { this._readable.removeListener("readable", readableCallback); this._readable.removeListener("error", rejectCallback); this._readable.removeListener("end", rejectCallback); this._readable.removeListener("close", rejectCallback); if (options.abortSignal) { options.abortSignal.removeEventListener("abort", abortHandler); } }; const readableCallback = () => { const callbackChunk = this._readable.read(size); if (callbackChunk) { this._position += callbackChunk.length; cleanUp(); // callbackChunk.length maybe less than desired size if the stream ends. resolve(this.toUint8Array(callbackChunk)); } }; const rejectCallback = () => { cleanUp(); reject(); }; const abortHandler = () => { cleanUp(); reject(ABORT_ERROR); }; this._readable.on("readable", readableCallback); this._readable.once("error", rejectCallback); this._readable.once("end", rejectCallback); this._readable.once("close", rejectCallback); if (options.abortSignal) { options.abortSignal.addEventListener("abort", abortHandler); } /* eslint-enable @typescript-eslint/no-use-before-define */ }); } } } // Copyright (c) Microsoft Corporation. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * A Node.js BlobQuickQueryStream will internally parse avro data stream for blob query. */ class BlobQuickQueryStream extends stream.Readable { /** * Creates an instance of BlobQuickQueryStream. * * @param source - The current ReadableStream returned from getter * @param options - */ constructor(source, options = {}) { super(); this.avroPaused = true; this.source = source; this.onProgress = options.onProgress; this.onError = options.onError; this.avroReader = new AvroReader(new AvroReadableFromStream(this.source)); this.avroIter = this.avroReader.parseObjects({ abortSignal: options.abortSignal }); } _read() { if (this.avroPaused) { this.readInternal().catch((err) => { this.emit("error", err); }); } } async readInternal() { this.avroPaused = false; let avroNext; do { avroNext = await this.avroIter.next(); if (avroNext.done) { break; } const obj = avroNext.value; const schema = obj.$schema; if (typeof schema !== "string") { throw Error("Missing schema in avro record."); } switch (schema) { case "com.microsoft.azure.storage.queryBlobContents.resultData": { const data = obj.data; if (data instanceof Uint8Array === false) { throw Error("Invalid data in avro result record."); } if (!this.push(Buffer.from(data))) { this.avroPaused = true; } } break; case "com.microsoft.azure.storage.queryBlobContents.progress": { const bytesScanned = obj.bytesScanned; if (typeof bytesScanned !== "number") { throw Error("Invalid bytesScanned in avro progress record."); } if (this.onProgress) { this.onProgress({ loadedBytes: bytesScanned }); } } break; case "com.microsoft.azure.storage.queryBlobContents.end": if (this.onProgress) { const totalBytes = obj.totalBytes; if (typeof totalBytes !== "number") { throw Error("Invalid totalBytes in avro end record."); } this.onProgress({ loadedBytes: totalBytes }); } this.push(null); break; case "com.microsoft.azure.storage.queryBlobContents.error": if (this.onError) { const fatal = obj.fatal; if (typeof fatal !== "boolean") { throw Error("Invalid fatal in avro error record."); } const name = obj.name; if (typeof name !== "string") { throw Error("Invalid name in avro error record."); } const description = obj.description; if (typeof description !== "string") { throw Error("Invalid description in avro error record."); } const position = obj.position; if (typeof position !== "number") { throw Error("Invalid position in avro error record."); } this.onError({ position, name, isFatal: fatal, description, }); } break; default: throw Error(`Unknown schema ${schema} in avro progress record.`); } } while (!avroNext.done && !this.avroPaused); } } // Copyright (c) Microsoft Corporation. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * BlobQueryResponse implements BlobDownloadResponseModel interface, and in Node.js runtime it will * parse avor data returned by blob query. */ class BlobQueryResponse { /** * Creates an instance of BlobQueryResponse. * * @param originalResponse - * @param options - */ constructor(originalResponse, options = {}) { this.originalResponse = originalResponse; this.blobDownloadStream = new BlobQuickQueryStream(this.originalResponse.readableStreamBody, options); } /** * Indicates that the service supports * requests for partial file content. * * @readonly */ get acceptRanges() { return this.originalResponse.acceptRanges; } /** * Returns if it was previously specified * for the file. * * @readonly */ get cacheControl() { return this.originalResponse.cacheControl; } /** * Returns the value that was specified * for the 'x-ms-content-disposition' header and specifies how to process the * response. * * @readonly */ get contentDisposition() { return this.originalResponse.contentDisposition; } /** * Returns the value that was specified * for the Content-Encoding request header. * * @readonly */ get contentEncoding() { return this.originalResponse.contentEncoding; } /** * Returns the value that was specified * for the Content-Language request header. * * @readonly */ get contentLanguage() { return this.originalResponse.contentLanguage; } /** * The current sequence number for a * page blob. This header is not returned for block blobs or append blobs. * * @readonly */ get blobSequenceNumber() { return this.originalResponse.blobSequenceNumber; } /** * The blob's type. Possible values include: * 'BlockBlob', 'PageBlob', 'AppendBlob'. * * @readonly */ get blobType() { return this.originalResponse.blobType; } /** * The number of bytes present in the * response body. * * @readonly */ get contentLength() { return this.originalResponse.contentLength; } /** * If the file has an MD5 hash and the * request is to read the full file, this response header is returned so that * the client can check for message content integrity. If the request is to * read a specified range and the 'x-ms-range-get-content-md5' is set to * true, then the request returns an MD5 hash for the range, as long as the * range size is less than or equal to 4 MB. If neither of these sets of * conditions is true, then no value is returned for the 'Content-MD5' * header. * * @readonly */ get contentMD5() { return this.originalResponse.contentMD5; } /** * Indicates the range of bytes returned if * the client requested a subset of the file by setting the Range request * header. * * @readonly */ get contentRange() { return this.originalResponse.contentRange; } /** * The content type specified for the file. * The default content type is 'application/octet-stream' * * @readonly */ get contentType() { return this.originalResponse.contentType; } /** * Conclusion time of the last attempted * Copy File operation where this file was the destination file. This value * can specify the time of a completed, aborted, or failed copy attempt. * * @readonly */ get copyCompletedOn() { return undefined; } /** * String identifier for the last attempted Copy * File operation where this file was the destination file. * * @readonly */ get copyId() { return this.originalResponse.copyId; } /** * Contains the number of bytes copied and * the total bytes in the source in the last attempted Copy File operation * where this file was the destination file. Can show between 0 and * Content-Length bytes copied. * * @readonly */ get copyProgress() { return this.originalResponse.copyProgress; } /** * URL up to 2KB in length that specifies the * source file used in the last attempted Copy File operation where this file * was the destination file. * * @readonly */ get copySource() { return this.originalResponse.copySource; } /** * State of the copy operation * identified by 'x-ms-copy-id'. Possible values include: 'pending', * 'success', 'aborted', 'failed' * * @readonly */ get copyStatus() { return this.originalResponse.copyStatus; } /** * Only appears when * x-ms-copy-status is failed or pending. Describes cause of fatal or * non-fatal copy operation failure. * * @readonly */ get copyStatusDescription() { return this.originalResponse.copyStatusDescription; } /** * When a blob is leased, * specifies whether the lease is of infinite or fixed duration. Possible * values include: 'infinite', 'fixed'. * * @readonly */ get leaseDuration() { return this.originalResponse.leaseDuration; } /** * Lease state of the blob. Possible * values include: 'available', 'leased', 'expired', 'breaking', 'broken'. * * @readonly */ get leaseState() { return this.originalResponse.leaseState; } /** * The current lease status of the * blob. Possible values include: 'locked', 'unlocked'. * * @readonly */ get leaseStatus() { return this.originalResponse.leaseStatus; } /** * A UTC date/time value generated by the service that * indicates the time at which the response was initiated. * * @readonly */ get date() { return this.originalResponse.date; } /** * The number of committed blocks * present in the blob. This header is returned only for append blobs. * * @readonly */ get blobCommittedBlockCount() { return this.originalResponse.blobCommittedBlockCount; } /** * The ETag contains a value that you can use to * perform operations conditionally, in quotes. * * @readonly */ get etag() { return this.originalResponse.etag; } /** * The error code. * * @readonly */ get errorCode() { return this.originalResponse.errorCode; } /** * The value of this header is set to * true if the file data and application metadata are completely encrypted * using the specified algorithm. Otherwise, the value is set to false (when * the file is unencrypted, or if only parts of the file/application metadata * are encrypted). * * @readonly */ get isServerEncrypted() { return this.originalResponse.isServerEncrypted; } /** * If the blob has a MD5 hash, and if * request contains range header (Range or x-ms-range), this response header * is returned with the value of the whole blob's MD5 value. This value may * or may not be equal to the value returned in Content-MD5 header, with the * latter calculated from the requested range. * * @readonly */ get blobContentMD5() { return this.originalResponse.blobContentMD5; } /** * Returns the date and time the file was last * modified. Any operation that modifies the file or its properties updates * the last modified time. * * @readonly */ get lastModified() { return this.originalResponse.lastModified; } /** * A name-value pair * to associate with a file storage object. * * @readonly */ get metadata() { return this.originalResponse.metadata; } /** * This header uniquely identifies the request * that was made and can be used for troubleshooting the request. * * @readonly */ get requestId() { return this.originalResponse.requestId; } /** * If a client request id header is sent in the request, this header will be present in the * response with the same value. * * @readonly */ get clientRequestId() { return this.originalResponse.clientRequestId; } /** * Indicates the version of the File service used * to execute the request. * * @readonly */ get version() { return this.originalResponse.version; } /** * The SHA-256 hash of the encryption key used to encrypt the blob. This value is only returned * when the blob was encrypted with a customer-provided key. * * @readonly */ get encryptionKeySha256() { return this.originalResponse.encryptionKeySha256; } /** * If the request is to read a specified range and the x-ms-range-get-content-crc64 is set to * true, then the request returns a crc64 for the range, as long as the range size is less than * or equal to 4 MB. If both x-ms-range-get-content-crc64 & x-ms-range-get-content-md5 is * specified in the same request, it will fail with 400(Bad Request) */ get contentCrc64() { return this.originalResponse.contentCrc64; } /** * The response body as a browser Blob. * Always undefined in node.js. * * @readonly */ get blobBody() { return undefined; } /** * The response body as a node.js Readable stream. * Always undefined in the browser. * * It will parse avor data returned by blob query. * * @readonly */ get readableStreamBody() { return coreHttp.isNode ? this.blobDownloadStream : undefined; } /** * The HTTP response. */ get _response() { return this.originalResponse._response; } } // Copyright (c) Microsoft Corporation. /** * Represents the access tier on a blob. * For detailed information about block blob level tiering see {@link https://docs.microsoft.com/azure/storage/blobs/storage-blob-storage-tiers|Hot, cool and archive storage tiers.} */ exports.BlockBlobTier = void 0; (function (BlockBlobTier) { /** * Optimized for storing data that is accessed frequently. */ BlockBlobTier["Hot"] = "Hot"; /** * 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). */ BlockBlobTier["Archive"] = "Archive"; })(exports.BlockBlobTier || (exports.BlockBlobTier = {})); /** * Specifies the page blob tier to set the blob to. This is only applicable to page blobs on premium storage accounts. * Please see {@link https://docs.microsoft.com/azure/storage/storage-premium-storage#scalability-and-performance-targets|here} * for detailed information on the corresponding IOPS and throughput per PageBlobTier. */ exports.PremiumPageBlobTier = void 0; (function (PremiumPageBlobTier) { /** * P4 Tier. */ PremiumPageBlobTier["P4"] = "P4"; /** * P6 Tier. */ PremiumPageBlobTier["P6"] = "P6"; /** * P10 Tier. */ PremiumPageBlobTier["P10"] = "P10"; /** * P15 Tier. */ PremiumPageBlobTier["P15"] = "P15"; /** * P20 Tier. */ PremiumPageBlobTier["P20"] = "P20"; /** * P30 Tier. */ PremiumPageBlobTier["P30"] = "P30"; /** * P40 Tier. */ PremiumPageBlobTier["P40"] = "P40"; /** * P50 Tier. */ PremiumPageBlobTier["P50"] = "P50"; /** * P60 Tier. */ PremiumPageBlobTier["P60"] = "P60"; /** * P70 Tier. */ PremiumPageBlobTier["P70"] = "P70"; /** * P80 Tier. */ PremiumPageBlobTier["P80"] = "P80"; })(exports.PremiumPageBlobTier || (exports.PremiumPageBlobTier = {})); function toAccessTier(tier) { if (tier === undefined) { return undefined; } return tier; // No more check if string is a valid AccessTier, and left this to underlay logic to decide(service). } function ensureCpkIfSpecified(cpk, isHttps) { if (cpk && !isHttps) { throw new RangeError("Customer-provided encryption key must be used over HTTPS."); } if (cpk && !cpk.encryptionAlgorithm) { cpk.encryptionAlgorithm = EncryptionAlgorithmAES25; } } /** * Defines the known cloud audiences for Storage. */ exports.StorageBlobAudience = void 0; (function (StorageBlobAudience) { /** * The OAuth scope to use to retrieve an AAD token for Azure Storage. */ StorageBlobAudience["StorageOAuthScopes"] = "https://storage.azure.com/.default"; /** * The OAuth scope to use to retrieve an AAD token for Azure Disk. */ StorageBlobAudience["DiskComputeOAuthScopes"] = "https://disk.compute.azure.com/.default"; })(exports.StorageBlobAudience || (exports.StorageBlobAudience = {})); // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * Function that converts PageRange and ClearRange to a common Range object. * PageRange and ClearRange have start and end while Range offset and count * this function normalizes to Range. * @param response - Model PageBlob Range response */ function rangeResponseFromModel(response) { const pageRange = (response._response.parsedBody.pageRange || []).map((x) => ({ offset: x.start, count: x.end - x.start, })); const clearRange = (response._response.parsedBody.clearRange || []).map((x) => ({ offset: x.start, count: x.end - x.start, })); return Object.assign(Object.assign({}, response), { pageRange, clearRange, _response: Object.assign(Object.assign({}, response._response), { parsedBody: { pageRange, clearRange, } }) }); } // Copyright (c) Microsoft Corporation. /** * This is the poller returned by {@link BlobClient.beginCopyFromURL}. * This can not be instantiated directly outside of this package. * * @hidden */ class BlobBeginCopyFromUrlPoller extends coreLro.Poller { constructor(options) { const { blobClient, copySource, intervalInMs = 15000, onProgress, resumeFrom, startCopyFromURLOptions, } = options; let state; if (resumeFrom) { state = JSON.parse(resumeFrom).state; } const operation = makeBlobBeginCopyFromURLPollOperation(Object.assign(Object.assign({}, state), { blobClient, copySource, startCopyFromURLOptions })); super(operation); if (typeof onProgress === "function") { this.onProgress(onProgress); } this.intervalInMs = intervalInMs; } delay() { return coreHttp.delay(this.intervalInMs); } } /** * Note: Intentionally using function expression over arrow function expression * so that the function can be invoked with a different context. * This affects what `this` refers to. * @hidden */ const cancel = async function cancel(options = {}) { const state = this.state; const { copyId } = state; if (state.isCompleted) { return makeBlobBeginCopyFromURLPollOperation(state); } if (!copyId) { state.isCancelled = true; return makeBlobBeginCopyFromURLPollOperation(state); } // if abortCopyFromURL throws, it will bubble up to user's poller.cancelOperation call await state.blobClient.abortCopyFromURL(copyId, { abortSignal: options.abortSignal, }); state.isCancelled = true; return makeBlobBeginCopyFromURLPollOperation(state); }; /** * Note: Intentionally using function expression over arrow function expression * so that the function can be invoked with a different context. * This affects what `this` refers to. * @hidden */ const update = async function update(options = {}) { const state = this.state; const { blobClient, copySource, startCopyFromURLOptions } = state; if (!state.isStarted) { state.isStarted = true; const result = await blobClient.startCopyFromURL(copySource, startCopyFromURLOptions); // copyId is needed to abort state.copyId = result.copyId; if (result.copyStatus === "success") { state.result = result; state.isCompleted = true; } } else if (!state.isCompleted) { try { const result = await state.blobClient.getProperties({ abortSignal: options.abortSignal }); const { copyStatus, copyProgress } = result; const prevCopyProgress = state.copyProgress; if (copyProgress) { state.copyProgress = copyProgress; } if (copyStatus === "pending" && copyProgress !== prevCopyProgress && typeof options.fireProgress === "function") { // trigger in setTimeout, or swallow error? options.fireProgress(state); } else if (copyStatus === "success") { state.result = result; state.isCompleted = true; } else if (copyStatus === "failed") { state.error = new Error(`Blob copy failed with reason: "${result.copyStatusDescription || "unknown"}"`); state.isCompleted = true; } } catch (err) { state.error = err; state.isCompleted = true; } } return makeBlobBeginCopyFromURLPollOperation(state); }; /** * Note: Intentionally using function expression over arrow function expression * so that the function can be invoked with a different context. * This affects what `this` refers to. * @hidden */ const toString = function toString() { return JSON.stringify({ state: this.state }, (key, value) => { // remove blobClient from serialized state since a client can't be hydrated from this info. if (key === "blobClient") { return undefined; } return value; }); }; /** * Creates a poll operation given the provided state. * @hidden */ function makeBlobBeginCopyFromURLPollOperation(state) { return { state: Object.assign({}, state), cancel, toString, update, }; } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * Generate a range string. For example: * * "bytes=255-" or "bytes=0-511" * * @param iRange - */ function rangeToString(iRange) { if (iRange.offset < 0) { throw new RangeError(`Range.offset cannot be smaller than 0.`); } if (iRange.count && iRange.count <= 0) { throw new RangeError(`Range.count must be larger than 0. Leave it undefined if you want a range from offset to the end.`); } return iRange.count ? `bytes=${iRange.offset}-${iRange.offset + iRange.count - 1}` : `bytes=${iRange.offset}-`; } // Copyright (c) Microsoft Corporation. /** * States for Batch. */ var BatchStates; (function (BatchStates) { BatchStates[BatchStates["Good"] = 0] = "Good"; BatchStates[BatchStates["Error"] = 1] = "Error"; })(BatchStates || (BatchStates = {})); /** * Batch provides basic parallel execution with concurrency limits. * Will stop execute left operations when one of the executed operation throws an error. * But Batch cannot cancel ongoing operations, you need to cancel them by yourself. */ class Batch { /** * Creates an instance of Batch. * @param concurrency - */ constructor(concurrency = 5) { /** * Number of active operations under execution. */ this.actives = 0; /** * Number of completed operations under execution. */ this.completed = 0; /** * Offset of next operation to be executed. */ this.offset = 0; /** * Operation array to be executed. */ this.operations = []; /** * States of Batch. When an error happens, state will turn into error. * Batch will stop execute left operations. */ this.state = BatchStates.Good; if (concurrency < 1) { throw new RangeError("concurrency must be larger than 0"); } this.concurrency = concurrency; this.emitter = new events.EventEmitter(); } /** * Add a operation into queue. * * @param operation - */ addOperation(operation) { this.operations.push(async () => { try { this.actives++; await operation(); this.actives--; this.completed++; this.parallelExecute(); } catch (error) { this.emitter.emit("error", error); } }); } /** * Start execute operations in the queue. * */ async do() { if (this.operations.length === 0) { return Promise.resolve(); } this.parallelExecute(); return new Promise((resolve, reject) => { this.emitter.on("finish", resolve); this.emitter.on("error", (error) => { this.state = BatchStates.Error; reject(error); }); }); } /** * Get next operation to be executed. Return null when reaching ends. * */ nextOperation() { if (this.offset < this.operations.length) { return this.operations[this.offset++]; } return null; } /** * Start execute operations. One one the most important difference between * this method with do() is that do() wraps as an sync method. * */ parallelExecute() { if (this.state === BatchStates.Error) { return; } if (this.completed >= this.operations.length) { this.emitter.emit("finish"); return; } while (this.actives < this.concurrency) { const operation = this.nextOperation(); if (operation) { operation(); } else { return; } } } } // Copyright (c) Microsoft Corporation. /** * This class generates a readable stream from the data in an array of buffers. */ class BuffersStream extends stream.Readable { /** * Creates an instance of BuffersStream that will emit the data * contained in the array of buffers. * * @param buffers - Array of buffers containing the data * @param byteLength - The total length of data contained in the buffers */ constructor(buffers, byteLength, options) { super(options); this.buffers = buffers; this.byteLength = byteLength; this.byteOffsetInCurrentBuffer = 0; this.bufferIndex = 0; this.pushedBytesLength = 0; // check byteLength is no larger than buffers[] total length let buffersLength = 0; for (const buf of this.buffers) { buffersLength += buf.byteLength; } if (buffersLength < this.byteLength) { throw new Error("Data size shouldn't be larger than the total length of buffers."); } } /** * Internal _read() that will be called when the stream wants to pull more data in. * * @param size - Optional. The size of data to be read */ _read(size) { if (this.pushedBytesLength >= this.byteLength) { this.push(null); } if (!size) { size = this.readableHighWaterMark; } const outBuffers = []; let i = 0; while (i < size && this.pushedBytesLength < this.byteLength) { // The last buffer may be longer than the data it contains. const remainingDataInAllBuffers = this.byteLength - this.pushedBytesLength; const remainingCapacityInThisBuffer = this.buffers[this.bufferIndex].byteLength - this.byteOffsetInCurrentBuffer; const remaining = Math.min(remainingCapacityInThisBuffer, remainingDataInAllBuffers); if (remaining > size - i) { // chunkSize = size - i const end = this.byteOffsetInCurrentBuffer + size - i; outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end)); this.pushedBytesLength += size - i; this.byteOffsetInCurrentBuffer = end; i = size; break; } else { // chunkSize = remaining const end = this.byteOffsetInCurrentBuffer + remaining; outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end)); if (remaining === remainingCapacityInThisBuffer) { // this.buffers[this.bufferIndex] used up, shift to next one this.byteOffsetInCurrentBuffer = 0; this.bufferIndex++; } else { this.byteOffsetInCurrentBuffer = end; } this.pushedBytesLength += remaining; i += remaining; } } if (outBuffers.length > 1) { this.push(Buffer.concat(outBuffers)); } else if (outBuffers.length === 1) { this.push(outBuffers[0]); } } } // Copyright (c) Microsoft Corporation. /** * 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__(181).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. * It will allocate an internal "buffer" of the capacity and fill the data in the input buffers * into the internal "buffer" serially with respect to the total length. * Then by calling PooledBuffer.getReadableStream(), you can get a readable stream * assembled from all the data in the internal "buffer". */ class PooledBuffer { constructor(capacity, buffers, totalLength) { /** * Internal buffers used to keep the data. * Each buffer has a length of the maxBufferLength except last one. */ this.buffers = []; this.capacity = capacity; this._size = 0; // allocate const bufferNum = Math.ceil(capacity / maxBufferLength); for (let i = 0; i < bufferNum; i++) { let len = i === bufferNum - 1 ? capacity % maxBufferLength : maxBufferLength; if (len === 0) { len = maxBufferLength; } this.buffers.push(Buffer.allocUnsafe(len)); } if (buffers) { this.fill(buffers, totalLength); } } /** * The size of the data contained in the pooled buffers. */ get size() { return this._size; } /** * Fill the internal buffers with data in the input buffers serially * with respect to the total length and the total capacity of the internal buffers. * Data copied will be shift out of the input buffers. * * @param buffers - Input buffers containing the data to be filled in the pooled buffer * @param totalLength - Total length of the data to be filled in. * */ fill(buffers, totalLength) { this._size = Math.min(this.capacity, totalLength); let i = 0, j = 0, targetOffset = 0, sourceOffset = 0, totalCopiedNum = 0; while (totalCopiedNum < this._size) { const source = buffers[i]; const target = this.buffers[j]; const copiedNum = source.copy(target, targetOffset, sourceOffset); totalCopiedNum += copiedNum; sourceOffset += copiedNum; targetOffset += copiedNum; if (sourceOffset === source.length) { i++; sourceOffset = 0; } if (targetOffset === target.length) { j++; targetOffset = 0; } } // clear copied from source buffers buffers.splice(0, i); if (buffers.length > 0) { buffers[0] = buffers[0].slice(sourceOffset); } } /** * Get the readable stream assembled from all the data in the internal buffers. * */ getReadableStream() { return new BuffersStream(this.buffers, this.size); } } // Copyright (c) Microsoft Corporation. /** * This class accepts a Node.js Readable stream as input, and keeps reading data * from the stream into the internal buffer structure, until it reaches maxBuffers. * Every available buffer will try to trigger outgoingHandler. * * The internal buffer structure includes an incoming buffer array, and a outgoing * buffer array. The incoming buffer array includes the "empty" buffers can be filled * with new incoming data. The outgoing array includes the filled buffers to be * handled by outgoingHandler. Every above buffer size is defined by parameter bufferSize. * * NUM_OF_ALL_BUFFERS = BUFFERS_IN_INCOMING + BUFFERS_IN_OUTGOING + BUFFERS_UNDER_HANDLING * * NUM_OF_ALL_BUFFERS lesser than or equal to maxBuffers * * PERFORMANCE IMPROVEMENT TIPS: * 1. Input stream highWaterMark is better to set a same value with bufferSize * parameter, which will avoid Buffer.concat() operations. * 2. concurrency should set a smaller value than maxBuffers, which is helpful to * reduce the possibility when a outgoing handler waits for the stream data. * in this situation, outgoing handlers are blocked. * Outgoing queue shouldn't be empty. */ class BufferScheduler { /** * Creates an instance of BufferScheduler. * * @param readable - A Node.js Readable stream * @param bufferSize - Buffer size of every maintained buffer * @param maxBuffers - How many buffers can be allocated * @param outgoingHandler - An async function scheduled to be * triggered when a buffer fully filled * with stream data * @param concurrency - Concurrency of executing outgoingHandlers (>0) * @param encoding - [Optional] Encoding of Readable stream when it's a string stream */ constructor(readable, bufferSize, maxBuffers, outgoingHandler, concurrency, encoding) { /** * An internal event emitter. */ this.emitter = new events.EventEmitter(); /** * An internal offset marker to track data offset in bytes of next outgoingHandler. */ this.offset = 0; /** * An internal marker to track whether stream is end. */ this.isStreamEnd = false; /** * An internal marker to track whether stream or outgoingHandler returns error. */ this.isError = false; /** * How many handlers are executing. */ this.executingOutgoingHandlers = 0; /** * How many buffers have been allocated. */ this.numBuffers = 0; /** * Because this class doesn't know how much data every time stream pops, which * is defined by highWaterMarker of the stream. So BufferScheduler will cache * data received from the stream, when data in unresolvedDataArray exceeds the * blockSize defined, it will try to concat a blockSize of buffer, fill into available * buffers from incoming and push to outgoing array. */ this.unresolvedDataArray = []; /** * How much data consisted in unresolvedDataArray. */ this.unresolvedLength = 0; /** * The array includes all the available buffers can be used to fill data from stream. */ this.incoming = []; /** * The array (queue) includes all the buffers filled from stream data. */ this.outgoing = []; if (bufferSize <= 0) { throw new RangeError(`bufferSize must be larger than 0, current is ${bufferSize}`); } if (maxBuffers <= 0) { throw new RangeError(`maxBuffers must be larger than 0, current is ${maxBuffers}`); } if (concurrency <= 0) { throw new RangeError(`concurrency must be larger than 0, current is ${concurrency}`); } this.bufferSize = bufferSize; this.maxBuffers = maxBuffers; this.readable = readable; this.outgoingHandler = outgoingHandler; this.concurrency = concurrency; this.encoding = encoding; } /** * Start the scheduler, will return error when stream of any of the outgoingHandlers * returns error. * */ async do() { return new Promise((resolve, reject) => { this.readable.on("data", (data) => { data = typeof data === "string" ? Buffer.from(data, this.encoding) : data; this.appendUnresolvedData(data); if (!this.resolveData()) { this.readable.pause(); } }); this.readable.on("error", (err) => { this.emitter.emit("error", err); }); this.readable.on("end", () => { this.isStreamEnd = true; this.emitter.emit("checkEnd"); }); this.emitter.on("error", (err) => { this.isError = true; this.readable.pause(); reject(err); }); this.emitter.on("checkEnd", () => { if (this.outgoing.length > 0) { this.triggerOutgoingHandlers(); return; } if (this.isStreamEnd && this.executingOutgoingHandlers === 0) { if (this.unresolvedLength > 0 && this.unresolvedLength < this.bufferSize) { const buffer = this.shiftBufferFromUnresolvedDataArray(); this.outgoingHandler(() => buffer.getReadableStream(), buffer.size, this.offset) .then(resolve) .catch(reject); } else if (this.unresolvedLength >= this.bufferSize) { return; } else { resolve(); } } }); }); } /** * Insert a new data into unresolved array. * * @param data - */ appendUnresolvedData(data) { this.unresolvedDataArray.push(data); this.unresolvedLength += data.length; } /** * Try to shift a buffer with size in blockSize. The buffer returned may be less * than blockSize when data in unresolvedDataArray is less than bufferSize. * */ shiftBufferFromUnresolvedDataArray(buffer) { if (!buffer) { buffer = new PooledBuffer(this.bufferSize, this.unresolvedDataArray, this.unresolvedLength); } else { buffer.fill(this.unresolvedDataArray, this.unresolvedLength); } this.unresolvedLength -= buffer.size; return buffer; } /** * Resolve data in unresolvedDataArray. For every buffer with size in blockSize * shifted, it will try to get (or allocate a buffer) from incoming, and fill it, * then push it into outgoing to be handled by outgoing handler. * * Return false when available buffers in incoming are not enough, else true. * * @returns Return false when buffers in incoming are not enough, else true. */ resolveData() { while (this.unresolvedLength >= this.bufferSize) { let buffer; if (this.incoming.length > 0) { buffer = this.incoming.shift(); this.shiftBufferFromUnresolvedDataArray(buffer); } else { if (this.numBuffers < this.maxBuffers) { buffer = this.shiftBufferFromUnresolvedDataArray(); this.numBuffers++; } else { // No available buffer, wait for buffer returned return false; } } this.outgoing.push(buffer); this.triggerOutgoingHandlers(); } return true; } /** * Try to trigger a outgoing handler for every buffer in outgoing. Stop when * concurrency reaches. */ async triggerOutgoingHandlers() { let buffer; do { if (this.executingOutgoingHandlers >= this.concurrency) { return; } buffer = this.outgoing.shift(); if (buffer) { this.triggerOutgoingHandler(buffer); } } while (buffer); } /** * Trigger a outgoing handler for a buffer shifted from outgoing. * * @param buffer - */ async triggerOutgoingHandler(buffer) { const bufferLength = buffer.size; this.executingOutgoingHandlers++; this.offset += bufferLength; try { await this.outgoingHandler(() => buffer.getReadableStream(), bufferLength, this.offset - bufferLength); } catch (err) { this.emitter.emit("error", err); return; } this.executingOutgoingHandlers--; this.reuseBuffer(buffer); this.emitter.emit("checkEnd"); } /** * Return buffer used by outgoing handler into incoming. * * @param buffer - */ reuseBuffer(buffer) { this.incoming.push(buffer); if (!this.isError && this.resolveData() && !this.isStreamEnd) { this.readable.resume(); } } } // Copyright (c) Microsoft Corporation. /** * Reads a readable stream into buffer. Fill the buffer from offset to end. * * @param stream - A Node.js Readable stream * @param buffer - Buffer to be filled, length must greater than or equal to offset * @param offset - From which position in the buffer to be filled, inclusive * @param end - To which position in the buffer to be filled, exclusive * @param encoding - Encoding of the Readable stream */ 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; } let chunk = stream.read(); if (!chunk) { return; } if (typeof chunk === "string") { chunk = Buffer.from(chunk, encoding); } // How much data needed in this chunk const chunkLength = pos + chunk.length > count ? count - pos : chunk.length; buffer.fill(chunk.slice(0, chunkLength), offset + pos, offset + pos + chunkLength); 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", (msg) => { clearTimeout(timeout); reject(msg); }); }); } /** * Reads a readable stream into buffer entirely. * * @param stream - A Node.js Readable stream * @param buffer - Buffer to be filled, length must greater than or equal to offset * @param encoding - Encoding of the Readable stream * @returns with the count of bytes read. * @throws `RangeError` If buffer size is not big enough. */ async function streamToBuffer2(stream, buffer, encoding) { let pos = 0; // Position in stream const bufferSize = buffer.length; return new Promise((resolve, reject) => { stream.on("readable", () => { let chunk = stream.read(); if (!chunk) { return; } if (typeof chunk === "string") { chunk = Buffer.from(chunk, encoding); } if (pos + chunk.length > bufferSize) { reject(new Error(`Stream exceeds buffer size. Buffer size: ${bufferSize}`)); return; } buffer.fill(chunk, pos, pos + chunk.length); pos += chunk.length; }); stream.on("end", () => { resolve(pos); }); stream.on("error", reject); }); } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * Writes the content of a readstream to a local file. Returns a Promise which is completed after the file handle is closed. * * @param rs - The read stream. * @param file - Destination file path. */ async function readStreamToLocalFile(rs, file) { return new Promise((resolve, reject) => { const ws = fs__namespace.createWriteStream(file); rs.on("error", (err) => { reject(err); }); ws.on("error", (err) => { reject(err); }); ws.on("close", resolve); rs.pipe(ws); }); } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * Promisified version of fs.stat(). */ const fsStat = util__namespace.promisify(fs__namespace.stat); const fsCreateReadStream = fs__namespace.createReadStream; /** * A BlobClient represents a URL to an Azure Storage blob; the blob may be a block blob, * append blob, or page blob. */ class BlobClient extends StorageClient { constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, // Legacy, no fix for eslint error without breaking. Disable it for this interface. /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ options) { options = options || {}; let pipeline; let url; if (isPipelineLike(credentialOrPipelineOrContainerName)) { // (url: string, pipeline: Pipeline) url = urlOrConnectionString; pipeline = credentialOrPipelineOrContainerName; } else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || credentialOrPipelineOrContainerName instanceof AnonymousCredential || coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) url = urlOrConnectionString; options = blobNameOrOptions; pipeline = newPipeline(credentialOrPipelineOrContainerName, options); } else if (!credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName !== "string") { // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) // The second parameter is undefined. Use anonymous credential. url = urlOrConnectionString; pipeline = newPipeline(new AnonymousCredential(), options); } else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string" && blobNameOrOptions && typeof blobNameOrOptions === "string") { // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) const containerName = credentialOrPipelineOrContainerName; const blobName = blobNameOrOptions; const extractedCreds = extractConnectionStringParts(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { if (coreHttp.isNode) { const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); if (!options.proxyOptions) { options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); } pipeline = newPipeline(sharedKeyCredential, options); } else { throw new Error("Account connection string is only supported in Node.js environment"); } } else if (extractedCreds.kind === "SASConnString") { url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + "?" + extractedCreds.accountSas; pipeline = newPipeline(new AnonymousCredential(), options); } else { throw new Error("Connection string must be either an Account connection string or a SAS connection string"); } } else { throw new Error("Expecting non-empty strings for containerName and blobName parameters"); } super(url, pipeline); ({ blobName: this._name, containerName: this._containerName } = this.getBlobAndContainerNamesFromUrl()); this.blobContext = new Blob$1(this.storageClientContext); this._snapshot = getURLParameter(this.url, URLConstants.Parameters.SNAPSHOT); this._versionId = getURLParameter(this.url, URLConstants.Parameters.VERSIONID); } /** * The name of the blob. */ get name() { return this._name; } /** * The name of the storage container the blob is associated with. */ get containerName() { return this._containerName; } /** * Creates a new BlobClient object identical to the source but with the specified snapshot timestamp. * Provide "" will remove the snapshot and return a Client to the base blob. * * @param snapshot - The snapshot timestamp. * @returns A new BlobClient object identical to the source but with the specified snapshot timestamp */ withSnapshot(snapshot) { return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); } /** * Creates a new BlobClient object pointing to a version of this blob. * Provide "" will remove the versionId and return a Client to the base blob. * * @param versionId - The versionId. * @returns A new BlobClient object pointing to the version of this blob. */ withVersion(versionId) { return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.VERSIONID, versionId.length === 0 ? undefined : versionId), this.pipeline); } /** * Creates a AppendBlobClient object. * */ getAppendBlobClient() { return new AppendBlobClient(this.url, this.pipeline); } /** * Creates a BlockBlobClient object. * */ getBlockBlobClient() { return new BlockBlobClient(this.url, this.pipeline); } /** * Creates a PageBlobClient object. * */ getPageBlobClient() { return new PageBlobClient(this.url, this.pipeline); } /** * Reads or downloads a blob from the system, including its metadata and properties. * You can also call Get Blob to read a snapshot. * * * In Node.js, data returns in a Readable stream readableStreamBody * * In browsers, data returns in a promise blobBody * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob * * @param offset - From which position of the blob to download, greater than or equal to 0 * @param count - How much data to be downloaded, greater than 0. Will download to the end when undefined * @param options - Optional options to Blob Download operation. * * * Example usage (Node.js): * * ```js * // Download and convert a blob to a string * const downloadBlockBlobResponse = await blobClient.download(); * const downloaded = await streamToBuffer(downloadBlockBlobResponse.readableStreamBody); * console.log("Downloaded blob content:", downloaded.toString()); * * async function streamToBuffer(readableStream) { * return new Promise((resolve, reject) => { * const chunks = []; * readableStream.on("data", (data) => { * chunks.push(data instanceof Buffer ? data : Buffer.from(data)); * }); * readableStream.on("end", () => { * resolve(Buffer.concat(chunks)); * }); * readableStream.on("error", reject); * }); * } * ``` * * Example usage (browser): * * ```js * // Download and convert a blob to a string * const downloadBlockBlobResponse = await blobClient.download(); * const downloaded = await blobToString(await downloadBlockBlobResponse.blobBody); * console.log( * "Downloaded blob content", * downloaded * ); * * async function blobToString(blob: Blob): Promise { * const fileReader = new FileReader(); * return new Promise((resolve, reject) => { * fileReader.onloadend = (ev: any) => { * resolve(ev.target!.result); * }; * fileReader.onerror = reject; * fileReader.readAsText(blob); * }); * } * ``` */ async download(offset = 0, count, options = {}) { var _a; options.conditions = options.conditions || {}; options.conditions = options.conditions || {}; ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); const { span, updatedOptions } = createSpan("BlobClient-download", options); try { const res = await this.blobContext.download(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), requestOptions: { onDownloadProgress: coreHttp.isNode ? undefined : options.onProgress, // for Node.js, progress is reported by RetriableReadableStream }, range: offset === 0 && !count ? undefined : rangeToString({ offset, count }), rangeGetContentMD5: options.rangeGetContentMD5, rangeGetContentCRC64: options.rangeGetContentCrc64, snapshot: options.snapshot, cpkInfo: options.customerProvidedKey }, convertTracingToRequestOptionsBase(updatedOptions))); const wrappedRes = Object.assign(Object.assign({}, res), { _response: res._response, objectReplicationDestinationPolicyId: res.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res.objectReplicationRules) }); // Return browser response immediately if (!coreHttp.isNode) { return wrappedRes; } // We support retrying when download stream unexpected ends in Node.js runtime // Following code shouldn't be bundled into browser build, however some // bundlers may try to bundle following code and "FileReadResponse.ts". // In this case, "FileDownloadResponse.browser.ts" will be used as a shim of "FileDownloadResponse.ts" // The config is in package.json "browser" field if (options.maxRetryRequests === undefined || options.maxRetryRequests < 0) { // TODO: Default value or make it a required parameter? options.maxRetryRequests = DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS; } if (res.contentLength === undefined) { throw new RangeError(`File download response doesn't contain valid content length header`); } if (!res.etag) { throw new RangeError(`File download response doesn't contain valid etag header`); } return new BlobDownloadResponse(wrappedRes, async (start) => { var _a; const updatedDownloadOptions = { leaseAccessConditions: options.conditions, modifiedAccessConditions: { ifMatch: options.conditions.ifMatch || res.etag, ifModifiedSince: options.conditions.ifModifiedSince, ifNoneMatch: options.conditions.ifNoneMatch, ifUnmodifiedSince: options.conditions.ifUnmodifiedSince, ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions, }, range: rangeToString({ count: offset + res.contentLength - start, offset: start, }), rangeGetContentMD5: options.rangeGetContentMD5, rangeGetContentCRC64: options.rangeGetContentCrc64, snapshot: options.snapshot, cpkInfo: options.customerProvidedKey, }; // Debug purpose only // console.log( // `Read from internal stream, range: ${ // updatedOptions.range // }, options: ${JSON.stringify(updatedOptions)}` // ); return (await this.blobContext.download(Object.assign({ abortSignal: options.abortSignal }, updatedDownloadOptions))).readableStreamBody; }, offset, res.contentLength, { maxRetryRequests: options.maxRetryRequests, onProgress: options.onProgress, }); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Returns true if the Azure blob resource represented by this client exists; false otherwise. * * NOTE: use this function with care since an existing blob might be deleted by other clients or * applications. Vice versa new blobs might be added by other clients or applications after this * function completes. * * @param options - options to Exists operation. */ async exists(options = {}) { const { span, updatedOptions } = createSpan("BlobClient-exists", options); try { ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); await this.getProperties({ abortSignal: options.abortSignal, customerProvidedKey: options.customerProvidedKey, conditions: options.conditions, tracingOptions: updatedOptions.tracingOptions, }); return true; } catch (e) { if (e.statusCode === 404) { // Expected exception when checking blob existence return false; } else if (e.statusCode === 409 && (e.details.errorCode === BlobUsesCustomerSpecifiedEncryptionMsg || e.details.errorCode === BlobDoesNotUseCustomerSpecifiedEncryption)) { // Expected exception when checking blob existence return true; } span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Returns all user-defined metadata, standard HTTP properties, and system properties * for the blob. It does not return the content of the blob. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-properties * * WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if * they originally contained uppercase characters. This differs from the metadata keys returned by * the methods of {@link ContainerClient} that list blobs using the `includeMetadata` option, which * will retain their original casing. * * @param options - Optional options to Get Properties operation. */ async getProperties(options = {}) { var _a; const { span, updatedOptions } = createSpan("BlobClient-getProperties", options); try { options.conditions = options.conditions || {}; ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); const res = await this.blobContext.getProperties(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey }, convertTracingToRequestOptionsBase(updatedOptions))); return Object.assign(Object.assign({}, res), { _response: res._response, objectReplicationDestinationPolicyId: res.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res.objectReplicationRules) }); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Marks the specified blob or snapshot for deletion. The blob is later deleted * during garbage collection. Note that in order to delete a blob, you must delete * all of its snapshots. You can delete both at the same time with the Delete * Blob operation. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob * * @param options - Optional options to Blob Delete operation. */ async delete(options = {}) { var _a; const { span, updatedOptions } = createSpan("BlobClient-delete", options); options.conditions = options.conditions || {}; try { return await this.blobContext.delete(Object.assign({ abortSignal: options.abortSignal, deleteSnapshots: options.deleteSnapshots, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Marks the specified blob or snapshot for deletion if it exists. The blob is later deleted * during garbage collection. Note that in order to delete a blob, you must delete * all of its snapshots. You can delete both at the same time with the Delete * Blob operation. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob * * @param options - Optional options to Blob Delete operation. */ async deleteIfExists(options = {}) { var _a, _b; const { span, updatedOptions } = createSpan("BlobClient-deleteIfExists", options); try { const res = await this.delete(updatedOptions); return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); } catch (e) { if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobNotFound") { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: "Expected exception when deleting a blob or snapshot only if it exists.", }); return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); } span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Restores the contents and metadata of soft deleted blob and any associated * soft deleted snapshots. Undelete Blob is supported only on version 2017-07-29 * or later. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/undelete-blob * * @param options - Optional options to Blob Undelete operation. */ async undelete(options = {}) { const { span, updatedOptions } = createSpan("BlobClient-undelete", options); try { return await this.blobContext.undelete(Object.assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Sets system properties on the blob. * * If no value provided, or no value provided for the specified blob HTTP headers, * these blob HTTP headers without a value will be cleared. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties * * @param blobHTTPHeaders - If no value provided, or no value provided for * the specified blob HTTP headers, these blob HTTP * headers without a value will be cleared. * A common header to set is `blobContentType` * enabling the browser to provide functionality * based on file type. * @param options - Optional options to Blob Set HTTP Headers operation. */ async setHTTPHeaders(blobHTTPHeaders, options = {}) { var _a; const { span, updatedOptions } = createSpan("BlobClient-setHTTPHeaders", options); options.conditions = options.conditions || {}; try { ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return await this.blobContext.setHttpHeaders(Object.assign({ abortSignal: options.abortSignal, blobHttpHeaders: blobHTTPHeaders, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Sets user-defined metadata for the specified blob as one or more name-value pairs. * * If no option provided, or no metadata defined in the parameter, the blob * metadata will be removed. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-metadata * * @param metadata - Replace existing metadata with this value. * If no value provided the existing metadata will be removed. * @param options - Optional options to Set Metadata operation. */ async setMetadata(metadata, options = {}) { var _a; const { span, updatedOptions } = createSpan("BlobClient-setMetadata", options); options.conditions = options.conditions || {}; try { ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return await this.blobContext.setMetadata(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Sets tags on the underlying blob. * A blob can have up to 10 tags. Tag keys must be between 1 and 128 characters. Tag values must be between 0 and 256 characters. * Valid tag key and value characters include lower and upper case letters, digits (0-9), * space (' '), plus ('+'), minus ('-'), period ('.'), foward slash ('/'), colon (':'), equals ('='), and underscore ('_'). * * @param tags - * @param options - */ async setTags(tags, options = {}) { var _a; const { span, updatedOptions } = createSpan("BlobClient-setTags", options); try { return await this.blobContext.setTags(Object.assign(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)), { tags: toBlobTags(tags) })); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Gets the tags associated with the underlying blob. * * @param options - */ async getTags(options = {}) { var _a; const { span, updatedOptions } = createSpan("BlobClient-getTags", options); try { const response = await this.blobContext.getTags(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); const wrappedResponse = Object.assign(Object.assign({}, response), { _response: response._response, tags: toTags({ blobTagSet: response.blobTagSet }) || {} }); return wrappedResponse; } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Get a {@link BlobLeaseClient} that manages leases on the blob. * * @param proposeLeaseId - Initial proposed lease Id. * @returns A new BlobLeaseClient object for managing leases on the blob. */ getBlobLeaseClient(proposeLeaseId) { return new BlobLeaseClient(this, proposeLeaseId); } /** * Creates a read-only snapshot of a blob. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/snapshot-blob * * @param options - Optional options to the Blob Create Snapshot operation. */ async createSnapshot(options = {}) { var _a; const { span, updatedOptions } = createSpan("BlobClient-createSnapshot", options); options.conditions = options.conditions || {}; try { ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return await this.blobContext.createSnapshot(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Asynchronously copies a blob to a destination within the storage account. * This method returns a long running operation poller that allows you to wait * indefinitely until the copy is completed. * You can also cancel a copy before it is completed by calling `cancelOperation` on the poller. * Note that the onProgress callback will not be invoked if the operation completes in the first * request, and attempting to cancel a completed copy will result in an error being thrown. * * In version 2012-02-12 and later, the source for a Copy Blob operation can be * a committed blob in any Azure storage account. * Beginning with version 2015-02-21, the source for a Copy Blob operation can be * an Azure file in any Azure storage account. * Only storage accounts created on or after June 7th, 2012 allow the Copy Blob * operation to copy from another storage account. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob * * Example using automatic polling: * * ```js * const copyPoller = await blobClient.beginCopyFromURL('url'); * const result = await copyPoller.pollUntilDone(); * ``` * * Example using manual polling: * * ```js * const copyPoller = await blobClient.beginCopyFromURL('url'); * while (!poller.isDone()) { * await poller.poll(); * } * const result = copyPoller.getResult(); * ``` * * Example using progress updates: * * ```js * const copyPoller = await blobClient.beginCopyFromURL('url', { * onProgress(state) { * console.log(`Progress: ${state.copyProgress}`); * } * }); * const result = await copyPoller.pollUntilDone(); * ``` * * Example using a changing polling interval (default 15 seconds): * * ```js * const copyPoller = await blobClient.beginCopyFromURL('url', { * intervalInMs: 1000 // poll blob every 1 second for copy progress * }); * const result = await copyPoller.pollUntilDone(); * ``` * * Example using copy cancellation: * * ```js * const copyPoller = await blobClient.beginCopyFromURL('url'); * // cancel operation after starting it. * try { * await copyPoller.cancelOperation(); * // calls to get the result now throw PollerCancelledError * await copyPoller.getResult(); * } catch (err) { * if (err.name === 'PollerCancelledError') { * console.log('The copy was cancelled.'); * } * } * ``` * * @param copySource - url to the source Azure Blob/File. * @param options - Optional options to the Blob Start Copy From URL operation. */ async beginCopyFromURL(copySource, options = {}) { const client = { abortCopyFromURL: (...args) => this.abortCopyFromURL(...args), getProperties: (...args) => this.getProperties(...args), startCopyFromURL: (...args) => this.startCopyFromURL(...args), }; const poller = new BlobBeginCopyFromUrlPoller({ blobClient: client, copySource, intervalInMs: options.intervalInMs, onProgress: options.onProgress, resumeFrom: options.resumeFrom, startCopyFromURLOptions: options, }); // Trigger the startCopyFromURL call by calling poll. // Any errors from this method should be surfaced to the user. await poller.poll(); return poller; } /** * Aborts a pending asynchronous Copy Blob operation, and leaves a destination blob with zero * length and full metadata. Version 2012-02-12 and newer. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/abort-copy-blob * * @param copyId - Id of the Copy From URL operation. * @param options - Optional options to the Blob Abort Copy From URL operation. */ async abortCopyFromURL(copyId, options = {}) { const { span, updatedOptions } = createSpan("BlobClient-abortCopyFromURL", options); try { return await this.blobContext.abortCopyFromURL(copyId, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * The synchronous Copy From URL operation copies a blob or an internet resource to a new blob. It will not * return a response until the copy is complete. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob-from-url * * @param copySource - The source URL to copy from, Shared Access Signature(SAS) maybe needed for authentication * @param options - */ async syncCopyFromURL(copySource, options = {}) { var _a, _b, _c; const { span, updatedOptions } = createSpan("BlobClient-syncCopyFromURL", options); options.conditions = options.conditions || {}; options.sourceConditions = options.sourceConditions || {}; try { return await this.blobContext.copyFromURL(copySource, Object.assign({ abortSignal: options.abortSignal, metadata: options.metadata, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: { sourceIfMatch: options.sourceConditions.ifMatch, sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince, }, 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({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Sets the tier on a blob. The operation is allowed on a page blob in a premium * storage account and on a block blob in a blob storage account (locally redundant * storage only). A premium page blob's tier determines the allowed size, IOPS, * and bandwidth of the blob. A block blob's tier determines Hot/Cool/Archive * storage type. This operation does not update the blob's ETag. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-tier * * @param tier - The tier to be set on the blob. Valid values are Hot, Cool, or Archive. * @param options - Optional options to the Blob Set Tier operation. */ async setAccessTier(tier, options = {}) { var _a; const { span, updatedOptions } = createSpan("BlobClient-setAccessTier", options); try { return await this.blobContext.setTier(toAccessTier(tier), Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), rehydratePriority: options.rehydratePriority }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } async downloadToBuffer(param1, param2, param3, param4 = {}) { let buffer; let offset = 0; let count = 0; let options = param4; if (param1 instanceof Buffer) { buffer = param1; offset = param2 || 0; count = typeof param3 === "number" ? param3 : 0; } else { offset = typeof param1 === "number" ? param1 : 0; count = typeof param2 === "number" ? param2 : 0; options = param3 || {}; } const { span, updatedOptions } = createSpan("BlobClient-downloadToBuffer", options); try { if (!options.blockSize) { options.blockSize = 0; } if (options.blockSize < 0) { throw new RangeError("blockSize option must be >= 0"); } if (options.blockSize === 0) { options.blockSize = DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES; } if (offset < 0) { throw new RangeError("offset option must be >= 0"); } if (count && count <= 0) { throw new RangeError("count option must be greater than 0"); } if (!options.conditions) { options.conditions = {}; } // Customer doesn't specify length, get it if (!count) { const response = await this.getProperties(Object.assign(Object.assign({}, options), { tracingOptions: Object.assign(Object.assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) })); count = response.contentLength - offset; if (count < 0) { throw new RangeError(`offset ${offset} shouldn't be larger than blob size ${response.contentLength}`); } } // Allocate the buffer of size = count if the buffer is not provided if (!buffer) { try { buffer = Buffer.alloc(count); } catch (error) { throw new Error(`Unable to allocate the buffer of size: ${count}(in bytes). Please try passing your own buffer to the "downloadToBuffer" method or try using other methods like "download" or "downloadToFile".\t ${error.message}`); } } if (buffer.length < count) { throw new RangeError(`The buffer's size should be equal to or larger than the request count of bytes: ${count}`); } let transferProgress = 0; const batch = new Batch(options.concurrency); for (let off = offset; off < offset + count; off = off + options.blockSize) { batch.addOperation(async () => { // Exclusive chunk end position let chunkEnd = offset + count; if (off + options.blockSize < chunkEnd) { chunkEnd = off + options.blockSize; } const response = await this.download(off, chunkEnd - off, { abortSignal: options.abortSignal, conditions: options.conditions, maxRetryRequests: options.maxRetryRequestsPerBlock, customerProvidedKey: options.customerProvidedKey, tracingOptions: Object.assign(Object.assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)), }); const stream = response.readableStreamBody; await streamToBuffer(stream, buffer, off - offset, chunkEnd - offset); // Update progress after block is downloaded, in case of block trying // Could provide finer grained progress updating inside HTTP requests, // only if convenience layer download try is enabled transferProgress += chunkEnd - off; if (options.onProgress) { options.onProgress({ loadedBytes: transferProgress }); } }); } await batch.do(); return buffer; } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * Downloads an Azure Blob to a local file. * Fails if the the given file path already exits. * Offset and count are optional, pass 0 and undefined respectively to download the entire blob. * * @param filePath - * @param offset - From which position of the block blob to download. * @param count - How much data to be downloaded. Will download to the end when passing undefined. * @param options - Options to Blob download options. * @returns The response data for blob download operation, * but with readableStreamBody set to undefined since its * content is already read and written into a local file * at the specified path. */ async downloadToFile(filePath, offset = 0, count, options = {}) { const { span, updatedOptions } = createSpan("BlobClient-downloadToFile", options); try { const response = await this.download(offset, count, Object.assign(Object.assign({}, options), { tracingOptions: Object.assign(Object.assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) })); if (response.readableStreamBody) { await readStreamToLocalFile(response.readableStreamBody, filePath); } // The stream is no longer accessible so setting it to undefined. response.blobDownloadStream = undefined; return response; } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } getBlobAndContainerNamesFromUrl() { let containerName; let blobName; try { // URL may look like the following // "https://myaccount.blob.core.windows.net/mycontainer/blob?sasString"; // "https://myaccount.blob.core.windows.net/mycontainer/blob"; // "https://myaccount.blob.core.windows.net/mycontainer/blob/a.txt?sasString"; // "https://myaccount.blob.core.windows.net/mycontainer/blob/a.txt"; // IPv4/IPv6 address hosts, Endpoints - `http://127.0.0.1:10000/devstoreaccount1/containername/blob` // http://localhost:10001/devstoreaccount1/containername/blob const parsedUrl = coreHttp.URLBuilder.parse(this.url); if (parsedUrl.getHost().split(".")[1] === "blob") { // "https://myaccount.blob.core.windows.net/containername/blob". // .getPath() -> /containername/blob const pathComponents = parsedUrl.getPath().match("/([^/]*)(/(.*))?"); containerName = pathComponents[1]; blobName = pathComponents[3]; } else if (isIpEndpointStyle(parsedUrl)) { // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/containername/blob // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/containername/blob // .getPath() -> /devstoreaccount1/containername/blob const pathComponents = parsedUrl.getPath().match("/([^/]*)/([^/]*)(/(.*))?"); containerName = pathComponents[2]; blobName = pathComponents[4]; } else { // "https://customdomain.com/containername/blob". // .getPath() -> /containername/blob const pathComponents = parsedUrl.getPath().match("/([^/]*)(/(.*))?"); containerName = pathComponents[1]; blobName = pathComponents[3]; } // decode the encoded blobName, containerName - to get all the special characters that might be present in them containerName = decodeURIComponent(containerName); blobName = decodeURIComponent(blobName); // Azure Storage Server will replace "\" with "/" in the blob names // doing the same in the SDK side so that the user doesn't have to replace "\" instances in the blobName blobName = blobName.replace(/\\/g, "/"); if (!containerName) { throw new Error("Provided containerName is invalid."); } return { blobName, containerName }; } catch (error) { throw new Error("Unable to extract blobName and containerName with provided information."); } } /** * Asynchronously copies a blob to a destination within the storage account. * In version 2012-02-12 and later, the source for a Copy Blob operation can be * a committed blob in any Azure storage account. * Beginning with version 2015-02-21, the source for a Copy Blob operation can be * an Azure file in any Azure storage account. * Only storage accounts created on or after June 7th, 2012 allow the Copy Blob * operation to copy from another storage account. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob * * @param copySource - url to the source Azure Blob/File. * @param options - Optional options to the Blob Start Copy From URL operation. */ async startCopyFromURL(copySource, options = {}) { var _a, _b, _c; const { span, updatedOptions } = createSpan("BlobClient-startCopyFromURL", options); options.conditions = options.conditions || {}; options.sourceConditions = options.sourceConditions || {}; try { return await this.blobContext.startCopyFromURL(copySource, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: { sourceIfMatch: options.sourceConditions.ifMatch, sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince, sourceIfTags: options.sourceConditions.tagConditions, }, 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, rehydratePriority: options.rehydratePriority, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags), sealBlob: options.sealBlob }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Only available for BlobClient constructed with a shared key credential. * * Generates a Blob Service Shared Access Signature (SAS) URI based on the client properties * and parameters passed in. The SAS is signed by the shared key credential of the client. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas * * @param options - Optional parameters. * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ generateSasUrl(options) { return new Promise((resolve) => { if (!(this.credential instanceof StorageSharedKeyCredential)) { throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); } const sas = generateBlobSASQueryParameters(Object.assign({ containerName: this._containerName, blobName: this._name, snapshotTime: this._snapshot, versionId: this._versionId }, options), this.credential).toString(); resolve(appendToURLQuery(this.url, sas)); }); } /** * Delete the immutablility policy on the blob. * * @param options - Optional options to delete immutability policy on the blob. */ async deleteImmutabilityPolicy(options) { const { span, updatedOptions } = createSpan("BlobClient-deleteImmutabilityPolicy", options); try { return await this.blobContext.deleteImmutabilityPolicy(Object.assign({ abortSignal: options === null || options === void 0 ? void 0 : options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Set immutablility policy on the blob. * * @param options - Optional options to set immutability policy on the blob. */ async setImmutabilityPolicy(immutabilityPolicy, options) { const { span, updatedOptions } = createSpan("BlobClient-setImmutabilityPolicy", options); try { return await this.blobContext.setImmutabilityPolicy(Object.assign({ abortSignal: options === null || options === void 0 ? void 0 : options.abortSignal, immutabilityPolicyExpiry: immutabilityPolicy.expiriesOn, immutabilityPolicyMode: immutabilityPolicy.policyMode, modifiedAccessConditions: options === null || options === void 0 ? void 0 : options.modifiedAccessCondition }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Set legal hold on the blob. * * @param options - Optional options to set legal hold on the blob. */ async setLegalHold(legalHoldEnabled, options) { const { span, updatedOptions } = createSpan("BlobClient-setLegalHold", options); try { return await this.blobContext.setLegalHold(legalHoldEnabled, Object.assign({ abortSignal: options === null || options === void 0 ? void 0 : options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } } /** * AppendBlobClient defines a set of operations applicable to append blobs. */ class AppendBlobClient extends BlobClient { constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, // Legacy, no fix for eslint error without breaking. Disable it for this interface. /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ options) { // In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead. // super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options); let pipeline; let url; options = options || {}; if (isPipelineLike(credentialOrPipelineOrContainerName)) { // (url: string, pipeline: Pipeline) url = urlOrConnectionString; pipeline = credentialOrPipelineOrContainerName; } else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || credentialOrPipelineOrContainerName instanceof AnonymousCredential || coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) url = urlOrConnectionString; url = urlOrConnectionString; options = blobNameOrOptions; pipeline = newPipeline(credentialOrPipelineOrContainerName, options); } else if (!credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName !== "string") { // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) url = urlOrConnectionString; // The second parameter is undefined. Use anonymous credential. pipeline = newPipeline(new AnonymousCredential(), options); } else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string" && blobNameOrOptions && typeof blobNameOrOptions === "string") { // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) const containerName = credentialOrPipelineOrContainerName; const blobName = blobNameOrOptions; const extractedCreds = extractConnectionStringParts(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { if (coreHttp.isNode) { const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); if (!options.proxyOptions) { options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); } pipeline = newPipeline(sharedKeyCredential, options); } else { throw new Error("Account connection string is only supported in Node.js environment"); } } else if (extractedCreds.kind === "SASConnString") { url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + "?" + extractedCreds.accountSas; pipeline = newPipeline(new AnonymousCredential(), options); } else { throw new Error("Connection string must be either an Account connection string or a SAS connection string"); } } else { throw new Error("Expecting non-empty strings for containerName and blobName parameters"); } super(url, pipeline); this.appendBlobContext = new AppendBlob(this.storageClientContext); } /** * Creates a new AppendBlobClient object identical to the source but with the * specified snapshot timestamp. * Provide "" will remove the snapshot and return a Client to the base blob. * * @param snapshot - The snapshot timestamp. * @returns A new AppendBlobClient object identical to the source but with the specified snapshot timestamp. */ withSnapshot(snapshot) { return new AppendBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); } /** * Creates a 0-length append blob. Call AppendBlock to append data to an append blob. * @see https://docs.microsoft.com/rest/api/storageservices/put-blob * * @param options - Options to the Append Block Create operation. * * * Example usage: * * ```js * const appendBlobClient = containerClient.getAppendBlobClient(""); * await appendBlobClient.create(); * ``` */ async create(options = {}) { var _a, _b, _c; const { span, updatedOptions } = createSpan("AppendBlobClient-create", options); options.conditions = options.conditions || {}; try { ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return await this.appendBlobContext.create(0, Object.assign({ abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, 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, blobTagsString: toBlobTagsString(options.tags) }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Creates a 0-length append blob. Call AppendBlock to append data to an append blob. * If the blob with the same name already exists, the content of the existing blob will remain unchanged. * @see https://docs.microsoft.com/rest/api/storageservices/put-blob * * @param options - */ async createIfNotExists(options = {}) { var _a, _b; const { span, updatedOptions } = createSpan("AppendBlobClient-createIfNotExists", options); const conditions = { ifNoneMatch: ETagAny }; try { const res = await this.create(Object.assign(Object.assign({}, updatedOptions), { conditions })); return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); } catch (e) { if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: "Expected exception when creating a blob only if it does not already exist.", }); return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); } span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Seals the append blob, making it read only. * * @param options - */ async seal(options = {}) { var _a; const { span, updatedOptions } = createSpan("AppendBlobClient-seal", options); options.conditions = options.conditions || {}; try { return await this.appendBlobContext.seal(Object.assign({ abortSignal: options.abortSignal, appendPositionAccessConditions: options.conditions, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Commits a new block of data to the end of the existing append blob. * @see https://docs.microsoft.com/rest/api/storageservices/append-block * * @param body - Data to be appended. * @param contentLength - Length of the body in bytes. * @param options - Options to the Append Block operation. * * * Example usage: * * ```js * const content = "Hello World!"; * * // Create a new append blob and append data to the blob. * const newAppendBlobClient = containerClient.getAppendBlobClient(""); * await newAppendBlobClient.create(); * await newAppendBlobClient.appendBlock(content, content.length); * * // Append data to an existing append blob. * const existingAppendBlobClient = containerClient.getAppendBlobClient(""); * await existingAppendBlobClient.appendBlock(content, content.length); * ``` */ async appendBlock(body, contentLength, options = {}) { var _a; const { span, updatedOptions } = createSpan("AppendBlobClient-appendBlock", options); options.conditions = options.conditions || {}; try { ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return await this.appendBlobContext.appendBlock(contentLength, body, Object.assign({ abortSignal: options.abortSignal, appendPositionAccessConditions: options.conditions, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), requestOptions: { onUploadProgress: options.onProgress, }, transactionalContentMD5: options.transactionalContentMD5, transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * The Append Block operation commits a new block of data to the end of an existing append blob * where the contents are read from a source url. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/append-block-from-url * * @param sourceURL - * The url to the blob that will be the source of the copy. A source blob in the same storage account can * be authenticated via Shared Key. However, if the source is a blob in another account, the source blob * must either be public or must be authenticated via a shared access signature. If the source blob is * public, no authentication is required to perform the operation. * @param sourceOffset - Offset in source to be appended * @param count - Number of bytes to be appended as a block * @param options - */ async appendBlockFromURL(sourceURL, sourceOffset, count, options = {}) { var _a; const { span, updatedOptions } = createSpan("AppendBlobClient-appendBlockFromURL", options); options.conditions = options.conditions || {}; options.sourceConditions = options.sourceConditions || {}; try { ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return await this.appendBlobContext.appendBlockFromUrl(sourceURL, 0, Object.assign({ abortSignal: options.abortSignal, sourceRange: rangeToString({ offset: sourceOffset, count }), sourceContentMD5: options.sourceContentMD5, sourceContentCrc64: options.sourceContentCrc64, leaseAccessConditions: options.conditions, appendPositionAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: { sourceIfMatch: options.sourceConditions.ifMatch, sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince, }, copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } } /** * BlockBlobClient defines a set of operations applicable to block blobs. */ class BlockBlobClient extends BlobClient { constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, // Legacy, no fix for eslint error without breaking. Disable it for this interface. /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ options) { // In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead. // super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options); let pipeline; let url; options = options || {}; if (isPipelineLike(credentialOrPipelineOrContainerName)) { // (url: string, pipeline: Pipeline) url = urlOrConnectionString; pipeline = credentialOrPipelineOrContainerName; } else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || credentialOrPipelineOrContainerName instanceof AnonymousCredential || coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) url = urlOrConnectionString; options = blobNameOrOptions; pipeline = newPipeline(credentialOrPipelineOrContainerName, options); } else if (!credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName !== "string") { // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) // The second parameter is undefined. Use anonymous credential. url = urlOrConnectionString; pipeline = newPipeline(new AnonymousCredential(), options); } else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string" && blobNameOrOptions && typeof blobNameOrOptions === "string") { // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) const containerName = credentialOrPipelineOrContainerName; const blobName = blobNameOrOptions; const extractedCreds = extractConnectionStringParts(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { if (coreHttp.isNode) { const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); if (!options.proxyOptions) { options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); } pipeline = newPipeline(sharedKeyCredential, options); } else { throw new Error("Account connection string is only supported in Node.js environment"); } } else if (extractedCreds.kind === "SASConnString") { url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + "?" + extractedCreds.accountSas; pipeline = newPipeline(new AnonymousCredential(), options); } else { throw new Error("Connection string must be either an Account connection string or a SAS connection string"); } } else { throw new Error("Expecting non-empty strings for containerName and blobName parameters"); } super(url, pipeline); this.blockBlobContext = new BlockBlob(this.storageClientContext); this._blobContext = new Blob$1(this.storageClientContext); } /** * Creates a new BlockBlobClient object identical to the source but with the * specified snapshot timestamp. * Provide "" will remove the snapshot and return a URL to the base blob. * * @param snapshot - The snapshot timestamp. * @returns A new BlockBlobClient object identical to the source but with the specified snapshot timestamp. */ withSnapshot(snapshot) { return new BlockBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * Quick query for a JSON or CSV formatted blob. * * Example usage (Node.js): * * ```js * // Query and convert a blob to a string * const queryBlockBlobResponse = await blockBlobClient.query("select * from BlobStorage"); * const downloaded = (await streamToBuffer(queryBlockBlobResponse.readableStreamBody)).toString(); * console.log("Query blob content:", downloaded); * * async function streamToBuffer(readableStream) { * return new Promise((resolve, reject) => { * const chunks = []; * readableStream.on("data", (data) => { * chunks.push(data instanceof Buffer ? data : Buffer.from(data)); * }); * readableStream.on("end", () => { * resolve(Buffer.concat(chunks)); * }); * readableStream.on("error", reject); * }); * } * ``` * * @param query - * @param options - */ async query(query, options = {}) { var _a; ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); const { span, updatedOptions } = createSpan("BlockBlobClient-query", options); try { if (!coreHttp.isNode) { throw new Error("This operation currently is only supported in Node.js."); } ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); const response = await this._blobContext.query(Object.assign({ abortSignal: options.abortSignal, queryRequest: { queryType: "SQL", expression: query, inputSerialization: toQuerySerialization(options.inputTextConfiguration), outputSerialization: toQuerySerialization(options.outputTextConfiguration), }, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey }, convertTracingToRequestOptionsBase(updatedOptions))); return new BlobQueryResponse(response, { abortSignal: options.abortSignal, onProgress: options.onProgress, onError: options.onError, }); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Creates a new block blob, or updates the content of an existing block blob. * Updating an existing block blob overwrites any existing metadata on the blob. * Partial updates are not supported; the content of the existing blob is * overwritten with the new content. To perform a partial update of a block blob's, * use {@link stageBlock} and {@link commitBlockList}. * * This is a non-parallel uploading method, please use {@link uploadFile}, * {@link uploadStream} or {@link uploadBrowserData} for better performance * with concurrency uploading. * * @see https://docs.microsoft.com/rest/api/storageservices/put-blob * * @param body - Blob, string, ArrayBuffer, ArrayBufferView or a function * which returns a new Readable stream whose offset is from data source beginning. * @param contentLength - Length of body in bytes. Use Buffer.byteLength() to calculate body length for a * string including non non-Base64/Hex-encoded characters. * @param options - Options to the Block Blob Upload operation. * @returns Response data for the Block Blob Upload operation. * * Example usage: * * ```js * const content = "Hello world!"; * const uploadBlobResponse = await blockBlobClient.upload(content, content.length); * ``` */ async upload(body, contentLength, options = {}) { var _a, _b, _c; options.conditions = options.conditions || {}; const { span, updatedOptions } = createSpan("BlockBlobClient-upload", options); try { ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return await this.blockBlobContext.upload(contentLength, body, Object.assign({ abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), requestOptions: { onUploadProgress: options.onProgress, }, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, 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, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags) }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Creates a new Block Blob where the contents of the blob are read from a given URL. * This API is supported beginning with the 2020-04-08 version. Partial updates * are not supported with Put Blob from URL; the content of an existing blob is overwritten with * the content of the new blob. To perform partial updates to a block blob’s contents using a * source URL, use {@link stageBlockFromURL} and {@link commitBlockList}. * * @param sourceURL - Specifies the URL of the blob. The value * may be a URL of up to 2 KB in length that specifies a blob. * The value should be URL-encoded as it would appear * in a request URI. The source blob must either be public * or must be authenticated via a shared access signature. * If the source blob is public, no authentication is required * to perform the operation. Here are some examples of source object URLs: * - https://myaccount.blob.core.windows.net/mycontainer/myblob * - https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= * @param options - Optional parameters. */ async syncUploadFromURL(sourceURL, options = {}) { var _a, _b, _c, _d, _e; options.conditions = options.conditions || {}; const { span, updatedOptions } = createSpan("BlockBlobClient-syncUploadFromURL", options); try { ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return await this.blockBlobContext.putBlobFromUrl(0, sourceURL, Object.assign(Object.assign(Object.assign({}, options), { blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: options.conditions.tagConditions }), sourceModifiedAccessConditions: { sourceIfMatch: (_a = options.sourceConditions) === null || _a === void 0 ? void 0 : _a.ifMatch, sourceIfModifiedSince: (_b = options.sourceConditions) === null || _b === void 0 ? void 0 : _b.ifModifiedSince, sourceIfNoneMatch: (_c = options.sourceConditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch, sourceIfUnmodifiedSince: (_d = options.sourceConditions) === null || _d === void 0 ? void 0 : _d.ifUnmodifiedSince, sourceIfTags: (_e = options.sourceConditions) === null || _e === void 0 ? void 0 : _e.tagConditions, }, cpkInfo: options.customerProvidedKey, copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization), tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags), copySourceTags: options.copySourceTags }), convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Uploads the specified block to the block blob's "staging area" to be later * committed by a call to commitBlockList. * @see https://docs.microsoft.com/rest/api/storageservices/put-block * * @param blockId - A 64-byte value that is base64-encoded * @param body - Data to upload to the staging area. * @param contentLength - Number of bytes to upload. * @param options - Options to the Block Blob Stage Block operation. * @returns Response data for the Block Blob Stage Block operation. */ async stageBlock(blockId, body, contentLength, options = {}) { const { span, updatedOptions } = createSpan("BlockBlobClient-stageBlock", options); try { ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return await this.blockBlobContext.stageBlock(blockId, contentLength, body, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, requestOptions: { onUploadProgress: options.onProgress, }, transactionalContentMD5: options.transactionalContentMD5, transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * The Stage Block From URL operation creates a new block to be committed as part * of a blob where the contents are read from a URL. * This API is available starting in version 2018-03-28. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/put-block-from-url * * @param blockId - A 64-byte value that is base64-encoded * @param sourceURL - Specifies the URL of the blob. The value * may be a URL of up to 2 KB in length that specifies a blob. * The value should be URL-encoded as it would appear * in a request URI. The source blob must either be public * or must be authenticated via a shared access signature. * If the source blob is public, no authentication is required * to perform the operation. Here are some examples of source object URLs: * - https://myaccount.blob.core.windows.net/mycontainer/myblob * - https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= * @param offset - From which position of the blob to download, greater than or equal to 0 * @param count - How much data to be downloaded, greater than 0. Will download to the end when undefined * @param options - Options to the Block Blob Stage Block From URL operation. * @returns Response data for the Block Blob Stage Block From URL operation. */ async stageBlockFromURL(blockId, sourceURL, offset = 0, count, options = {}) { const { span, updatedOptions } = createSpan("BlockBlobClient-stageBlockFromURL", options); try { ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return await this.blockBlobContext.stageBlockFromURL(blockId, 0, sourceURL, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, sourceContentMD5: options.sourceContentMD5, sourceContentCrc64: options.sourceContentCrc64, sourceRange: offset === 0 && !count ? undefined : rangeToString({ offset, count }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization) }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Writes a blob by specifying the list of block IDs that make up the blob. * In order to be written as part of a blob, a block must have been successfully written * to the server in a prior {@link stageBlock} operation. You can call {@link commitBlockList} to * update a blob by uploading only those blocks that have changed, then committing the new and existing * blocks together. Any blocks not specified in the block list and permanently deleted. * @see https://docs.microsoft.com/rest/api/storageservices/put-block-list * * @param blocks - Array of 64-byte value that is base64-encoded * @param options - Options to the Block Blob Commit Block List operation. * @returns Response data for the Block Blob Commit Block List operation. */ async commitBlockList(blocks, options = {}) { var _a, _b, _c; options.conditions = options.conditions || {}; const { span, updatedOptions } = createSpan("BlockBlobClient-commitBlockList", options); try { ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return await this.blockBlobContext.commitBlockList({ latest: blocks }, Object.assign({ abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, 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, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags) }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Returns the list of blocks that have been uploaded as part of a block blob * using the specified block list filter. * @see https://docs.microsoft.com/rest/api/storageservices/get-block-list * * @param listType - Specifies whether to return the list of committed blocks, * the list of uncommitted blocks, or both lists together. * @param options - Options to the Block Blob Get Block List operation. * @returns Response data for the Block Blob Get Block List operation. */ async getBlockList(listType, options = {}) { var _a; const { span, updatedOptions } = createSpan("BlockBlobClient-getBlockList", options); try { const res = await this.blockBlobContext.getBlockList(listType, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); if (!res.committedBlocks) { res.committedBlocks = []; } if (!res.uncommittedBlocks) { res.uncommittedBlocks = []; } return res; } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } // High level functions /** * Uploads a Buffer(Node.js)/Blob(browsers)/ArrayBuffer/ArrayBufferView object to a BlockBlob. * * When data length is no more than the specifiled {@link BlockBlobParallelUploadOptions.maxSingleShotSize} (default is * {@link BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES}), this method will use 1 {@link upload} call to finish the upload. * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call {@link commitBlockList} * to commit the block list. * * A common {@link BlockBlobParallelUploadOptions.blobHTTPHeaders} option to set is * `blobContentType`, enabling the browser to provide * functionality based on file type. * * @param data - Buffer(Node.js), Blob, ArrayBuffer or ArrayBufferView * @param options - */ async uploadData(data, options = {}) { const { span, updatedOptions } = createSpan("BlockBlobClient-uploadData", options); try { if (coreHttp.isNode) { let buffer; if (data instanceof Buffer) { buffer = data; } else if (data instanceof ArrayBuffer) { buffer = Buffer.from(data); } else { data = data; buffer = Buffer.from(data.buffer, data.byteOffset, data.byteLength); } return this.uploadSeekableInternal((offset, size) => buffer.slice(offset, offset + size), buffer.byteLength, updatedOptions); } else { const browserBlob = new Blob([data]); return this.uploadSeekableInternal((offset, size) => browserBlob.slice(offset, offset + size), browserBlob.size, updatedOptions); } } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * ONLY AVAILABLE IN BROWSERS. * * Uploads a browser Blob/File/ArrayBuffer/ArrayBufferView object to block blob. * * When buffer length lesser than or equal to 256MB, this method will use 1 upload call to finish the upload. * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call * {@link commitBlockList} to commit the block list. * * A common {@link BlockBlobParallelUploadOptions.blobHTTPHeaders} option to set is * `blobContentType`, enabling the browser to provide * functionality based on file type. * * @deprecated Use {@link uploadData} instead. * * @param browserData - Blob, File, ArrayBuffer or ArrayBufferView * @param options - Options to upload browser data. * @returns Response data for the Blob Upload operation. */ async uploadBrowserData(browserData, options = {}) { const { span, updatedOptions } = createSpan("BlockBlobClient-uploadBrowserData", options); try { const browserBlob = new Blob([browserData]); return await this.uploadSeekableInternal((offset, size) => browserBlob.slice(offset, offset + size), browserBlob.size, updatedOptions); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * * Uploads data to block blob. Requires a bodyFactory as the data source, * which need to return a {@link HttpRequestBody} object with the offset and size provided. * * When data length is no more than the specified {@link BlockBlobParallelUploadOptions.maxSingleShotSize} (default is * {@link BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES}), this method will use 1 {@link upload} call to finish the upload. * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call {@link commitBlockList} * to commit the block list. * * @param bodyFactory - * @param size - size of the data to upload. * @param options - Options to Upload to Block Blob operation. * @returns Response data for the Blob Upload operation. */ async uploadSeekableInternal(bodyFactory, size, options = {}) { if (!options.blockSize) { options.blockSize = 0; } if (options.blockSize < 0 || options.blockSize > BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES) { throw new RangeError(`blockSize option must be >= 0 and <= ${BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES}`); } if (options.maxSingleShotSize !== 0 && !options.maxSingleShotSize) { options.maxSingleShotSize = BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES; } if (options.maxSingleShotSize < 0 || options.maxSingleShotSize > BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES) { throw new RangeError(`maxSingleShotSize option must be >= 0 and <= ${BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES}`); } if (options.blockSize === 0) { if (size > BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES * BLOCK_BLOB_MAX_BLOCKS) { throw new RangeError(`${size} is too larger to upload to a block blob.`); } if (size > options.maxSingleShotSize) { options.blockSize = Math.ceil(size / BLOCK_BLOB_MAX_BLOCKS); if (options.blockSize < DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES) { options.blockSize = DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES; } } } if (!options.blobHTTPHeaders) { options.blobHTTPHeaders = {}; } if (!options.conditions) { options.conditions = {}; } const { span, updatedOptions } = createSpan("BlockBlobClient-uploadSeekableInternal", options); try { if (size <= options.maxSingleShotSize) { return await this.upload(bodyFactory(0, size), size, updatedOptions); } const numBlocks = Math.floor((size - 1) / options.blockSize) + 1; if (numBlocks > BLOCK_BLOB_MAX_BLOCKS) { throw new RangeError(`The buffer's size is too big or the BlockSize is too small;` + `the number of blocks must be <= ${BLOCK_BLOB_MAX_BLOCKS}`); } const blockList = []; const blockIDPrefix = coreHttp.generateUuid(); let transferProgress = 0; const batch = new Batch(options.concurrency); for (let i = 0; i < numBlocks; i++) { batch.addOperation(async () => { const blockID = generateBlockID(blockIDPrefix, i); const start = options.blockSize * i; const end = i === numBlocks - 1 ? size : start + options.blockSize; const contentLength = end - start; blockList.push(blockID); await this.stageBlock(blockID, bodyFactory(start, contentLength), contentLength, { abortSignal: options.abortSignal, conditions: options.conditions, encryptionScope: options.encryptionScope, tracingOptions: updatedOptions.tracingOptions, }); // Update progress after block is successfully uploaded to server, in case of block trying // TODO: Hook with convenience layer progress event in finer level transferProgress += contentLength; if (options.onProgress) { options.onProgress({ loadedBytes: transferProgress, }); } }); } await batch.do(); return this.commitBlockList(blockList, updatedOptions); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * Uploads a local file in blocks to a block blob. * * When file size lesser than or equal to 256MB, this method will use 1 upload call to finish the upload. * Otherwise, this method will call stageBlock to upload blocks, and finally call commitBlockList * to commit the block list. * * @param filePath - Full path of local file * @param options - Options to Upload to Block Blob operation. * @returns Response data for the Blob Upload operation. */ async uploadFile(filePath, options = {}) { const { span, updatedOptions } = createSpan("BlockBlobClient-uploadFile", options); try { const size = (await fsStat(filePath)).size; return await this.uploadSeekableInternal((offset, count) => { return () => fsCreateReadStream(filePath, { autoClose: true, end: count ? offset + count - 1 : Infinity, start: offset, }); }, size, Object.assign(Object.assign({}, options), { tracingOptions: Object.assign(Object.assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) })); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * Uploads a Node.js Readable stream into block blob. * * PERFORMANCE IMPROVEMENT TIPS: * * Input stream highWaterMark is better to set a same value with bufferSize * parameter, which will avoid Buffer.concat() operations. * * @param stream - Node.js Readable stream * @param bufferSize - Size of every buffer allocated, also the block size in the uploaded block blob. Default value is 8MB * @param maxConcurrency - Max concurrency indicates the max number of buffers that can be allocated, * positive correlation with max uploading concurrency. Default value is 5 * @param options - Options to Upload Stream to Block Blob operation. * @returns Response data for the Blob Upload operation. */ async uploadStream(stream, bufferSize = DEFAULT_BLOCK_BUFFER_SIZE_BYTES, maxConcurrency = 5, options = {}) { if (!options.blobHTTPHeaders) { options.blobHTTPHeaders = {}; } if (!options.conditions) { options.conditions = {}; } const { span, updatedOptions } = createSpan("BlockBlobClient-uploadStream", options); try { let blockNum = 0; const blockIDPrefix = coreHttp.generateUuid(); let transferProgress = 0; const blockList = []; const scheduler = new BufferScheduler(stream, bufferSize, maxConcurrency, async (body, length) => { const blockID = generateBlockID(blockIDPrefix, blockNum); blockList.push(blockID); blockNum++; await this.stageBlock(blockID, body, length, { conditions: options.conditions, encryptionScope: options.encryptionScope, tracingOptions: updatedOptions.tracingOptions, }); // Update progress after block is successfully uploaded to server, in case of block trying transferProgress += length; if (options.onProgress) { options.onProgress({ loadedBytes: transferProgress }); } }, // concurrency should set a smaller value than maxConcurrency, which is helpful to // reduce the possibility when a outgoing handler waits for stream data, in // this situation, outgoing handlers are blocked. // Outgoing queue shouldn't be empty. Math.ceil((maxConcurrency / 4) * 3)); await scheduler.do(); return await this.commitBlockList(blockList, Object.assign(Object.assign({}, options), { tracingOptions: Object.assign(Object.assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) })); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } } /** * PageBlobClient defines a set of operations applicable to page blobs. */ class PageBlobClient extends BlobClient { constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, // Legacy, no fix for eslint error without breaking. Disable it for this interface. /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ options) { // In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead. // super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options); let pipeline; let url; options = options || {}; if (isPipelineLike(credentialOrPipelineOrContainerName)) { // (url: string, pipeline: Pipeline) url = urlOrConnectionString; pipeline = credentialOrPipelineOrContainerName; } else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || credentialOrPipelineOrContainerName instanceof AnonymousCredential || coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) url = urlOrConnectionString; options = blobNameOrOptions; pipeline = newPipeline(credentialOrPipelineOrContainerName, options); } else if (!credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName !== "string") { // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) // The second parameter is undefined. Use anonymous credential. url = urlOrConnectionString; pipeline = newPipeline(new AnonymousCredential(), options); } else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string" && blobNameOrOptions && typeof blobNameOrOptions === "string") { // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) const containerName = credentialOrPipelineOrContainerName; const blobName = blobNameOrOptions; const extractedCreds = extractConnectionStringParts(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { if (coreHttp.isNode) { const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); if (!options.proxyOptions) { options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); } pipeline = newPipeline(sharedKeyCredential, options); } else { throw new Error("Account connection string is only supported in Node.js environment"); } } else if (extractedCreds.kind === "SASConnString") { url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + "?" + extractedCreds.accountSas; pipeline = newPipeline(new AnonymousCredential(), options); } else { throw new Error("Connection string must be either an Account connection string or a SAS connection string"); } } else { throw new Error("Expecting non-empty strings for containerName and blobName parameters"); } super(url, pipeline); this.pageBlobContext = new PageBlob(this.storageClientContext); } /** * Creates a new PageBlobClient object identical to the source but with the * specified snapshot timestamp. * Provide "" will remove the snapshot and return a Client to the base blob. * * @param snapshot - The snapshot timestamp. * @returns A new PageBlobClient object identical to the source but with the specified snapshot timestamp. */ withSnapshot(snapshot) { return new PageBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); } /** * Creates a page blob of the specified length. Call uploadPages to upload data * data to a page blob. * @see https://docs.microsoft.com/rest/api/storageservices/put-blob * * @param size - size of the page blob. * @param options - Options to the Page Blob Create operation. * @returns Response data for the Page Blob Create operation. */ async create(size, options = {}) { var _a, _b, _c; options.conditions = options.conditions || {}; const { span, updatedOptions } = createSpan("PageBlobClient-create", options); try { ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return await this.pageBlobContext.create(0, size, Object.assign({ abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, blobSequenceNumber: options.blobSequenceNumber, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, 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, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags) }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Creates a page blob of the specified length. Call uploadPages to upload data * data to a page blob. If the blob with the same name already exists, the content * of the existing blob will remain unchanged. * @see https://docs.microsoft.com/rest/api/storageservices/put-blob * * @param size - size of the page blob. * @param options - */ async createIfNotExists(size, options = {}) { var _a, _b; const { span, updatedOptions } = createSpan("PageBlobClient-createIfNotExists", options); try { const conditions = { ifNoneMatch: ETagAny }; const res = await this.create(size, Object.assign(Object.assign({}, options), { conditions, tracingOptions: updatedOptions.tracingOptions })); return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); } catch (e) { if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: "Expected exception when creating a blob only if it does not already exist.", }); return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); } span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Writes 1 or more pages to the page blob. The start and end offsets must be a multiple of 512. * @see https://docs.microsoft.com/rest/api/storageservices/put-page * * @param body - Data to upload * @param offset - Offset of destination page blob * @param count - Content length of the body, also number of bytes to be uploaded * @param options - Options to the Page Blob Upload Pages operation. * @returns Response data for the Page Blob Upload Pages operation. */ async uploadPages(body, offset, count, options = {}) { var _a; options.conditions = options.conditions || {}; const { span, updatedOptions } = createSpan("PageBlobClient-uploadPages", options); try { ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return await this.pageBlobContext.uploadPages(count, body, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), requestOptions: { onUploadProgress: options.onProgress, }, range: rangeToString({ offset, count }), sequenceNumberAccessConditions: options.conditions, transactionalContentMD5: options.transactionalContentMD5, transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * The Upload Pages operation writes a range of pages to a page blob where the * contents are read from a URL. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/put-page-from-url * * @param sourceURL - Specify a URL to the copy source, Shared Access Signature(SAS) maybe needed for authentication * @param sourceOffset - The source offset to copy from. Pass 0 to copy from the beginning of source page blob * @param destOffset - Offset of destination page blob * @param count - Number of bytes to be uploaded from source page blob * @param options - */ async uploadPagesFromURL(sourceURL, sourceOffset, destOffset, count, options = {}) { var _a; options.conditions = options.conditions || {}; options.sourceConditions = options.sourceConditions || {}; const { span, updatedOptions } = createSpan("PageBlobClient-uploadPagesFromURL", options); try { ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return await this.pageBlobContext.uploadPagesFromURL(sourceURL, rangeToString({ offset: sourceOffset, count }), 0, rangeToString({ offset: destOffset, count }), Object.assign({ abortSignal: options.abortSignal, sourceContentMD5: options.sourceContentMD5, sourceContentCrc64: options.sourceContentCrc64, leaseAccessConditions: options.conditions, sequenceNumberAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: { sourceIfMatch: options.sourceConditions.ifMatch, sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince, }, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization) }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Frees the specified pages from the page blob. * @see https://docs.microsoft.com/rest/api/storageservices/put-page * * @param offset - Starting byte position of the pages to clear. * @param count - Number of bytes to clear. * @param options - Options to the Page Blob Clear Pages operation. * @returns Response data for the Page Blob Clear Pages operation. */ async clearPages(offset = 0, count, options = {}) { var _a; options.conditions = options.conditions || {}; const { span, updatedOptions } = createSpan("PageBlobClient-clearPages", options); try { return await this.pageBlobContext.clearPages(0, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), range: rangeToString({ offset, count }), sequenceNumberAccessConditions: options.conditions, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Returns the list of valid page ranges for a page blob or snapshot of a page blob. * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges * * @param offset - Starting byte position of the page ranges. * @param count - Number of bytes to get. * @param options - Options to the Page Blob Get Ranges operation. * @returns Response data for the Page Blob Get Ranges operation. */ async getPageRanges(offset = 0, count, options = {}) { var _a; options.conditions = options.conditions || {}; const { span, updatedOptions } = createSpan("PageBlobClient-getPageRanges", options); try { return await this.pageBlobContext .getPageRanges(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), range: rangeToString({ offset, count }) }, convertTracingToRequestOptionsBase(updatedOptions))) .then(rangeResponseFromModel); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * getPageRangesSegment returns a single segment of page ranges starting from the * specified Marker. Use an empty Marker to start enumeration from the beginning. * After getting a segment, process it, and then call getPageRangesSegment again * (passing the the previously-returned Marker) to get the next segment. * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges * * @param offset - Starting byte position of the page ranges. * @param count - Number of bytes to get. * @param marker - A string value that identifies the portion of the list to be returned with the next list operation. * @param options - Options to PageBlob Get Page Ranges Segment operation. */ async listPageRangesSegment(offset = 0, count, marker, options = {}) { var _a; const { span, updatedOptions } = createSpan("PageBlobClient-getPageRangesSegment", options); try { return await this.pageBlobContext.getPageRanges(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), range: rangeToString({ offset, count }), marker: marker, maxPageSize: options.maxPageSize }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Returns an AsyncIterableIterator for {@link PageBlobGetPageRangesResponseModel} * * @param offset - Starting byte position of the page ranges. * @param count - Number of bytes to get. * @param marker - A string value that identifies the portion of * the get of page ranges to be returned with the next getting operation. The * operation returns the ContinuationToken value within the response body if the * getting operation did not return all page ranges remaining within the current page. * The ContinuationToken value can be used as the value for * the marker parameter in a subsequent call to request the next page of get * items. The marker value is opaque to the client. * @param options - Options to List Page Ranges operation. */ listPageRangeItemSegments(offset = 0, count, marker, options = {}) { return tslib.__asyncGenerator(this, arguments, function* listPageRangeItemSegments_1() { let getPageRangeItemSegmentsResponse; if (!!marker || marker === undefined) { do { getPageRangeItemSegmentsResponse = yield tslib.__await(this.listPageRangesSegment(offset, count, marker, options)); marker = getPageRangeItemSegmentsResponse.continuationToken; yield yield tslib.__await(yield tslib.__await(getPageRangeItemSegmentsResponse)); } while (marker); } }); } /** * Returns an AsyncIterableIterator of {@link PageRangeInfo} objects * * @param offset - Starting byte position of the page ranges. * @param count - Number of bytes to get. * @param options - Options to List Page Ranges operation. */ listPageRangeItems(offset = 0, count, options = {}) { return tslib.__asyncGenerator(this, arguments, function* listPageRangeItems_1() { var e_1, _a; let marker; try { for (var _b = tslib.__asyncValues(this.listPageRangeItemSegments(offset, count, marker, options)), _c; _c = yield tslib.__await(_b.next()), !_c.done;) { const getPageRangesSegment = _c.value; yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(ExtractPageRangeInfoItems(getPageRangesSegment)))); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) yield tslib.__await(_a.call(_b)); } finally { if (e_1) throw e_1.error; } } }); } /** * Returns an async iterable iterator to list of page ranges for a page blob. * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges * * .byPage() returns an async iterable iterator to list of page ranges for a page blob. * * Example using `for await` syntax: * * ```js * // Get the pageBlobClient before you run these snippets, * // Can be obtained from `blobServiceClient.getContainerClient("").getPageBlobClient("");` * let i = 1; * for await (const pageRange of pageBlobClient.listPageRanges()) { * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); * } * ``` * * Example using `iter.next()`: * * ```js * let i = 1; * let iter = pageBlobClient.listPageRanges(); * let pageRangeItem = await iter.next(); * while (!pageRangeItem.done) { * console.log(`Page range ${i++}: ${pageRangeItem.value.start} - ${pageRangeItem.value.end}, IsClear: ${pageRangeItem.value.isClear}`); * pageRangeItem = await iter.next(); * } * ``` * * Example using `byPage()`: * * ```js * // passing optional maxPageSize in the page settings * let i = 1; * for await (const response of pageBlobClient.listPageRanges().byPage({ maxPageSize: 20 })) { * for (const pageRange of response) { * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); * } * } * ``` * * Example using paging with a marker: * * ```js * let i = 1; * let iterator = pageBlobClient.listPageRanges().byPage({ maxPageSize: 2 }); * let response = (await iterator.next()).value; * * // Prints 2 page ranges * for (const pageRange of response) { * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); * } * * // Gets next marker * let marker = response.continuationToken; * * // Passing next marker as continuationToken * * iterator = pageBlobClient.listPageRanges().byPage({ continuationToken: marker, maxPageSize: 10 }); * response = (await iterator.next()).value; * * // Prints 10 page ranges * for (const blob of response) { * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); * } * ``` * @param offset - Starting byte position of the page ranges. * @param count - Number of bytes to get. * @param options - Options to the Page Blob Get Ranges operation. * @returns An asyncIterableIterator that supports paging. */ listPageRanges(offset = 0, count, options = {}) { options.conditions = options.conditions || {}; // AsyncIterableIterator to iterate over blobs const iter = this.listPageRangeItems(offset, count, options); return { /** * The next method, part of the iteration protocol */ next() { return iter.next(); }, /** * The connection to the async iterator, part of the iteration protocol */ [Symbol.asyncIterator]() { return this; }, /** * Return an AsyncIterableIterator that works a page at a time */ byPage: (settings = {}) => { return this.listPageRangeItemSegments(offset, count, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, options)); }, }; } /** * Gets the collection of page ranges that differ between a specified snapshot and this page blob. * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges * * @param offset - Starting byte position of the page blob * @param count - Number of bytes to get ranges diff. * @param prevSnapshot - Timestamp of snapshot to retrieve the difference. * @param options - Options to the Page Blob Get Page Ranges Diff operation. * @returns Response data for the Page Blob Get Page Range Diff operation. */ async getPageRangesDiff(offset, count, prevSnapshot, options = {}) { var _a; options.conditions = options.conditions || {}; const { span, updatedOptions } = createSpan("PageBlobClient-getPageRangesDiff", options); try { return await this.pageBlobContext .getPageRangesDiff(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), prevsnapshot: prevSnapshot, range: rangeToString({ offset, count }) }, convertTracingToRequestOptionsBase(updatedOptions))) .then(rangeResponseFromModel); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * getPageRangesDiffSegment returns a single segment of page ranges starting from the * specified Marker for difference between previous snapshot and the target page blob. * Use an empty Marker to start enumeration from the beginning. * After getting a segment, process it, and then call getPageRangesDiffSegment again * (passing the the previously-returned Marker) to get the next segment. * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges * * @param offset - Starting byte position of the page ranges. * @param count - Number of bytes to get. * @param prevSnapshotOrUrl - Timestamp of snapshot to retrieve the difference or URL of snapshot to retrieve the difference. * @param marker - A string value that identifies the portion of the get to be returned with the next get operation. * @param options - Options to the Page Blob Get Page Ranges Diff operation. */ async listPageRangesDiffSegment(offset, count, prevSnapshotOrUrl, marker, options) { var _a; const { span, updatedOptions } = createSpan("PageBlobClient-getPageRangesDiffSegment", options); try { return await this.pageBlobContext.getPageRangesDiff(Object.assign({ abortSignal: options === null || options === void 0 ? void 0 : options.abortSignal, leaseAccessConditions: options === null || options === void 0 ? void 0 : options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.conditions), { ifTags: (_a = options === null || options === void 0 ? void 0 : options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), prevsnapshot: prevSnapshotOrUrl, range: rangeToString({ offset: offset, count: count, }), marker: marker, maxPageSize: options === null || options === void 0 ? void 0 : options.maxPageSize }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Returns an AsyncIterableIterator for {@link PageBlobGetPageRangesDiffResponseModel} * * * @param offset - Starting byte position of the page ranges. * @param count - Number of bytes to get. * @param prevSnapshotOrUrl - Timestamp of snapshot to retrieve the difference or URL of snapshot to retrieve the difference. * @param marker - A string value that identifies the portion of * the get of page ranges to be returned with the next getting operation. The * operation returns the ContinuationToken value within the response body if the * getting operation did not return all page ranges remaining within the current page. * The ContinuationToken value can be used as the value for * the marker parameter in a subsequent call to request the next page of get * items. The marker value is opaque to the client. * @param options - Options to the Page Blob Get Page Ranges Diff operation. */ listPageRangeDiffItemSegments(offset, count, prevSnapshotOrUrl, marker, options) { return tslib.__asyncGenerator(this, arguments, function* listPageRangeDiffItemSegments_1() { let getPageRangeItemSegmentsResponse; if (!!marker || marker === undefined) { do { getPageRangeItemSegmentsResponse = yield tslib.__await(this.listPageRangesDiffSegment(offset, count, prevSnapshotOrUrl, marker, options)); marker = getPageRangeItemSegmentsResponse.continuationToken; yield yield tslib.__await(yield tslib.__await(getPageRangeItemSegmentsResponse)); } while (marker); } }); } /** * Returns an AsyncIterableIterator of {@link PageRangeInfo} objects * * @param offset - Starting byte position of the page ranges. * @param count - Number of bytes to get. * @param prevSnapshotOrUrl - Timestamp of snapshot to retrieve the difference or URL of snapshot to retrieve the difference. * @param options - Options to the Page Blob Get Page Ranges Diff operation. */ listPageRangeDiffItems(offset, count, prevSnapshotOrUrl, options) { return tslib.__asyncGenerator(this, arguments, function* listPageRangeDiffItems_1() { var e_2, _a; let marker; try { for (var _b = tslib.__asyncValues(this.listPageRangeDiffItemSegments(offset, count, prevSnapshotOrUrl, marker, options)), _c; _c = yield tslib.__await(_b.next()), !_c.done;) { const getPageRangesSegment = _c.value; yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(ExtractPageRangeInfoItems(getPageRangesSegment)))); } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) yield tslib.__await(_a.call(_b)); } finally { if (e_2) throw e_2.error; } } }); } /** * Returns an async iterable iterator to list of page ranges that differ between a specified snapshot and this page blob. * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges * * .byPage() returns an async iterable iterator to list of page ranges that differ between a specified snapshot and this page blob. * * Example using `for await` syntax: * * ```js * // Get the pageBlobClient before you run these snippets, * // Can be obtained from `blobServiceClient.getContainerClient("").getPageBlobClient("");` * let i = 1; * for await (const pageRange of pageBlobClient.listPageRangesDiff()) { * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); * } * ``` * * Example using `iter.next()`: * * ```js * let i = 1; * let iter = pageBlobClient.listPageRangesDiff(); * let pageRangeItem = await iter.next(); * while (!pageRangeItem.done) { * console.log(`Page range ${i++}: ${pageRangeItem.value.start} - ${pageRangeItem.value.end}, IsClear: ${pageRangeItem.value.isClear}`); * pageRangeItem = await iter.next(); * } * ``` * * Example using `byPage()`: * * ```js * // passing optional maxPageSize in the page settings * let i = 1; * for await (const response of pageBlobClient.listPageRangesDiff().byPage({ maxPageSize: 20 })) { * for (const pageRange of response) { * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); * } * } * ``` * * Example using paging with a marker: * * ```js * let i = 1; * let iterator = pageBlobClient.listPageRangesDiff().byPage({ maxPageSize: 2 }); * let response = (await iterator.next()).value; * * // Prints 2 page ranges * for (const pageRange of response) { * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); * } * * // Gets next marker * let marker = response.continuationToken; * * // Passing next marker as continuationToken * * iterator = pageBlobClient.listPageRangesDiff().byPage({ continuationToken: marker, maxPageSize: 10 }); * response = (await iterator.next()).value; * * // Prints 10 page ranges * for (const blob of response) { * console.log(`Page range ${i++}: ${pageRange.start} - ${pageRange.end}`); * } * ``` * @param offset - Starting byte position of the page ranges. * @param count - Number of bytes to get. * @param prevSnapshot - Timestamp of snapshot to retrieve the difference. * @param options - Options to the Page Blob Get Ranges operation. * @returns An asyncIterableIterator that supports paging. */ listPageRangesDiff(offset, count, prevSnapshot, options = {}) { options.conditions = options.conditions || {}; // AsyncIterableIterator to iterate over blobs const iter = this.listPageRangeDiffItems(offset, count, prevSnapshot, Object.assign({}, options)); return { /** * The next method, part of the iteration protocol */ next() { return iter.next(); }, /** * The connection to the async iterator, part of the iteration protocol */ [Symbol.asyncIterator]() { return this; }, /** * Return an AsyncIterableIterator that works a page at a time */ byPage: (settings = {}) => { return this.listPageRangeDiffItemSegments(offset, count, prevSnapshot, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, options)); }, }; } /** * Gets the collection of page ranges that differ between a specified snapshot and this page blob for managed disks. * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges * * @param offset - Starting byte position of the page blob * @param count - Number of bytes to get ranges diff. * @param prevSnapshotUrl - URL of snapshot to retrieve the difference. * @param options - Options to the Page Blob Get Page Ranges Diff operation. * @returns Response data for the Page Blob Get Page Range Diff operation. */ async getPageRangesDiffForManagedDisks(offset, count, prevSnapshotUrl, options = {}) { var _a; options.conditions = options.conditions || {}; const { span, updatedOptions } = createSpan("PageBlobClient-GetPageRangesDiffForManagedDisks", options); try { return await this.pageBlobContext .getPageRangesDiff(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), prevSnapshotUrl, range: rangeToString({ offset, count }) }, convertTracingToRequestOptionsBase(updatedOptions))) .then(rangeResponseFromModel); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Resizes the page blob to the specified size (which must be a multiple of 512). * @see https://docs.microsoft.com/rest/api/storageservices/set-blob-properties * * @param size - Target size * @param options - Options to the Page Blob Resize operation. * @returns Response data for the Page Blob Resize operation. */ async resize(size, options = {}) { var _a; options.conditions = options.conditions || {}; const { span, updatedOptions } = createSpan("PageBlobClient-resize", options); try { return await this.pageBlobContext.resize(size, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Sets a page blob's sequence number. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties * * @param sequenceNumberAction - Indicates how the service should modify the blob's sequence number. * @param sequenceNumber - Required if sequenceNumberAction is max or update * @param options - Options to the Page Blob Update Sequence Number operation. * @returns Response data for the Page Blob Update Sequence Number operation. */ async updateSequenceNumber(sequenceNumberAction, sequenceNumber, options = {}) { var _a; options.conditions = options.conditions || {}; const { span, updatedOptions } = createSpan("PageBlobClient-updateSequenceNumber", options); try { return await this.pageBlobContext.updateSequenceNumber(sequenceNumberAction, Object.assign({ abortSignal: options.abortSignal, blobSequenceNumber: sequenceNumber, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Begins an operation to start an incremental copy from one page blob's snapshot to this page blob. * The snapshot is copied such that only the differential changes between the previously * copied snapshot are transferred to the destination. * The copied snapshots are complete copies of the original snapshot and can be read or copied from as usual. * @see https://docs.microsoft.com/rest/api/storageservices/incremental-copy-blob * @see https://docs.microsoft.com/en-us/azure/virtual-machines/windows/incremental-snapshots * * @param copySource - Specifies the name of the source page blob snapshot. For example, * https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= * @param options - Options to the Page Blob Copy Incremental operation. * @returns Response data for the Page Blob Copy Incremental operation. */ async startCopyIncremental(copySource, options = {}) { var _a; const { span, updatedOptions } = createSpan("PageBlobClient-startCopyIncremental", options); try { return await this.pageBlobContext.copyIncremental(copySource, Object.assign({ abortSignal: options.abortSignal, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } } // Copyright (c) Microsoft Corporation. async function getBodyAsText(batchResponse) { let buffer = Buffer.alloc(BATCH_MAX_PAYLOAD_IN_BYTES); const responseLength = await streamToBuffer2(batchResponse.readableStreamBody, buffer); // Slice the buffer to trim the empty ending. buffer = buffer.slice(0, responseLength); return buffer.toString(); } function utf8ByteLength(str) { return Buffer.byteLength(str); } // Copyright (c) Microsoft Corporation. const HTTP_HEADER_DELIMITER = ": "; const SPACE_DELIMITER = " "; const NOT_FOUND = -1; /** * Util class for parsing batch response. */ class BatchResponseParser { constructor(batchResponse, subRequests) { if (!batchResponse || !batchResponse.contentType) { // In special case(reported), server may return invalid content-type which could not be parsed. throw new RangeError("batchResponse is malformed or doesn't contain valid content-type."); } if (!subRequests || subRequests.size === 0) { // This should be prevent during coding. throw new RangeError("Invalid state: subRequests is not provided or size is 0."); } this.batchResponse = batchResponse; this.subRequests = subRequests; this.responseBatchBoundary = this.batchResponse.contentType.split("=")[1]; this.perResponsePrefix = `--${this.responseBatchBoundary}${HTTP_LINE_ENDING}`; this.batchResponseEnding = `--${this.responseBatchBoundary}--`; } // For example of response, please refer to https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch#response async parseBatchResponse() { // When logic reach here, suppose batch request has already succeeded with 202, so we can further parse // sub request's response. if (this.batchResponse._response.status !== HTTPURLConnection.HTTP_ACCEPTED) { throw new Error(`Invalid state: batch request failed with status: '${this.batchResponse._response.status}'.`); } const responseBodyAsText = await getBodyAsText(this.batchResponse); const subResponses = responseBodyAsText .split(this.batchResponseEnding)[0] // string after ending is useless .split(this.perResponsePrefix) .slice(1); // string before first response boundary is useless const subResponseCount = subResponses.length; // Defensive coding in case of potential error parsing. // Note: subResponseCount == 1 is special case where sub request is invalid. // We try to prevent such cases through early validation, e.g. validate sub request count >= 1. // While in unexpected sub request invalid case, we allow sub response to be parsed and return to user. if (subResponseCount !== this.subRequests.size && subResponseCount !== 1) { throw new Error("Invalid state: sub responses' count is not equal to sub requests' count."); } const deserializedSubResponses = new Array(subResponseCount); let subResponsesSucceededCount = 0; let subResponsesFailedCount = 0; // Parse sub subResponses. for (let index = 0; index < subResponseCount; index++) { const subResponse = subResponses[index]; const deserializedSubResponse = {}; deserializedSubResponse.headers = new coreHttp.HttpHeaders(); const responseLines = subResponse.split(`${HTTP_LINE_ENDING}`); let subRespHeaderStartFound = false; let subRespHeaderEndFound = false; let subRespFailed = false; let contentId = NOT_FOUND; for (const responseLine of responseLines) { if (!subRespHeaderStartFound) { // Convention line to indicate content ID if (responseLine.startsWith(HeaderConstants.CONTENT_ID)) { contentId = parseInt(responseLine.split(HTTP_HEADER_DELIMITER)[1]); } // Http version line with status code indicates the start of sub request's response. // Example: HTTP/1.1 202 Accepted if (responseLine.startsWith(HTTP_VERSION_1_1)) { subRespHeaderStartFound = true; const tokens = responseLine.split(SPACE_DELIMITER); deserializedSubResponse.status = parseInt(tokens[1]); deserializedSubResponse.statusMessage = tokens.slice(2).join(SPACE_DELIMITER); } continue; // Skip convention headers not specifically for sub request i.e. Content-Type: application/http and Content-ID: * } if (responseLine.trim() === "") { // Sub response's header start line already found, and the first empty line indicates header end line found. if (!subRespHeaderEndFound) { subRespHeaderEndFound = true; } continue; // Skip empty line } // Note: when code reach here, it indicates subRespHeaderStartFound == true if (!subRespHeaderEndFound) { if (responseLine.indexOf(HTTP_HEADER_DELIMITER) === -1) { // Defensive coding to prevent from missing valuable lines. throw new Error(`Invalid state: find non-empty line '${responseLine}' without HTTP header delimiter '${HTTP_HEADER_DELIMITER}'.`); } // Parse headers of sub response. const tokens = responseLine.split(HTTP_HEADER_DELIMITER); deserializedSubResponse.headers.set(tokens[0], tokens[1]); if (tokens[0] === HeaderConstants.X_MS_ERROR_CODE) { deserializedSubResponse.errorCode = tokens[1]; subRespFailed = true; } } else { // Assemble body of sub response. if (!deserializedSubResponse.bodyAsText) { deserializedSubResponse.bodyAsText = ""; } deserializedSubResponse.bodyAsText += responseLine; } } // Inner for end // The response will contain the Content-ID header for each corresponding subrequest response to use for tracking. // The Content-IDs are set to a valid index in the subrequests we sent. In the status code 202 path, we could expect it // to be 1-1 mapping from the [0, subRequests.size) to the Content-IDs returned. If not, we simply don't return that // unexpected subResponse in the parsed reponse and we can always look it up in the raw response for debugging purpose. if (contentId !== NOT_FOUND && Number.isInteger(contentId) && contentId >= 0 && contentId < this.subRequests.size && deserializedSubResponses[contentId] === undefined) { deserializedSubResponse._request = this.subRequests.get(contentId); deserializedSubResponses[contentId] = deserializedSubResponse; } else { logger.error(`subResponses[${index}] is dropped as the Content-ID is not found or invalid, Content-ID: ${contentId}`); } if (subRespFailed) { subResponsesFailedCount++; } else { subResponsesSucceededCount++; } } return { subResponses: deserializedSubResponses, subResponsesSucceededCount: subResponsesSucceededCount, subResponsesFailedCount: subResponsesFailedCount, }; } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. var MutexLockStatus; (function (MutexLockStatus) { MutexLockStatus[MutexLockStatus["LOCKED"] = 0] = "LOCKED"; MutexLockStatus[MutexLockStatus["UNLOCKED"] = 1] = "UNLOCKED"; })(MutexLockStatus || (MutexLockStatus = {})); /** * An async mutex lock. */ class Mutex { /** * Lock for a specific key. If the lock has been acquired by another customer, then * will wait until getting the lock. * * @param key - lock key */ static async lock(key) { return new Promise((resolve) => { if (this.keys[key] === undefined || this.keys[key] === MutexLockStatus.UNLOCKED) { this.keys[key] = MutexLockStatus.LOCKED; resolve(); } else { this.onUnlockEvent(key, () => { this.keys[key] = MutexLockStatus.LOCKED; resolve(); }); } }); } /** * Unlock a key. * * @param key - */ static async unlock(key) { return new Promise((resolve) => { if (this.keys[key] === MutexLockStatus.LOCKED) { this.emitUnlockEvent(key); } delete this.keys[key]; resolve(); }); } static onUnlockEvent(key, handler) { if (this.listeners[key] === undefined) { this.listeners[key] = [handler]; } else { this.listeners[key].push(handler); } } static emitUnlockEvent(key) { if (this.listeners[key] !== undefined && this.listeners[key].length > 0) { const handler = this.listeners[key].shift(); setImmediate(() => { handler.call(this); }); } } } Mutex.keys = {}; Mutex.listeners = {}; // Copyright (c) Microsoft Corporation. /** * A BlobBatch represents an aggregated set of operations on blobs. * Currently, only `delete` and `setAccessTier` are supported. */ class BlobBatch { constructor() { this.batch = "batch"; this.batchRequest = new InnerBatchRequest(); } /** * Get the value of Content-Type for a batch request. * The value must be multipart/mixed with a batch boundary. * Example: multipart/mixed; boundary=batch_a81786c8-e301-4e42-a729-a32ca24ae252 */ getMultiPartContentType() { return this.batchRequest.getMultipartContentType(); } /** * Get assembled HTTP request body for sub requests. */ getHttpRequestBody() { return this.batchRequest.getHttpRequestBody(); } /** * Get sub requests that are added into the batch request. */ getSubRequests() { return this.batchRequest.getSubRequests(); } async addSubRequestInternal(subRequest, assembleSubRequestFunc) { await Mutex.lock(this.batch); try { this.batchRequest.preAddSubRequest(subRequest); await assembleSubRequestFunc(); this.batchRequest.postAddSubRequest(subRequest); } finally { await Mutex.unlock(this.batch); } } setBatchType(batchType) { if (!this.batchType) { this.batchType = batchType; } if (this.batchType !== batchType) { throw new RangeError(`BlobBatch only supports one operation type per batch and it already is being used for ${this.batchType} operations.`); } } async deleteBlob(urlOrBlobClient, credentialOrOptions, options) { let url; let credential; if (typeof urlOrBlobClient === "string" && ((coreHttp.isNode && credentialOrOptions instanceof StorageSharedKeyCredential) || credentialOrOptions instanceof AnonymousCredential || coreHttp.isTokenCredential(credentialOrOptions))) { // First overload url = urlOrBlobClient; credential = credentialOrOptions; } else if (urlOrBlobClient instanceof BlobClient) { // Second overload url = urlOrBlobClient.url; credential = urlOrBlobClient.credential; options = credentialOrOptions; } else { throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); } if (!options) { options = {}; } const { span, updatedOptions } = createSpan("BatchDeleteRequest-addSubRequest", options); try { this.setBatchType("delete"); await this.addSubRequestInternal({ url: url, credential: credential, }, async () => { await new BlobClient(url, this.batchRequest.createPipeline(credential)).delete(updatedOptions); }); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } async setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options) { let url; let credential; let tier; if (typeof urlOrBlobClient === "string" && ((coreHttp.isNode && credentialOrTier instanceof StorageSharedKeyCredential) || credentialOrTier instanceof AnonymousCredential || coreHttp.isTokenCredential(credentialOrTier))) { // First overload url = urlOrBlobClient; credential = credentialOrTier; tier = tierOrOptions; } else if (urlOrBlobClient instanceof BlobClient) { // Second overload url = urlOrBlobClient.url; credential = urlOrBlobClient.credential; tier = credentialOrTier; options = tierOrOptions; } else { throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); } if (!options) { options = {}; } const { span, updatedOptions } = createSpan("BatchSetTierRequest-addSubRequest", options); try { this.setBatchType("setAccessTier"); await this.addSubRequestInternal({ url: url, credential: credential, }, async () => { await new BlobClient(url, this.batchRequest.createPipeline(credential)).setAccessTier(tier, updatedOptions); }); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } } /** * Inner batch request class which is responsible for assembling and serializing sub requests. * See https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch#request-body for how requests are assembled. */ class InnerBatchRequest { constructor() { this.operationCount = 0; this.body = ""; const tempGuid = coreHttp.generateUuid(); // batch_{batchid} this.boundary = `batch_${tempGuid}`; // --batch_{batchid} // Content-Type: application/http // Content-Transfer-Encoding: binary this.subRequestPrefix = `--${this.boundary}${HTTP_LINE_ENDING}${HeaderConstants.CONTENT_TYPE}: application/http${HTTP_LINE_ENDING}${HeaderConstants.CONTENT_TRANSFER_ENCODING}: binary`; // multipart/mixed; boundary=batch_{batchid} this.multipartContentType = `multipart/mixed; boundary=${this.boundary}`; // --batch_{batchid}-- this.batchRequestEnding = `--${this.boundary}--`; this.subRequests = new Map(); } /** * Create pipeline to assemble sub requests. The idea here is to use existing * credential and serialization/deserialization components, with additional policies to * filter unnecessary headers, assemble sub requests into request's body * and intercept request from going to wire. * @param credential - Such as AnonymousCredential, StorageSharedKeyCredential or any credential from the `@azure/identity` package to authenticate requests to the service. You can also provide an object that implements the TokenCredential interface. If not specified, AnonymousCredential is used. */ createPipeline(credential) { const isAnonymousCreds = credential instanceof AnonymousCredential; const policyFactoryLength = 3 + (isAnonymousCreds ? 0 : 1); // [deserializationPolicy, BatchHeaderFilterPolicyFactory, (Optional)Credential, BatchRequestAssemblePolicyFactory] const factories = new Array(policyFactoryLength); factories[0] = coreHttp.deserializationPolicy(); // Default deserializationPolicy is provided by protocol layer factories[1] = new BatchHeaderFilterPolicyFactory(); // Use batch header filter policy to exclude unnecessary headers if (!isAnonymousCreds) { factories[2] = coreHttp.isTokenCredential(credential) ? attachCredential(coreHttp.bearerTokenAuthenticationPolicy(credential, StorageOAuthScopes), credential) : credential; } factories[policyFactoryLength - 1] = new BatchRequestAssemblePolicyFactory(this); // Use batch assemble policy to assemble request and intercept request from going to wire return new Pipeline(factories, {}); } appendSubRequestToBody(request) { // Start to assemble sub request this.body += [ this.subRequestPrefix, `${HeaderConstants.CONTENT_ID}: ${this.operationCount}`, "", `${request.method.toString()} ${getURLPathAndQuery(request.url)} ${HTTP_VERSION_1_1}${HTTP_LINE_ENDING}`, // sub request start line with method ].join(HTTP_LINE_ENDING); for (const header of request.headers.headersArray()) { this.body += `${header.name}: ${header.value}${HTTP_LINE_ENDING}`; } this.body += HTTP_LINE_ENDING; // sub request's headers need be ending with an empty line // No body to assemble for current batch request support // End to assemble sub request } preAddSubRequest(subRequest) { if (this.operationCount >= BATCH_MAX_REQUEST) { throw new RangeError(`Cannot exceed ${BATCH_MAX_REQUEST} sub requests in a single batch`); } // Fast fail if url for sub request is invalid const path = getURLPath(subRequest.url); if (!path || path === "") { throw new RangeError(`Invalid url for sub request: '${subRequest.url}'`); } } postAddSubRequest(subRequest) { this.subRequests.set(this.operationCount, subRequest); this.operationCount++; } // Return the http request body with assembling the ending line to the sub request body. getHttpRequestBody() { return `${this.body}${this.batchRequestEnding}${HTTP_LINE_ENDING}`; } getMultipartContentType() { return this.multipartContentType; } getSubRequests() { return this.subRequests; } } class BatchRequestAssemblePolicy extends coreHttp.BaseRequestPolicy { constructor(batchRequest, nextPolicy, options) { super(nextPolicy, options); this.dummyResponse = { request: new coreHttp.WebResource(), status: 200, headers: new coreHttp.HttpHeaders(), }; this.batchRequest = batchRequest; } async sendRequest(request) { await this.batchRequest.appendSubRequestToBody(request); return this.dummyResponse; // Intercept request from going to wire } } class BatchRequestAssemblePolicyFactory { constructor(batchRequest) { this.batchRequest = batchRequest; } create(nextPolicy, options) { return new BatchRequestAssemblePolicy(this.batchRequest, nextPolicy, options); } } class BatchHeaderFilterPolicy extends coreHttp.BaseRequestPolicy { // The base class has a protected constructor. Adding a public one to enable constructing of this class. /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/ constructor(nextPolicy, options) { super(nextPolicy, options); } async sendRequest(request) { let xMsHeaderName = ""; for (const header of request.headers.headersArray()) { if (iEqual(header.name, HeaderConstants.X_MS_VERSION)) { xMsHeaderName = header.name; } } if (xMsHeaderName !== "") { request.headers.remove(xMsHeaderName); // The subrequests should not have the x-ms-version header. } return this._nextPolicy.sendRequest(request); } } class BatchHeaderFilterPolicyFactory { create(nextPolicy, options) { return new BatchHeaderFilterPolicy(nextPolicy, options); } } // Copyright (c) Microsoft Corporation. /** * A BlobBatchClient allows you to make batched requests to the Azure Storage Blob service. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch */ class BlobBatchClient { constructor(url, credentialOrPipeline, // Legacy, no fix for eslint error without breaking. Disable it for this interface. /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ options) { let pipeline; if (isPipelineLike(credentialOrPipeline)) { pipeline = credentialOrPipeline; } else if (!credentialOrPipeline) { // no credential provided pipeline = newPipeline(new AnonymousCredential(), options); } else { pipeline = newPipeline(credentialOrPipeline, options); } const storageClientContext = new StorageClientContext(url, pipeline.toServiceClientOptions()); const path = getURLPath(url); if (path && path !== "/") { // Container scoped. this.serviceOrContainerContext = new Container(storageClientContext); } else { this.serviceOrContainerContext = new Service(storageClientContext); } } /** * Creates a {@link BlobBatch}. * A BlobBatch represents an aggregated set of operations on blobs. */ createBatch() { return new BlobBatch(); } async deleteBlobs(urlsOrBlobClients, credentialOrOptions, // Legacy, no fix for eslint error without breaking. Disable it for this interface. /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ options) { const batch = new BlobBatch(); for (const urlOrBlobClient of urlsOrBlobClients) { if (typeof urlOrBlobClient === "string") { await batch.deleteBlob(urlOrBlobClient, credentialOrOptions, options); } else { await batch.deleteBlob(urlOrBlobClient, credentialOrOptions); } } return this.submitBatch(batch); } async setBlobsAccessTier(urlsOrBlobClients, credentialOrTier, tierOrOptions, // Legacy, no fix for eslint error without breaking. Disable it for this interface. /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ options) { const batch = new BlobBatch(); for (const urlOrBlobClient of urlsOrBlobClients) { if (typeof urlOrBlobClient === "string") { await batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options); } else { await batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions); } } return this.submitBatch(batch); } /** * Submit batch request which consists of multiple subrequests. * * Get `blobBatchClient` and other details before running the snippets. * `blobServiceClient.getBlobBatchClient()` gives the `blobBatchClient` * * Example usage: * * ```js * let batchRequest = new BlobBatch(); * await batchRequest.deleteBlob(urlInString0, credential0); * await batchRequest.deleteBlob(urlInString1, credential1, { * deleteSnapshots: "include" * }); * const batchResp = await blobBatchClient.submitBatch(batchRequest); * console.log(batchResp.subResponsesSucceededCount); * ``` * * Example using a lease: * * ```js * let batchRequest = new BlobBatch(); * await batchRequest.setBlobAccessTier(blockBlobClient0, "Cool"); * await batchRequest.setBlobAccessTier(blockBlobClient1, "Cool", { * conditions: { leaseId: leaseId } * }); * const batchResp = await blobBatchClient.submitBatch(batchRequest); * console.log(batchResp.subResponsesSucceededCount); * ``` * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch * * @param batchRequest - A set of Delete or SetTier operations. * @param options - */ async submitBatch(batchRequest, options = {}) { if (!batchRequest || batchRequest.getSubRequests().size === 0) { throw new RangeError("Batch request should contain one or more sub requests."); } const { span, updatedOptions } = createSpan("BlobBatchClient-submitBatch", options); try { const batchRequestBody = batchRequest.getHttpRequestBody(); // ServiceSubmitBatchResponseModel and ContainerSubmitBatchResponse are compatible for now. const rawBatchResponse = await this.serviceOrContainerContext.submitBatch(utf8ByteLength(batchRequestBody), batchRequest.getMultiPartContentType(), batchRequestBody, Object.assign(Object.assign({}, options), convertTracingToRequestOptionsBase(updatedOptions))); // Parse the sub responses result, if logic reaches here(i.e. the batch request succeeded with status code 202). const batchResponseParser = new BatchResponseParser(rawBatchResponse, batchRequest.getSubRequests()); const responseSummary = await batchResponseParser.parseBatchResponse(); const res = { _response: rawBatchResponse._response, contentType: rawBatchResponse.contentType, errorCode: rawBatchResponse.errorCode, requestId: rawBatchResponse.requestId, clientRequestId: rawBatchResponse.clientRequestId, version: rawBatchResponse.version, subResponses: responseSummary.subResponses, subResponsesSucceededCount: responseSummary.subResponsesSucceededCount, subResponsesFailedCount: responseSummary.subResponsesFailedCount, }; return res; } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } } /** * A ContainerClient represents a URL to the Azure Storage container allowing you to manipulate its blobs. */ class ContainerClient extends StorageClient { constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, // Legacy, no fix for eslint error without breaking. Disable it for this interface. /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ options) { let pipeline; let url; options = options || {}; if (isPipelineLike(credentialOrPipelineOrContainerName)) { // (url: string, pipeline: Pipeline) url = urlOrConnectionString; pipeline = credentialOrPipelineOrContainerName; } else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || credentialOrPipelineOrContainerName instanceof AnonymousCredential || coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) url = urlOrConnectionString; pipeline = newPipeline(credentialOrPipelineOrContainerName, options); } else if (!credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName !== "string") { // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) // The second parameter is undefined. Use anonymous credential. url = urlOrConnectionString; pipeline = newPipeline(new AnonymousCredential(), options); } else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string") { // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) const containerName = credentialOrPipelineOrContainerName; const extractedCreds = extractConnectionStringParts(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { if (coreHttp.isNode) { const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); url = appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)); if (!options.proxyOptions) { options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); } pipeline = newPipeline(sharedKeyCredential, options); } else { throw new Error("Account connection string is only supported in Node.js environment"); } } else if (extractedCreds.kind === "SASConnString") { url = appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)) + "?" + extractedCreds.accountSas; pipeline = newPipeline(new AnonymousCredential(), options); } else { throw new Error("Connection string must be either an Account connection string or a SAS connection string"); } } else { throw new Error("Expecting non-empty strings for containerName parameter"); } super(url, pipeline); this._containerName = this.getContainerNameFromUrl(); this.containerContext = new Container(this.storageClientContext); } /** * The name of the container. */ get containerName() { return this._containerName; } /** * 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. * * * Example usage: * * ```js * const containerClient = blobServiceClient.getContainerClient(""); * const createContainerResponse = await containerClient.create(); * console.log("Container was created successfully", createContainerResponse.requestId); * ``` */ async create(options = {}) { const { span, updatedOptions } = createSpan("ContainerClient-create", options); try { // Spread operator in destructuring assignments, // this will filter out unwanted properties from the response object into result object return await this.containerContext.create(Object.assign(Object.assign({}, options), convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * 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 - */ async createIfNotExists(options = {}) { var _a, _b; const { span, updatedOptions } = createSpan("ContainerClient-createIfNotExists", options); try { const res = await this.create(updatedOptions); return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); } catch (e) { if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerAlreadyExists") { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: "Expected exception when creating a container only if it does not already exist.", }); return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); } span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Returns true if the Azure container resource represented by this client exists; false otherwise. * * NOTE: use this function with care since an existing container might be deleted by other clients or * applications. Vice versa new containers with the same name might be added by other clients or * applications after this function completes. * * @param options - */ async exists(options = {}) { const { span, updatedOptions } = createSpan("ContainerClient-exists", options); try { await this.getProperties({ abortSignal: options.abortSignal, tracingOptions: updatedOptions.tracingOptions, }); return true; } catch (e) { if (e.statusCode === 404) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: "Expected exception when checking container existence", }); return false; } span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Creates a {@link BlobClient} * * @param blobName - A blob name * @returns A new BlobClient object for the given blob name. */ getBlobClient(blobName) { return new BlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); } /** * Creates an {@link AppendBlobClient} * * @param blobName - An append blob name */ getAppendBlobClient(blobName) { return new AppendBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); } /** * Creates a {@link BlockBlobClient} * * @param blobName - A block blob name * * * Example usage: * * ```js * const content = "Hello world!"; * * const blockBlobClient = containerClient.getBlockBlobClient(""); * const uploadBlobResponse = await blockBlobClient.upload(content, content.length); * ``` */ getBlockBlobClient(blobName) { return new BlockBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); } /** * Creates a {@link PageBlobClient} * * @param blobName - A page blob name */ getPageBlobClient(blobName) { return new PageBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline); } /** * Returns all user-defined metadata and system properties for the specified * container. The data returned does not include the container's list of blobs. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-container-properties * * WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if * they originally contained uppercase characters. This differs from the metadata keys returned by * the `listContainers` method of {@link BlobServiceClient} using the `includeMetadata` option, which * will retain their original casing. * * @param options - Options to Container Get Properties operation. */ async getProperties(options = {}) { if (!options.conditions) { options.conditions = {}; } const { span, updatedOptions } = createSpan("ContainerClient-getProperties", options); try { return await this.containerContext.getProperties(Object.assign(Object.assign({ abortSignal: options.abortSignal }, options.conditions), convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Marks the specified container for deletion. The container and any blobs * contained within it are later deleted during garbage collection. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-container * * @param options - Options to Container Delete operation. */ async delete(options = {}) { if (!options.conditions) { options.conditions = {}; } const { span, updatedOptions } = createSpan("ContainerClient-delete", options); try { return await this.containerContext.delete(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Marks the specified container for deletion if it exists. The container and any blobs * contained within it are later deleted during garbage collection. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-container * * @param options - Options to Container Delete operation. */ async deleteIfExists(options = {}) { var _a, _b; const { span, updatedOptions } = createSpan("ContainerClient-deleteIfExists", options); try { const res = await this.delete(updatedOptions); return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response }); } catch (e) { if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerNotFound") { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: "Expected exception when deleting a container only if it exists.", }); return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); } span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Sets one or more user-defined name-value pairs for the specified container. * * If no option provided, or no metadata defined in the parameter, the container * metadata will be removed. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-container-metadata * * @param metadata - Replace existing metadata with this value. * If no value provided the existing metadata will be removed. * @param options - Options to Container Set Metadata operation. */ async setMetadata(metadata, options = {}) { if (!options.conditions) { options.conditions = {}; } if (options.conditions.ifUnmodifiedSince) { throw new RangeError("the IfUnmodifiedSince must have their default values because they are ignored by the blob service"); } const { span, updatedOptions } = createSpan("ContainerClient-setMetadata", options); try { return await this.containerContext.setMetadata(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata, modifiedAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Gets the permissions for the specified container. The permissions indicate * whether container data may be accessed publicly. * * WARNING: JavaScript Date will potentially lose precision when parsing startsOn and expiresOn strings. * For example, new Date("2018-12-31T03:44:23.8827891Z").toISOString() will get "2018-12-31T03:44:23.882Z". * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-container-acl * * @param options - Options to Container Get Access Policy operation. */ async getAccessPolicy(options = {}) { if (!options.conditions) { options.conditions = {}; } const { span, updatedOptions } = createSpan("ContainerClient-getAccessPolicy", options); try { const response = await this.containerContext.getAccessPolicy(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions))); const res = { _response: response._response, blobPublicAccess: response.blobPublicAccess, date: response.date, etag: response.etag, errorCode: response.errorCode, lastModified: response.lastModified, requestId: response.requestId, clientRequestId: response.clientRequestId, signedIdentifiers: [], version: response.version, }; for (const identifier of response) { let accessPolicy = undefined; if (identifier.accessPolicy) { accessPolicy = { permissions: identifier.accessPolicy.permissions, }; if (identifier.accessPolicy.expiresOn) { accessPolicy.expiresOn = new Date(identifier.accessPolicy.expiresOn); } if (identifier.accessPolicy.startsOn) { accessPolicy.startsOn = new Date(identifier.accessPolicy.startsOn); } } res.signedIdentifiers.push({ accessPolicy, id: identifier.id, }); } return res; } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Sets the permissions for the specified container. The permissions indicate * whether blobs in a container may be accessed publicly. * * When you set permissions for a container, the existing permissions are replaced. * If no access or containerAcl provided, the existing container ACL will be * removed. * * When you establish a stored access policy on a container, it may take up to 30 seconds to take effect. * During this interval, a shared access signature that is associated with the stored access policy will * fail with status code 403 (Forbidden), until the access policy becomes active. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-container-acl * * @param access - The level of public access to data in the container. * @param containerAcl - Array of elements each having a unique Id and details of the access policy. * @param options - Options to Container Set Access Policy operation. */ async setAccessPolicy(access, containerAcl, options = {}) { options.conditions = options.conditions || {}; const { span, updatedOptions } = createSpan("ContainerClient-setAccessPolicy", options); try { const acl = []; for (const identifier of containerAcl || []) { acl.push({ accessPolicy: { expiresOn: identifier.accessPolicy.expiresOn ? truncatedISO8061Date(identifier.accessPolicy.expiresOn) : "", permissions: identifier.accessPolicy.permissions, startsOn: identifier.accessPolicy.startsOn ? truncatedISO8061Date(identifier.accessPolicy.startsOn) : "", }, id: identifier.id, }); } return await this.containerContext.setAccessPolicy(Object.assign({ abortSignal: options.abortSignal, access, containerAcl: acl, leaseAccessConditions: options.conditions, modifiedAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Get a {@link BlobLeaseClient} that manages leases on the container. * * @param proposeLeaseId - Initial proposed lease Id. * @returns A new BlobLeaseClient object for managing leases on the container. */ getBlobLeaseClient(proposeLeaseId) { return new BlobLeaseClient(this, proposeLeaseId); } /** * Creates a new block blob, or updates the content of an existing block blob. * * Updating an existing block blob overwrites any existing metadata on the blob. * Partial updates are not supported; the content of the existing blob is * overwritten with the new content. To perform a partial update of a block blob's, * use {@link BlockBlobClient.stageBlock} and {@link BlockBlobClient.commitBlockList}. * * This is a non-parallel uploading method, please use {@link BlockBlobClient.uploadFile}, * {@link BlockBlobClient.uploadStream} or {@link BlockBlobClient.uploadBrowserData} for better * performance with concurrency uploading. * * @see https://docs.microsoft.com/rest/api/storageservices/put-blob * * @param blobName - Name of the block blob to create or update. * @param body - Blob, string, ArrayBuffer, ArrayBufferView or a function * which returns a new Readable stream whose offset is from data source beginning. * @param contentLength - Length of body in bytes. Use Buffer.byteLength() to calculate body length for a * string including non non-Base64/Hex-encoded characters. * @param options - Options to configure the Block Blob Upload operation. * @returns Block Blob upload response data and the corresponding BlockBlobClient instance. */ async uploadBlockBlob(blobName, body, contentLength, options = {}) { const { span, updatedOptions } = createSpan("ContainerClient-uploadBlockBlob", options); try { const blockBlobClient = this.getBlockBlobClient(blobName); const response = await blockBlobClient.upload(body, contentLength, updatedOptions); return { blockBlobClient, response, }; } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Marks the specified blob or snapshot for deletion. The blob is later deleted * during garbage collection. Note that in order to delete a blob, you must delete * all of its snapshots. You can delete both at the same time with the Delete * Blob operation. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob * * @param blobName - * @param options - Options to Blob Delete operation. * @returns Block blob deletion response data. */ async deleteBlob(blobName, options = {}) { const { span, updatedOptions } = createSpan("ContainerClient-deleteBlob", options); try { let blobClient = this.getBlobClient(blobName); if (options.versionId) { blobClient = blobClient.withVersion(options.versionId); } return await blobClient.delete(updatedOptions); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * listBlobFlatSegment returns a single segment of blobs starting from the * specified Marker. Use an empty Marker to start enumeration from the beginning. * After getting a segment, process it, and then call listBlobsFlatSegment again * (passing the the previously-returned Marker) to get the next segment. * @see https://docs.microsoft.com/rest/api/storageservices/list-blobs * * @param marker - A string value that identifies the portion of the list to be returned with the next list operation. * @param options - Options to Container List Blob Flat Segment operation. */ async listBlobFlatSegment(marker, options = {}) { const { span, updatedOptions } = createSpan("ContainerClient-listBlobFlatSegment", options); try { const response = await this.containerContext.listBlobFlatSegment(Object.assign(Object.assign({ marker }, options), convertTracingToRequestOptionsBase(updatedOptions))); 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; }) }) }); return wrappedResponse; } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * listBlobHierarchySegment returns a single segment of blobs starting from * the specified Marker. Use an empty Marker to start enumeration from the * beginning. After getting a segment, process it, and then call listBlobsHierarchicalSegment * again (passing the the previously-returned Marker) to get the next segment. * @see https://docs.microsoft.com/rest/api/storageservices/list-blobs * * @param delimiter - The character or string used to define the virtual hierarchy * @param marker - A string value that identifies the portion of the list to be returned with the next list operation. * @param options - Options to Container List Blob Hierarchy Segment operation. */ async listBlobHierarchySegment(delimiter, marker, options = {}) { var _a; const { span, updatedOptions } = createSpan("ContainerClient-listBlobHierarchySegment", options); try { const response = await this.containerContext.listBlobHierarchySegment(delimiter, Object.assign(Object.assign({ marker }, options), convertTracingToRequestOptionsBase(updatedOptions))); 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), }; return blobPrefix; }) }) }); return wrappedResponse; } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Returns an AsyncIterableIterator for ContainerListBlobFlatSegmentResponse * * @param marker - A string value that identifies the portion of * the list of blobs to be returned with the next listing operation. The * operation returns the ContinuationToken value within the response body if the * listing operation did not return all blobs remaining to be listed * with the current page. The ContinuationToken value can be used as the value for * the marker parameter in a subsequent call to request the next page of list * items. The marker value is opaque to the client. * @param options - Options to list blobs operation. */ listSegments(marker, options = {}) { return tslib.__asyncGenerator(this, arguments, function* listSegments_1() { let listBlobsFlatSegmentResponse; if (!!marker || marker === undefined) { do { listBlobsFlatSegmentResponse = yield tslib.__await(this.listBlobFlatSegment(marker, options)); marker = listBlobsFlatSegmentResponse.continuationToken; yield yield tslib.__await(yield tslib.__await(listBlobsFlatSegmentResponse)); } while (marker); } }); } /** * Returns an AsyncIterableIterator of {@link BlobItem} objects * * @param options - Options to list blobs operation. */ listItems(options = {}) { return tslib.__asyncGenerator(this, arguments, function* listItems_1() { var e_1, _a; let marker; try { for (var _b = tslib.__asyncValues(this.listSegments(marker, options)), _c; _c = yield tslib.__await(_b.next()), !_c.done;) { const listBlobsFlatSegmentResponse = _c.value; yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(listBlobsFlatSegmentResponse.segment.blobItems))); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) yield tslib.__await(_a.call(_b)); } finally { if (e_1) throw e_1.error; } } }); } /** * Returns an async iterable iterator to list all the blobs * under the specified account. * * .byPage() returns an async iterable iterator to list the blobs in pages. * * Example using `for await` syntax: * * ```js * // Get the containerClient before you run these snippets, * // Can be obtained from `blobServiceClient.getContainerClient("");` * let i = 1; * for await (const blob of containerClient.listBlobsFlat()) { * console.log(`Blob ${i++}: ${blob.name}`); * } * ``` * * Example using `iter.next()`: * * ```js * let i = 1; * let iter = containerClient.listBlobsFlat(); * let blobItem = await iter.next(); * while (!blobItem.done) { * console.log(`Blob ${i++}: ${blobItem.value.name}`); * blobItem = await iter.next(); * } * ``` * * Example using `byPage()`: * * ```js * // passing optional maxPageSize in the page settings * let i = 1; * for await (const response of containerClient.listBlobsFlat().byPage({ maxPageSize: 20 })) { * for (const blob of response.segment.blobItems) { * console.log(`Blob ${i++}: ${blob.name}`); * } * } * ``` * * Example using paging with a marker: * * ```js * let i = 1; * let iterator = containerClient.listBlobsFlat().byPage({ maxPageSize: 2 }); * let response = (await iterator.next()).value; * * // Prints 2 blob names * for (const blob of response.segment.blobItems) { * console.log(`Blob ${i++}: ${blob.name}`); * } * * // Gets next marker * let marker = response.continuationToken; * * // Passing next marker as continuationToken * * iterator = containerClient.listBlobsFlat().byPage({ continuationToken: marker, maxPageSize: 10 }); * response = (await iterator.next()).value; * * // Prints 10 blob names * for (const blob of response.segment.blobItems) { * console.log(`Blob ${i++}: ${blob.name}`); * } * ``` * * @param options - Options to list blobs. * @returns An asyncIterableIterator that supports paging. */ listBlobsFlat(options = {}) { const include = []; if (options.includeCopy) { include.push("copy"); } if (options.includeDeleted) { include.push("deleted"); } if (options.includeMetadata) { include.push("metadata"); } if (options.includeSnapshots) { include.push("snapshots"); } if (options.includeVersions) { include.push("versions"); } if (options.includeUncommitedBlobs) { include.push("uncommittedblobs"); } if (options.includeTags) { include.push("tags"); } if (options.includeDeletedWithVersions) { include.push("deletedwithversions"); } if (options.includeImmutabilityPolicy) { include.push("immutabilitypolicy"); } if (options.includeLegalHold) { include.push("legalhold"); } if (options.prefix === "") { options.prefix = undefined; } const updatedOptions = Object.assign(Object.assign({}, options), (include.length > 0 ? { include: include } : {})); // AsyncIterableIterator to iterate over blobs const iter = this.listItems(updatedOptions); return { /** * The next method, part of the iteration protocol */ next() { return iter.next(); }, /** * The connection to the async iterator, part of the iteration protocol */ [Symbol.asyncIterator]() { return this; }, /** * Return an AsyncIterableIterator that works a page at a time */ byPage: (settings = {}) => { return this.listSegments(settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); }, }; } /** * Returns an AsyncIterableIterator for ContainerListBlobHierarchySegmentResponse * * @param delimiter - The character or string used to define the virtual hierarchy * @param marker - A string value that identifies the portion of * the list of blobs to be returned with the next listing operation. The * operation returns the ContinuationToken value within the response body if the * listing operation did not return all blobs remaining to be listed * with the current page. The ContinuationToken value can be used as the value for * the marker parameter in a subsequent call to request the next page of list * items. The marker value is opaque to the client. * @param options - Options to list blobs operation. */ listHierarchySegments(delimiter, marker, options = {}) { return tslib.__asyncGenerator(this, arguments, function* listHierarchySegments_1() { let listBlobsHierarchySegmentResponse; if (!!marker || marker === undefined) { do { listBlobsHierarchySegmentResponse = yield tslib.__await(this.listBlobHierarchySegment(delimiter, marker, options)); marker = listBlobsHierarchySegmentResponse.continuationToken; yield yield tslib.__await(yield tslib.__await(listBlobsHierarchySegmentResponse)); } while (marker); } }); } /** * Returns an AsyncIterableIterator for {@link BlobPrefix} and {@link BlobItem} objects. * * @param delimiter - The character or string used to define the virtual hierarchy * @param options - Options to list blobs operation. */ listItemsByHierarchy(delimiter, options = {}) { return tslib.__asyncGenerator(this, arguments, function* listItemsByHierarchy_1() { var e_2, _a; let marker; try { for (var _b = tslib.__asyncValues(this.listHierarchySegments(delimiter, marker, options)), _c; _c = yield tslib.__await(_b.next()), !_c.done;) { const listBlobsHierarchySegmentResponse = _c.value; const segment = listBlobsHierarchySegmentResponse.segment; if (segment.blobPrefixes) { for (const prefix of segment.blobPrefixes) { yield yield tslib.__await(Object.assign({ kind: "prefix" }, prefix)); } } for (const blob of segment.blobItems) { yield yield tslib.__await(Object.assign({ kind: "blob" }, blob)); } } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) yield tslib.__await(_a.call(_b)); } finally { if (e_2) throw e_2.error; } } }); } /** * Returns an async iterable iterator to list all the blobs by hierarchy. * under the specified account. * * .byPage() returns an async iterable iterator to list the blobs by hierarchy in pages. * * Example using `for await` syntax: * * ```js * for await (const item of containerClient.listBlobsByHierarchy("/")) { * if (item.kind === "prefix") { * console.log(`\tBlobPrefix: ${item.name}`); * } else { * console.log(`\tBlobItem: name - ${item.name}`); * } * } * ``` * * Example using `iter.next()`: * * ```js * let iter = containerClient.listBlobsByHierarchy("/", { prefix: "prefix1/" }); * let entity = await iter.next(); * while (!entity.done) { * let item = entity.value; * if (item.kind === "prefix") { * console.log(`\tBlobPrefix: ${item.name}`); * } else { * console.log(`\tBlobItem: name - ${item.name}`); * } * entity = await iter.next(); * } * ``` * * Example using `byPage()`: * * ```js * console.log("Listing blobs by hierarchy by page"); * for await (const response of containerClient.listBlobsByHierarchy("/").byPage()) { * const segment = response.segment; * if (segment.blobPrefixes) { * for (const prefix of segment.blobPrefixes) { * console.log(`\tBlobPrefix: ${prefix.name}`); * } * } * for (const blob of response.segment.blobItems) { * console.log(`\tBlobItem: name - ${blob.name}`); * } * } * ``` * * Example using paging with a max page size: * * ```js * console.log("Listing blobs by hierarchy by page, specifying a prefix and a max page size"); * * let i = 1; * for await (const response of containerClient * .listBlobsByHierarchy("/", { prefix: "prefix2/sub1/" }) * .byPage({ maxPageSize: 2 })) { * console.log(`Page ${i++}`); * const segment = response.segment; * * if (segment.blobPrefixes) { * for (const prefix of segment.blobPrefixes) { * console.log(`\tBlobPrefix: ${prefix.name}`); * } * } * * for (const blob of response.segment.blobItems) { * console.log(`\tBlobItem: name - ${blob.name}`); * } * } * ``` * * @param delimiter - The character or string used to define the virtual hierarchy * @param options - Options to list blobs operation. */ listBlobsByHierarchy(delimiter, options = {}) { if (delimiter === "") { throw new RangeError("delimiter should contain one or more characters"); } const include = []; if (options.includeCopy) { include.push("copy"); } if (options.includeDeleted) { include.push("deleted"); } if (options.includeMetadata) { include.push("metadata"); } if (options.includeSnapshots) { include.push("snapshots"); } if (options.includeVersions) { include.push("versions"); } if (options.includeUncommitedBlobs) { include.push("uncommittedblobs"); } if (options.includeTags) { include.push("tags"); } if (options.includeDeletedWithVersions) { include.push("deletedwithversions"); } if (options.includeImmutabilityPolicy) { include.push("immutabilitypolicy"); } if (options.includeLegalHold) { include.push("legalhold"); } if (options.prefix === "") { options.prefix = undefined; } const updatedOptions = Object.assign(Object.assign({}, options), (include.length > 0 ? { include: include } : {})); // AsyncIterableIterator to iterate over blob prefixes and blobs const iter = this.listItemsByHierarchy(delimiter, updatedOptions); return { /** * The next method, part of the iteration protocol */ async next() { return iter.next(); }, /** * The connection to the async iterator, part of the iteration protocol */ [Symbol.asyncIterator]() { return this; }, /** * Return an AsyncIterableIterator that works a page at a time */ byPage: (settings = {}) => { return this.listHierarchySegments(delimiter, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); }, }; } /** * The Filter Blobs operation enables callers to list blobs in the container whose tags * match a given search expression. * * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. * The given expression must evaluate to true for a blob to be returned in the results. * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; * however, only a subset of the OData filter syntax is supported in the Blob service. * @param marker - A string value that identifies the portion of * the list of blobs to be returned with the next listing operation. The * operation returns the continuationToken value within the response body if the * listing operation did not return all blobs remaining to be listed * with the current page. The continuationToken value can be used as the value for * the marker parameter in a subsequent call to request the next page of list * items. The marker value is opaque to the client. * @param options - Options to find blobs by tags. */ async findBlobsByTagsSegment(tagFilterSqlExpression, marker, options = {}) { const { span, updatedOptions } = createSpan("ContainerClient-findBlobsByTagsSegment", options); try { const response = await this.containerContext.filterBlobs(Object.assign({ abortSignal: options.abortSignal, where: tagFilterSqlExpression, marker, maxPageSize: options.maxPageSize }, convertTracingToRequestOptionsBase(updatedOptions))); const wrappedResponse = Object.assign(Object.assign({}, response), { _response: response._response, blobs: response.blobs.map((blob) => { var _a; let tagValue = ""; if (((_a = blob.tags) === null || _a === void 0 ? void 0 : _a.blobTagSet.length) === 1) { tagValue = blob.tags.blobTagSet[0].value; } return Object.assign(Object.assign({}, blob), { tags: toTags(blob.tags), tagValue }); }) }); return wrappedResponse; } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Returns an AsyncIterableIterator for ContainerFindBlobsByTagsSegmentResponse. * * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. * The given expression must evaluate to true for a blob to be returned in the results. * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; * however, only a subset of the OData filter syntax is supported in the Blob service. * @param marker - A string value that identifies the portion of * the list of blobs to be returned with the next listing operation. The * operation returns the continuationToken value within the response body if the * listing operation did not return all blobs remaining to be listed * with the current page. The continuationToken value can be used as the value for * the marker parameter in a subsequent call to request the next page of list * items. The marker value is opaque to the client. * @param options - Options to find blobs by tags. */ findBlobsByTagsSegments(tagFilterSqlExpression, marker, options = {}) { return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsSegments_1() { let response; if (!!marker || marker === undefined) { do { response = yield tslib.__await(this.findBlobsByTagsSegment(tagFilterSqlExpression, marker, options)); response.blobs = response.blobs || []; marker = response.continuationToken; yield yield tslib.__await(response); } while (marker); } }); } /** * Returns an AsyncIterableIterator for blobs. * * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. * The given expression must evaluate to true for a blob to be returned in the results. * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; * however, only a subset of the OData filter syntax is supported in the Blob service. * @param options - Options to findBlobsByTagsItems. */ findBlobsByTagsItems(tagFilterSqlExpression, options = {}) { return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsItems_1() { var e_3, _a; let marker; try { for (var _b = tslib.__asyncValues(this.findBlobsByTagsSegments(tagFilterSqlExpression, marker, options)), _c; _c = yield tslib.__await(_b.next()), !_c.done;) { const segment = _c.value; yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(segment.blobs))); } } catch (e_3_1) { e_3 = { error: e_3_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) yield tslib.__await(_a.call(_b)); } finally { if (e_3) throw e_3.error; } } }); } /** * Returns an async iterable iterator to find all blobs with specified tag * under the specified container. * * .byPage() returns an async iterable iterator to list the blobs in pages. * * Example using `for await` syntax: * * ```js * let i = 1; * for await (const blob of containerClient.findBlobsByTags("tagkey='tagvalue'")) { * console.log(`Blob ${i++}: ${blob.name}`); * } * ``` * * Example using `iter.next()`: * * ```js * let i = 1; * const iter = containerClient.findBlobsByTags("tagkey='tagvalue'"); * let blobItem = await iter.next(); * while (!blobItem.done) { * console.log(`Blob ${i++}: ${blobItem.value.name}`); * blobItem = await iter.next(); * } * ``` * * Example using `byPage()`: * * ```js * // passing optional maxPageSize in the page settings * let i = 1; * for await (const response of containerClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 20 })) { * if (response.blobs) { * for (const blob of response.blobs) { * console.log(`Blob ${i++}: ${blob.name}`); * } * } * } * ``` * * Example using paging with a marker: * * ```js * let i = 1; * let iterator = containerClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 2 }); * let response = (await iterator.next()).value; * * // Prints 2 blob names * if (response.blobs) { * for (const blob of response.blobs) { * console.log(`Blob ${i++}: ${blob.name}`); * } * } * * // Gets next marker * let marker = response.continuationToken; * // Passing next marker as continuationToken * iterator = containerClient * .findBlobsByTags("tagkey='tagvalue'") * .byPage({ continuationToken: marker, maxPageSize: 10 }); * response = (await iterator.next()).value; * * // Prints blob names * if (response.blobs) { * for (const blob of response.blobs) { * console.log(`Blob ${i++}: ${blob.name}`); * } * } * ``` * * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. * The given expression must evaluate to true for a blob to be returned in the results. * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; * however, only a subset of the OData filter syntax is supported in the Blob service. * @param options - Options to find blobs by tags. */ findBlobsByTags(tagFilterSqlExpression, options = {}) { // AsyncIterableIterator to iterate over blobs const listSegmentOptions = Object.assign({}, options); const iter = this.findBlobsByTagsItems(tagFilterSqlExpression, listSegmentOptions); return { /** * The next method, part of the iteration protocol */ next() { return iter.next(); }, /** * The connection to the async iterator, part of the iteration protocol */ [Symbol.asyncIterator]() { return this; }, /** * Return an AsyncIterableIterator that works a page at a time */ byPage: (settings = {}) => { return this.findBlobsByTagsSegments(tagFilterSqlExpression, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); }, }; } getContainerNameFromUrl() { let containerName; try { // URL may look like the following // "https://myaccount.blob.core.windows.net/mycontainer?sasString"; // "https://myaccount.blob.core.windows.net/mycontainer"; // IPv4/IPv6 address hosts, Endpoints - `http://127.0.0.1:10000/devstoreaccount1/containername` // http://localhost:10001/devstoreaccount1/containername const parsedUrl = coreHttp.URLBuilder.parse(this.url); if (parsedUrl.getHost().split(".")[1] === "blob") { // "https://myaccount.blob.core.windows.net/containername". // "https://customdomain.com/containername". // .getPath() -> /containername containerName = parsedUrl.getPath().split("/")[1]; } else if (isIpEndpointStyle(parsedUrl)) { // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/containername // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/containername // .getPath() -> /devstoreaccount1/containername containerName = parsedUrl.getPath().split("/")[2]; } else { // "https://customdomain.com/containername". // .getPath() -> /containername containerName = parsedUrl.getPath().split("/")[1]; } // decode the encoded containerName - to get all the special characters that might be present in it containerName = decodeURIComponent(containerName); if (!containerName) { throw new Error("Provided containerName is invalid."); } return containerName; } catch (error) { throw new Error("Unable to extract containerName with provided information."); } } /** * Only available for ContainerClient constructed with a shared key credential. * * Generates a Blob Container Service Shared Access Signature (SAS) URI based on the client properties * and parameters passed in. The SAS is signed by the shared key credential of the client. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas * * @param options - Optional parameters. * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ generateSasUrl(options) { return new Promise((resolve) => { if (!(this.credential instanceof StorageSharedKeyCredential)) { throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); } const sas = generateBlobSASQueryParameters(Object.assign({ containerName: this._containerName }, options), this.credential).toString(); resolve(appendToURLQuery(this.url, sas)); }); } /** * Creates a BlobBatchClient object to conduct batch operations. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch * * @returns A new BlobBatchClient object for this container. */ getBlobBatchClient() { return new BlobBatchClient(this.url, this.pipeline); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * This is a helper class to construct a string representing the permissions granted by an AccountSAS. Setting a value * to true means that any SAS which uses these permissions will grant permissions for that operation. Once all the * values are set, this should be serialized with toString and set as the permissions field on an * {@link AccountSASSignatureValues} object. It is possible to construct the permissions string without this class, but * the order of the permissions is particular and this class guarantees correctness. */ class AccountSASPermissions { constructor() { /** * Permission to read resources and list queues and tables granted. */ this.read = false; /** * Permission to write resources granted. */ this.write = false; /** * Permission to create blobs and files granted. */ this.delete = false; /** * Permission to delete versions granted. */ this.deleteVersion = false; /** * Permission to list blob containers, blobs, shares, directories, and files granted. */ this.list = false; /** * Permission to add messages, table entities, and append to blobs granted. */ this.add = false; /** * Permission to create blobs and files granted. */ this.create = false; /** * Permissions to update messages and table entities granted. */ this.update = false; /** * Permission to get and delete messages granted. */ this.process = false; /** * Specfies Tag access granted. */ this.tag = false; /** * Permission to filter blobs. */ this.filter = false; /** * Permission to set immutability policy. */ this.setImmutabilityPolicy = false; /** * Specifies that Permanent Delete is permitted. */ this.permanentDelete = false; } /** * Parse initializes the AccountSASPermissions fields from a string. * * @param permissions - */ static parse(permissions) { const accountSASPermissions = new AccountSASPermissions(); for (const c of permissions) { switch (c) { case "r": accountSASPermissions.read = true; break; case "w": accountSASPermissions.write = true; break; case "d": accountSASPermissions.delete = true; break; case "x": accountSASPermissions.deleteVersion = true; break; case "l": accountSASPermissions.list = true; break; case "a": accountSASPermissions.add = true; break; case "c": accountSASPermissions.create = true; break; case "u": accountSASPermissions.update = true; break; case "p": accountSASPermissions.process = true; break; case "t": accountSASPermissions.tag = true; break; case "f": accountSASPermissions.filter = true; break; case "i": accountSASPermissions.setImmutabilityPolicy = true; break; case "y": accountSASPermissions.permanentDelete = true; break; default: throw new RangeError(`Invalid permission character: ${c}`); } } return accountSASPermissions; } /** * Creates a {@link AccountSASPermissions} from a raw object which contains same keys as it * and boolean values for them. * * @param permissionLike - */ static from(permissionLike) { const accountSASPermissions = new AccountSASPermissions(); if (permissionLike.read) { accountSASPermissions.read = true; } if (permissionLike.write) { accountSASPermissions.write = true; } if (permissionLike.delete) { accountSASPermissions.delete = true; } if (permissionLike.deleteVersion) { accountSASPermissions.deleteVersion = true; } if (permissionLike.filter) { accountSASPermissions.filter = true; } if (permissionLike.tag) { accountSASPermissions.tag = true; } if (permissionLike.list) { accountSASPermissions.list = true; } if (permissionLike.add) { accountSASPermissions.add = true; } if (permissionLike.create) { accountSASPermissions.create = true; } if (permissionLike.update) { accountSASPermissions.update = true; } if (permissionLike.process) { accountSASPermissions.process = true; } if (permissionLike.setImmutabilityPolicy) { accountSASPermissions.setImmutabilityPolicy = true; } if (permissionLike.permanentDelete) { accountSASPermissions.permanentDelete = true; } return accountSASPermissions; } /** * Produces the SAS permissions string for an Azure Storage account. * Call this method to set AccountSASSignatureValues Permissions field. * * Using this method will guarantee the resource types are in * an order accepted by the service. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas * */ toString() { // The order of the characters should be as specified here to ensure correctness: // https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas // Use a string array instead of string concatenating += operator for performance const permissions = []; if (this.read) { permissions.push("r"); } if (this.write) { permissions.push("w"); } if (this.delete) { permissions.push("d"); } if (this.deleteVersion) { permissions.push("x"); } if (this.filter) { permissions.push("f"); } if (this.tag) { permissions.push("t"); } if (this.list) { permissions.push("l"); } if (this.add) { permissions.push("a"); } if (this.create) { permissions.push("c"); } if (this.update) { permissions.push("u"); } if (this.process) { permissions.push("p"); } if (this.setImmutabilityPolicy) { permissions.push("i"); } if (this.permanentDelete) { permissions.push("y"); } return permissions.join(""); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * This is a helper class to construct a string representing the resources accessible by an AccountSAS. Setting a value * to true means that any SAS which uses these permissions will grant access to that resource type. Once all the * values are set, this should be serialized with toString and set as the resources field on an * {@link AccountSASSignatureValues} object. It is possible to construct the resources string without this class, but * the order of the resources is particular and this class guarantees correctness. */ class AccountSASResourceTypes { constructor() { /** * Permission to access service level APIs granted. */ this.service = false; /** * Permission to access container level APIs (Blob Containers, Tables, Queues, File Shares) granted. */ this.container = false; /** * Permission to access object level APIs (Blobs, Table Entities, Queue Messages, Files) granted. */ this.object = false; } /** * Creates an {@link AccountSASResourceTypes} from the specified resource types string. This method will throw an * Error if it encounters a character that does not correspond to a valid resource type. * * @param resourceTypes - */ static parse(resourceTypes) { const accountSASResourceTypes = new AccountSASResourceTypes(); for (const c of resourceTypes) { switch (c) { case "s": accountSASResourceTypes.service = true; break; case "c": accountSASResourceTypes.container = true; break; case "o": accountSASResourceTypes.object = true; break; default: throw new RangeError(`Invalid resource type: ${c}`); } } return accountSASResourceTypes; } /** * Converts the given resource types to a string. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas * */ toString() { const resourceTypes = []; if (this.service) { resourceTypes.push("s"); } if (this.container) { resourceTypes.push("c"); } if (this.object) { resourceTypes.push("o"); } return resourceTypes.join(""); } } // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * This is a helper class to construct a string representing the services accessible by an AccountSAS. Setting a value * to true means that any SAS which uses these permissions will grant access to that service. Once all the * values are set, this should be serialized with toString and set as the services field on an * {@link AccountSASSignatureValues} object. It is possible to construct the services string without this class, but * the order of the services is particular and this class guarantees correctness. */ class AccountSASServices { constructor() { /** * Permission to access blob resources granted. */ this.blob = false; /** * Permission to access file resources granted. */ this.file = false; /** * Permission to access queue resources granted. */ this.queue = false; /** * Permission to access table resources granted. */ this.table = false; } /** * Creates an {@link AccountSASServices} from the specified services string. This method will throw an * Error if it encounters a character that does not correspond to a valid service. * * @param services - */ static parse(services) { const accountSASServices = new AccountSASServices(); for (const c of services) { switch (c) { case "b": accountSASServices.blob = true; break; case "f": accountSASServices.file = true; break; case "q": accountSASServices.queue = true; break; case "t": accountSASServices.table = true; break; default: throw new RangeError(`Invalid service character: ${c}`); } } return accountSASServices; } /** * Converts the given services to a string. * */ toString() { const services = []; if (this.blob) { services.push("b"); } if (this.table) { services.push("t"); } if (this.queue) { services.push("q"); } if (this.file) { services.push("f"); } return services.join(""); } } // Copyright (c) Microsoft Corporation. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * Generates a {@link SASQueryParameters} object which contains all SAS query parameters needed to make an actual * REST request. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas * * @param accountSASSignatureValues - * @param sharedKeyCredential - */ function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyCredential) { const version = accountSASSignatureValues.version ? accountSASSignatureValues.version : SERVICE_VERSION; if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.setImmutabilityPolicy && version < "2020-08-04") { throw RangeError("'version' must be >= '2020-08-04' when provided 'i' permission."); } if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.deleteVersion && version < "2019-10-10") { throw RangeError("'version' must be >= '2019-10-10' when provided 'x' permission."); } if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.permanentDelete && version < "2019-10-10") { throw RangeError("'version' must be >= '2019-10-10' when provided 'y' permission."); } if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.tag && version < "2019-12-12") { throw RangeError("'version' must be >= '2019-12-12' when provided 't' permission."); } if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.filter && version < "2019-12-12") { throw RangeError("'version' must be >= '2019-12-12' when provided 'f' permission."); } if (accountSASSignatureValues.encryptionScope && version < "2020-12-06") { throw RangeError("'version' must be >= '2020-12-06' when provided 'encryptionScope' in SAS."); } const parsedPermissions = AccountSASPermissions.parse(accountSASSignatureValues.permissions.toString()); const parsedServices = AccountSASServices.parse(accountSASSignatureValues.services).toString(); const parsedResourceTypes = AccountSASResourceTypes.parse(accountSASSignatureValues.resourceTypes).toString(); let stringToSign; if (version >= "2020-12-06") { stringToSign = [ sharedKeyCredential.accountName, parsedPermissions, parsedServices, parsedResourceTypes, accountSASSignatureValues.startsOn ? truncatedISO8061Date(accountSASSignatureValues.startsOn, false) : "", truncatedISO8061Date(accountSASSignatureValues.expiresOn, false), accountSASSignatureValues.ipRange ? ipRangeToString(accountSASSignatureValues.ipRange) : "", accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "", version, accountSASSignatureValues.encryptionScope ? accountSASSignatureValues.encryptionScope : "", "", // Account SAS requires an additional newline character ].join("\n"); } else { stringToSign = [ sharedKeyCredential.accountName, parsedPermissions, parsedServices, parsedResourceTypes, accountSASSignatureValues.startsOn ? truncatedISO8061Date(accountSASSignatureValues.startsOn, false) : "", truncatedISO8061Date(accountSASSignatureValues.expiresOn, false), accountSASSignatureValues.ipRange ? ipRangeToString(accountSASSignatureValues.ipRange) : "", accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "", version, "", // Account SAS requires an additional newline character ].join("\n"); } const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); return new SASQueryParameters(version, signature, parsedPermissions.toString(), parsedServices, parsedResourceTypes, accountSASSignatureValues.protocol, accountSASSignatureValues.startsOn, accountSASSignatureValues.expiresOn, accountSASSignatureValues.ipRange, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, accountSASSignatureValues.encryptionScope); } /** * A BlobServiceClient represents a Client to the Azure Storage Blob service allowing you * to manipulate blob containers. */ class BlobServiceClient extends StorageClient { constructor(url, credentialOrPipeline, // Legacy, no fix for eslint error without breaking. Disable it for this interface. /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ options) { let pipeline; if (isPipelineLike(credentialOrPipeline)) { pipeline = credentialOrPipeline; } else if ((coreHttp.isNode && credentialOrPipeline instanceof StorageSharedKeyCredential) || credentialOrPipeline instanceof AnonymousCredential || coreHttp.isTokenCredential(credentialOrPipeline)) { pipeline = newPipeline(credentialOrPipeline, options); } else { // The second parameter is undefined. Use anonymous credential pipeline = newPipeline(new AnonymousCredential(), options); } super(url, pipeline); this.serviceContext = new Service(this.storageClientContext); } /** * * Creates an instance of BlobServiceClient from connection string. * * @param connectionString - Account connection string or a SAS connection string of an Azure storage account. * [ Note - Account connection string can only be used in NODE.JS runtime. ] * Account connection string example - * `DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=accountKey;EndpointSuffix=core.windows.net` * SAS connection string example - * `BlobEndpoint=https://myaccount.blob.core.windows.net/;QueueEndpoint=https://myaccount.queue.core.windows.net/;FileEndpoint=https://myaccount.file.core.windows.net/;TableEndpoint=https://myaccount.table.core.windows.net/;SharedAccessSignature=sasString` * @param options - Optional. Options to configure the HTTP pipeline. */ static fromConnectionString(connectionString, // Legacy, no fix for eslint error without breaking. Disable it for this interface. /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ options) { options = options || {}; const extractedCreds = extractConnectionStringParts(connectionString); if (extractedCreds.kind === "AccountConnString") { if (coreHttp.isNode) { const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); if (!options.proxyOptions) { options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); } const pipeline = newPipeline(sharedKeyCredential, options); return new BlobServiceClient(extractedCreds.url, pipeline); } else { throw new Error("Account connection string is only supported in Node.js environment"); } } else if (extractedCreds.kind === "SASConnString") { const pipeline = newPipeline(new AnonymousCredential(), options); return new BlobServiceClient(extractedCreds.url + "?" + extractedCreds.accountSas, pipeline); } else { throw new Error("Connection string must be either an Account connection string or a SAS connection string"); } } /** * Creates a {@link ContainerClient} object * * @param containerName - A container name * @returns A new ContainerClient object for the given container name. * * Example usage: * * ```js * const containerClient = blobServiceClient.getContainerClient(""); * ``` */ getContainerClient(containerName) { return new ContainerClient(appendToURLPath(this.url, encodeURIComponent(containerName)), this.pipeline); } /** * 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. * @returns Container creation response and the corresponding container client. */ async createContainer(containerName, options = {}) { const { span, updatedOptions } = createSpan("BlobServiceClient-createContainer", options); try { const containerClient = this.getContainerClient(containerName); const containerCreateResponse = await containerClient.create(updatedOptions); return { containerClient, containerCreateResponse, }; } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Deletes a Blob container. * * @param containerName - Name of the container to delete. * @param options - Options to configure Container Delete operation. * @returns Container deletion response. */ async deleteContainer(containerName, options = {}) { const { span, updatedOptions } = createSpan("BlobServiceClient-deleteContainer", options); try { const containerClient = this.getContainerClient(containerName); return await containerClient.delete(updatedOptions); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Restore a previously deleted Blob container. * This API is only functional if Container Soft Delete is enabled for the storage account associated with the container. * * @param deletedContainerName - Name of the previously deleted container. * @param deletedContainerVersion - Version of the previously deleted container, used to uniquely identify the deleted container. * @param options - Options to configure Container Restore operation. * @returns Container deletion response. */ async undeleteContainer(deletedContainerName, deletedContainerVersion, options = {}) { const { span, updatedOptions } = createSpan("BlobServiceClient-undeleteContainer", options); try { const containerClient = this.getContainerClient(options.destinationContainerName || deletedContainerName); // Hack to access a protected member. const containerContext = new Container(containerClient["storageClientContext"]); const containerUndeleteResponse = await containerContext.restore(Object.assign({ deletedContainerName, deletedContainerVersion }, updatedOptions)); return { containerClient, containerUndeleteResponse }; } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Rename an existing Blob Container. * * @param sourceContainerName - The name of the source container. * @param destinationContainerName - The new name of the container. * @param options - Options to configure Container Rename operation. */ /* eslint-disable-next-line @typescript-eslint/ban-ts-comment */ // @ts-ignore Need to hide this interface for now. Make it public and turn on the live tests for it when the service is ready. async renameContainer(sourceContainerName, destinationContainerName, options = {}) { var _a; const { span, updatedOptions } = createSpan("BlobServiceClient-renameContainer", options); try { const containerClient = this.getContainerClient(destinationContainerName); // Hack to access a protected member. const containerContext = new Container(containerClient["storageClientContext"]); const containerRenameResponse = await containerContext.rename(sourceContainerName, Object.assign(Object.assign({}, updatedOptions), { sourceLeaseId: (_a = options.sourceCondition) === null || _a === void 0 ? void 0 : _a.leaseId })); return { containerClient, containerRenameResponse }; } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Gets the properties of a storage account’s Blob service, including properties * for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties * * @param options - Options to the Service Get Properties operation. * @returns Response data for the Service Get Properties operation. */ async getProperties(options = {}) { const { span, updatedOptions } = createSpan("BlobServiceClient-getProperties", options); try { return await this.serviceContext.getProperties(Object.assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Sets properties for a storage account’s Blob service endpoint, including properties * for Storage Analytics, CORS (Cross-Origin Resource Sharing) rules and soft delete settings. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-service-properties * * @param properties - * @param options - Options to the Service Set Properties operation. * @returns Response data for the Service Set Properties operation. */ async setProperties(properties, options = {}) { const { span, updatedOptions } = createSpan("BlobServiceClient-setProperties", options); try { return await this.serviceContext.setProperties(properties, Object.assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Retrieves statistics related to replication for the Blob service. It is only * available on the secondary location endpoint when read-access geo-redundant * replication is enabled for the storage account. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-stats * * @param options - Options to the Service Get Statistics operation. * @returns Response data for the Service Get Statistics operation. */ async getStatistics(options = {}) { const { span, updatedOptions } = createSpan("BlobServiceClient-getStatistics", options); try { return await this.serviceContext.getStatistics(Object.assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * The Get Account Information operation returns the sku name and account kind * for the specified account. * The Get Account Information operation is available on service versions beginning * with version 2018-03-28. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-account-information * * @param options - Options to the Service Get Account Info operation. * @returns Response data for the Service Get Account Info operation. */ async getAccountInfo(options = {}) { const { span, updatedOptions } = createSpan("BlobServiceClient-getAccountInfo", options); try { return await this.serviceContext.getAccountInfo(Object.assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Returns a list of the containers under the specified account. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/list-containers2 * * @param marker - A string value that identifies the portion of * the list of containers to be returned with the next listing operation. The * operation returns the continuationToken value within the response body if the * listing operation did not return all containers remaining to be listed * with the current page. The continuationToken value can be used as the value for * the marker parameter in a subsequent call to request the next page of list * items. The marker value is opaque to the client. * @param options - Options to the Service List Container Segment operation. * @returns Response data for the Service List Container Segment operation. */ async listContainersSegment(marker, options = {}) { const { span, updatedOptions } = createSpan("BlobServiceClient-listContainersSegment", options); try { return await this.serviceContext.listContainersSegment(Object.assign(Object.assign(Object.assign({ abortSignal: options.abortSignal, marker }, options), { include: typeof options.include === "string" ? [options.include] : options.include }), convertTracingToRequestOptionsBase(updatedOptions))); } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * The Filter Blobs operation enables callers to list blobs across all containers whose tags * match a given search expression. Filter blobs searches across all containers within a * storage account but can be scoped within the expression to a single container. * * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. * The given expression must evaluate to true for a blob to be returned in the results. * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; * however, only a subset of the OData filter syntax is supported in the Blob service. * @param marker - A string value that identifies the portion of * the list of blobs to be returned with the next listing operation. The * operation returns the continuationToken value within the response body if the * listing operation did not return all blobs remaining to be listed * with the current page. The continuationToken value can be used as the value for * the marker parameter in a subsequent call to request the next page of list * items. The marker value is opaque to the client. * @param options - Options to find blobs by tags. */ async findBlobsByTagsSegment(tagFilterSqlExpression, marker, options = {}) { const { span, updatedOptions } = createSpan("BlobServiceClient-findBlobsByTagsSegment", options); try { const response = await this.serviceContext.filterBlobs(Object.assign({ abortSignal: options.abortSignal, where: tagFilterSqlExpression, marker, maxPageSize: options.maxPageSize }, convertTracingToRequestOptionsBase(updatedOptions))); const wrappedResponse = Object.assign(Object.assign({}, response), { _response: response._response, blobs: response.blobs.map((blob) => { var _a; let tagValue = ""; if (((_a = blob.tags) === null || _a === void 0 ? void 0 : _a.blobTagSet.length) === 1) { tagValue = blob.tags.blobTagSet[0].value; } return Object.assign(Object.assign({}, blob), { tags: toTags(blob.tags), tagValue }); }) }); return wrappedResponse; } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Returns an AsyncIterableIterator for ServiceFindBlobsByTagsSegmentResponse. * * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. * The given expression must evaluate to true for a blob to be returned in the results. * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; * however, only a subset of the OData filter syntax is supported in the Blob service. * @param marker - A string value that identifies the portion of * the list of blobs to be returned with the next listing operation. The * operation returns the continuationToken value within the response body if the * listing operation did not return all blobs remaining to be listed * with the current page. The continuationToken value can be used as the value for * the marker parameter in a subsequent call to request the next page of list * items. The marker value is opaque to the client. * @param options - Options to find blobs by tags. */ findBlobsByTagsSegments(tagFilterSqlExpression, marker, options = {}) { return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsSegments_1() { let response; if (!!marker || marker === undefined) { do { response = yield tslib.__await(this.findBlobsByTagsSegment(tagFilterSqlExpression, marker, options)); response.blobs = response.blobs || []; marker = response.continuationToken; yield yield tslib.__await(response); } while (marker); } }); } /** * Returns an AsyncIterableIterator for blobs. * * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. * The given expression must evaluate to true for a blob to be returned in the results. * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; * however, only a subset of the OData filter syntax is supported in the Blob service. * @param options - Options to findBlobsByTagsItems. */ findBlobsByTagsItems(tagFilterSqlExpression, options = {}) { return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsItems_1() { var e_1, _a; let marker; try { for (var _b = tslib.__asyncValues(this.findBlobsByTagsSegments(tagFilterSqlExpression, marker, options)), _c; _c = yield tslib.__await(_b.next()), !_c.done;) { const segment = _c.value; yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(segment.blobs))); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) yield tslib.__await(_a.call(_b)); } finally { if (e_1) throw e_1.error; } } }); } /** * Returns an async iterable iterator to find all blobs with specified tag * under the specified account. * * .byPage() returns an async iterable iterator to list the blobs in pages. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties * * Example using `for await` syntax: * * ```js * let i = 1; * for await (const blob of blobServiceClient.findBlobsByTags("tagkey='tagvalue'")) { * console.log(`Blob ${i++}: ${container.name}`); * } * ``` * * Example using `iter.next()`: * * ```js * let i = 1; * const iter = blobServiceClient.findBlobsByTags("tagkey='tagvalue'"); * let blobItem = await iter.next(); * while (!blobItem.done) { * console.log(`Blob ${i++}: ${blobItem.value.name}`); * blobItem = await iter.next(); * } * ``` * * Example using `byPage()`: * * ```js * // passing optional maxPageSize in the page settings * let i = 1; * for await (const response of blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 20 })) { * if (response.blobs) { * for (const blob of response.blobs) { * console.log(`Blob ${i++}: ${blob.name}`); * } * } * } * ``` * * Example using paging with a marker: * * ```js * let i = 1; * let iterator = blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 2 }); * let response = (await iterator.next()).value; * * // Prints 2 blob names * if (response.blobs) { * for (const blob of response.blobs) { * console.log(`Blob ${i++}: ${blob.name}`); * } * } * * // Gets next marker * let marker = response.continuationToken; * // Passing next marker as continuationToken * iterator = blobServiceClient * .findBlobsByTags("tagkey='tagvalue'") * .byPage({ continuationToken: marker, maxPageSize: 10 }); * response = (await iterator.next()).value; * * // Prints blob names * if (response.blobs) { * for (const blob of response.blobs) { * console.log(`Blob ${i++}: ${blob.name}`); * } * } * ``` * * @param tagFilterSqlExpression - The where parameter enables the caller to query blobs whose tags match a given expression. * The given expression must evaluate to true for a blob to be returned in the results. * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; * however, only a subset of the OData filter syntax is supported in the Blob service. * @param options - Options to find blobs by tags. */ findBlobsByTags(tagFilterSqlExpression, options = {}) { // AsyncIterableIterator to iterate over blobs const listSegmentOptions = Object.assign({}, options); const iter = this.findBlobsByTagsItems(tagFilterSqlExpression, listSegmentOptions); return { /** * The next method, part of the iteration protocol */ next() { return iter.next(); }, /** * The connection to the async iterator, part of the iteration protocol */ [Symbol.asyncIterator]() { return this; }, /** * Return an AsyncIterableIterator that works a page at a time */ byPage: (settings = {}) => { return this.findBlobsByTagsSegments(tagFilterSqlExpression, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); }, }; } /** * Returns an AsyncIterableIterator for ServiceListContainersSegmentResponses * * @param marker - A string value that identifies the portion of * the list of containers to be returned with the next listing operation. The * operation returns the continuationToken value within the response body if the * listing operation did not return all containers remaining to be listed * with the current page. The continuationToken value can be used as the value for * the marker parameter in a subsequent call to request the next page of list * items. The marker value is opaque to the client. * @param options - Options to list containers operation. */ listSegments(marker, options = {}) { return tslib.__asyncGenerator(this, arguments, function* listSegments_1() { let listContainersSegmentResponse; if (!!marker || marker === undefined) { do { listContainersSegmentResponse = yield tslib.__await(this.listContainersSegment(marker, options)); listContainersSegmentResponse.containerItems = listContainersSegmentResponse.containerItems || []; marker = listContainersSegmentResponse.continuationToken; yield yield tslib.__await(yield tslib.__await(listContainersSegmentResponse)); } while (marker); } }); } /** * Returns an AsyncIterableIterator for Container Items * * @param options - Options to list containers operation. */ listItems(options = {}) { return tslib.__asyncGenerator(this, arguments, function* listItems_1() { var e_2, _a; let marker; try { for (var _b = tslib.__asyncValues(this.listSegments(marker, options)), _c; _c = yield tslib.__await(_b.next()), !_c.done;) { const segment = _c.value; yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(segment.containerItems))); } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) yield tslib.__await(_a.call(_b)); } finally { if (e_2) throw e_2.error; } } }); } /** * Returns an async iterable iterator to list all the containers * under the specified account. * * .byPage() returns an async iterable iterator to list the containers in pages. * * Example using `for await` syntax: * * ```js * let i = 1; * for await (const container of blobServiceClient.listContainers()) { * console.log(`Container ${i++}: ${container.name}`); * } * ``` * * Example using `iter.next()`: * * ```js * let i = 1; * const iter = blobServiceClient.listContainers(); * let containerItem = await iter.next(); * while (!containerItem.done) { * console.log(`Container ${i++}: ${containerItem.value.name}`); * containerItem = await iter.next(); * } * ``` * * Example using `byPage()`: * * ```js * // passing optional maxPageSize in the page settings * let i = 1; * for await (const response of blobServiceClient.listContainers().byPage({ maxPageSize: 20 })) { * if (response.containerItems) { * for (const container of response.containerItems) { * console.log(`Container ${i++}: ${container.name}`); * } * } * } * ``` * * Example using paging with a marker: * * ```js * let i = 1; * let iterator = blobServiceClient.listContainers().byPage({ maxPageSize: 2 }); * let response = (await iterator.next()).value; * * // Prints 2 container names * if (response.containerItems) { * for (const container of response.containerItems) { * console.log(`Container ${i++}: ${container.name}`); * } * } * * // Gets next marker * let marker = response.continuationToken; * // Passing next marker as continuationToken * iterator = blobServiceClient * .listContainers() * .byPage({ continuationToken: marker, maxPageSize: 10 }); * response = (await iterator.next()).value; * * // Prints 10 container names * if (response.containerItems) { * for (const container of response.containerItems) { * console.log(`Container ${i++}: ${container.name}`); * } * } * ``` * * @param options - Options to list containers. * @returns An asyncIterableIterator that supports paging. */ listContainers(options = {}) { if (options.prefix === "") { options.prefix = undefined; } const include = []; if (options.includeDeleted) { include.push("deleted"); } if (options.includeMetadata) { include.push("metadata"); } if (options.includeSystem) { include.push("system"); } // AsyncIterableIterator to iterate over containers const listSegmentOptions = Object.assign(Object.assign({}, options), (include.length > 0 ? { include } : {})); const iter = this.listItems(listSegmentOptions); return { /** * The next method, part of the iteration protocol */ next() { return iter.next(); }, /** * The connection to the async iterator, part of the iteration protocol */ [Symbol.asyncIterator]() { return this; }, /** * Return an AsyncIterableIterator that works a page at a time */ byPage: (settings = {}) => { return this.listSegments(settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); }, }; } /** * ONLY AVAILABLE WHEN USING BEARER TOKEN AUTHENTICATION (TokenCredential). * * Retrieves a user delegation key for the Blob service. This is only a valid operation when using * bearer token authentication. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-user-delegation-key * * @param startsOn - The start time for the user delegation SAS. Must be within 7 days of the current time * @param expiresOn - The end time for the user delegation SAS. Must be within 7 days of the current time */ async getUserDelegationKey(startsOn, expiresOn, options = {}) { const { span, updatedOptions } = createSpan("BlobServiceClient-getUserDelegationKey", options); try { const response = await this.serviceContext.getUserDelegationKey({ startsOn: truncatedISO8061Date(startsOn, false), expiresOn: truncatedISO8061Date(expiresOn, false), }, Object.assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); const userDelegationKey = { signedObjectId: response.signedObjectId, signedTenantId: response.signedTenantId, signedStartsOn: new Date(response.signedStartsOn), signedExpiresOn: new Date(response.signedExpiresOn), signedService: response.signedService, signedVersion: response.signedVersion, value: response.value, }; const res = Object.assign({ _response: response._response, requestId: response.requestId, clientRequestId: response.clientRequestId, version: response.version, date: response.date, errorCode: response.errorCode }, userDelegationKey); return res; } catch (e) { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, message: e.message, }); throw e; } finally { span.end(); } } /** * Creates a BlobBatchClient object to conduct batch operations. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch * * @returns A new BlobBatchClient object for this service. */ getBlobBatchClient() { return new BlobBatchClient(this.url, this.pipeline); } /** * Only available for BlobServiceClient constructed with a shared key credential. * * Generates a Blob account Shared Access Signature (SAS) URI based on the client properties * and parameters passed in. The SAS is signed by the shared key credential of the client. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-account-sas * * @param expiresOn - Optional. The time at which the shared access signature becomes invalid. Default to an hour later if not provided. * @param permissions - Specifies the list of permissions to be associated with the SAS. * @param resourceTypes - Specifies the resource types associated with the shared access signature. * @param options - Optional parameters. * @returns An account SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ generateAccountSasUrl(expiresOn, permissions = AccountSASPermissions.parse("r"), resourceTypes = "sco", options = {}) { if (!(this.credential instanceof StorageSharedKeyCredential)) { throw RangeError("Can only generate the account SAS when the client is initialized with a shared key credential"); } if (expiresOn === undefined) { const now = new Date(); expiresOn = new Date(now.getTime() + 3600 * 1000); } const sas = generateAccountSASQueryParameters(Object.assign({ permissions, expiresOn, resourceTypes, services: AccountSASServices.parse("b").toString() }, options), this.credential).toString(); return appendToURLQuery(this.url, sas); } } // 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; } })); Object.defineProperty(exports, "HttpHeaders", ({ enumerable: true, get: function () { return coreHttp.HttpHeaders; } })); Object.defineProperty(exports, "RequestPolicyOptions", ({ enumerable: true, get: function () { return coreHttp.RequestPolicyOptions; } })); Object.defineProperty(exports, "RestError", ({ enumerable: true, get: function () { return coreHttp.RestError; } })); Object.defineProperty(exports, "WebResource", ({ enumerable: true, get: function () { return coreHttp.WebResource; } })); Object.defineProperty(exports, "deserializationPolicy", ({ enumerable: true, get: function () { return coreHttp.deserializationPolicy; } })); exports.AccountSASPermissions = AccountSASPermissions; exports.AccountSASResourceTypes = AccountSASResourceTypes; exports.AccountSASServices = AccountSASServices; exports.AnonymousCredential = AnonymousCredential; exports.AnonymousCredentialPolicy = AnonymousCredentialPolicy; exports.AppendBlobClient = AppendBlobClient; exports.BlobBatch = BlobBatch; exports.BlobBatchClient = BlobBatchClient; exports.BlobClient = BlobClient; exports.BlobLeaseClient = BlobLeaseClient; exports.BlobSASPermissions = BlobSASPermissions; exports.BlobServiceClient = BlobServiceClient; exports.BlockBlobClient = BlockBlobClient; exports.ContainerClient = ContainerClient; exports.ContainerSASPermissions = ContainerSASPermissions; exports.Credential = Credential; exports.CredentialPolicy = CredentialPolicy; exports.PageBlobClient = PageBlobClient; exports.Pipeline = Pipeline; exports.SASQueryParameters = SASQueryParameters; exports.StorageBrowserPolicy = StorageBrowserPolicy; exports.StorageBrowserPolicyFactory = StorageBrowserPolicyFactory; exports.StorageOAuthScopes = StorageOAuthScopes; exports.StorageRetryPolicy = StorageRetryPolicy; exports.StorageRetryPolicyFactory = StorageRetryPolicyFactory; exports.StorageSharedKeyCredential = StorageSharedKeyCredential; exports.StorageSharedKeyCredentialPolicy = StorageSharedKeyCredentialPolicy; exports.generateAccountSASQueryParameters = generateAccountSASQueryParameters; exports.generateBlobSASQueryParameters = generateBlobSASQueryParameters; exports.isPipelineLike = isPipelineLike; exports.logger = logger; exports.newPipeline = newPipeline; //# sourceMappingURL=index.js.map /***/ }), /***/ 3849: /***/ ((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 __esDecorate; var __runInitializers; var __propKey; var __setFunctionName; 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); } }; __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.push(_); } else if (_ = accept(result)) { if (kind === "field") initializers.push(_); 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) { 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 (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]) { 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: false } : 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("__esDecorate", __esDecorate); exporter("__runInitializers", __runInitializers); exporter("__propKey", __propKey); exporter("__setFunctionName", __setFunctionName); 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); }); /***/ }), /***/ 9469: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /*! * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ResourceStream = exports.paginator = exports.Paginator = void 0; /*! * @module common/paginator */ const arrify = __nccwpck_require__(6251); const extend = __nccwpck_require__(3860); const resource_stream_1 = __nccwpck_require__(7618); Object.defineProperty(exports, "ResourceStream", ({ enumerable: true, get: function () { return resource_stream_1.ResourceStream; } })); /*! Developer Documentation * * paginator is used to auto-paginate `nextQuery` methods as well as * streamifying them. * * Before: * * search.query('done=true', function(err, results, nextQuery) { * search.query(nextQuery, function(err, results, nextQuery) {}); * }); * * After: * * search.query('done=true', function(err, results) {}); * * Methods to extend should be written to accept callbacks and return a * `nextQuery`. */ class Paginator { /** * Cache the original method, then overwrite it on the Class's prototype. * * @param {function} Class - The parent class of the methods to extend. * @param {string|string[]} methodNames - Name(s) of the methods to extend. */ // tslint:disable-next-line:variable-name extend(Class, methodNames) { methodNames = arrify(methodNames); methodNames.forEach(methodName => { const originalMethod = Class.prototype[methodName]; // map the original method to a private member Class.prototype[methodName + '_'] = originalMethod; // overwrite the original to auto-paginate /* eslint-disable @typescript-eslint/no-explicit-any */ Class.prototype[methodName] = function (...args) { const parsedArguments = paginator.parseArguments_(args); return paginator.run_(parsedArguments, originalMethod.bind(this)); }; }); } /** * Wraps paginated API calls in a readable object stream. * * This method simply calls the nextQuery recursively, emitting results to a * stream. The stream ends when `nextQuery` is null. * * `maxResults` will act as a cap for how many results are fetched and emitted * to the stream. * * @param {string} methodName - Name of the method to streamify. * @return {function} - Wrapped function. */ /* eslint-disable @typescript-eslint/no-explicit-any */ streamify(methodName) { return function ( /* eslint-disable @typescript-eslint/no-explicit-any */ ...args) { const parsedArguments = paginator.parseArguments_(args); const originalMethod = this[methodName + '_'] || this[methodName]; return paginator.runAsStream_(parsedArguments, originalMethod.bind(this)); }; } /** * Parse a pseudo-array `arguments` for a query and callback. * * @param {array} args - The original `arguments` pseduo-array that the original * method received. */ /* eslint-disable @typescript-eslint/no-explicit-any */ parseArguments_(args) { let query; let autoPaginate = true; let maxApiCalls = -1; let maxResults = -1; let callback; const firstArgument = args[0]; const lastArgument = args[args.length - 1]; if (typeof firstArgument === 'function') { callback = firstArgument; } else { query = firstArgument; } if (typeof lastArgument === 'function') { callback = lastArgument; } if (typeof query === 'object') { query = extend(true, {}, query); // Check if the user only asked for a certain amount of results. if (query.maxResults && typeof query.maxResults === 'number') { // `maxResults` is used API-wide. maxResults = query.maxResults; } else if (typeof query.pageSize === 'number') { // `pageSize` is Pub/Sub's `maxResults`. maxResults = query.pageSize; } if (query.maxApiCalls && typeof query.maxApiCalls === 'number') { maxApiCalls = query.maxApiCalls; delete query.maxApiCalls; } // maxResults is the user specified limit. if (maxResults !== -1 || query.autoPaginate === false) { autoPaginate = false; } } const parsedArguments = { query: query || {}, autoPaginate, maxApiCalls, maxResults, callback, }; parsedArguments.streamOptions = extend(true, {}, parsedArguments.query); delete parsedArguments.streamOptions.autoPaginate; delete parsedArguments.streamOptions.maxResults; delete parsedArguments.streamOptions.pageSize; return parsedArguments; } /** * This simply checks to see if `autoPaginate` is set or not, if it's true * then we buffer all results, otherwise simply call the original method. * * @param {array} parsedArguments - Parsed arguments from the original method * call. * @param {object=|string=} parsedArguments.query - Query object. This is most * commonly an object, but to make the API more simple, it can also be a * string in some places. * @param {function=} parsedArguments.callback - Callback function. * @param {boolean} parsedArguments.autoPaginate - Auto-pagination enabled. * @param {boolean} parsedArguments.maxApiCalls - Maximum API calls to make. * @param {number} parsedArguments.maxResults - Maximum results to return. * @param {function} originalMethod - The cached method that accepts a callback * and returns `nextQuery` to receive more results. */ run_(parsedArguments, originalMethod) { const query = parsedArguments.query; const callback = parsedArguments.callback; if (!parsedArguments.autoPaginate) { return originalMethod(query, callback); } const results = new Array(); let otherArgs = []; const promise = new Promise((resolve, reject) => { const stream = paginator.runAsStream_(parsedArguments, originalMethod); stream .on('error', reject) .on('data', (data) => results.push(data)) .on('end', () => { otherArgs = stream._otherArgs || []; resolve(results); }); }); if (!callback) { return promise.then(results => [results, query, ...otherArgs]); } promise.then(results => callback(null, results, query, ...otherArgs), (err) => callback(err)); } /** * This method simply calls the nextQuery recursively, emitting results to a * stream. The stream ends when `nextQuery` is null. * * `maxResults` will act as a cap for how many results are fetched and emitted * to the stream. * * @param {object=|string=} parsedArguments.query - Query object. This is most * commonly an object, but to make the API more simple, it can also be a * string in some places. * @param {function=} parsedArguments.callback - Callback function. * @param {boolean} parsedArguments.autoPaginate - Auto-pagination enabled. * @param {boolean} parsedArguments.maxApiCalls - Maximum API calls to make. * @param {number} parsedArguments.maxResults - Maximum results to return. * @param {function} originalMethod - The cached method that accepts a callback * and returns `nextQuery` to receive more results. * @return {stream} - Readable object stream. */ /* eslint-disable @typescript-eslint/no-explicit-any */ runAsStream_(parsedArguments, originalMethod) { return new resource_stream_1.ResourceStream(parsedArguments, originalMethod); } } exports.Paginator = Paginator; const paginator = new Paginator(); exports.paginator = paginator; //# sourceMappingURL=index.js.map /***/ }), /***/ 7618: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /*! * Copyright 2019 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ResourceStream = void 0; const stream_1 = __nccwpck_require__(2203); class ResourceStream extends stream_1.Transform { constructor(args, requestFn) { const options = Object.assign({ objectMode: true }, args.streamOptions); super(options); this._ended = false; this._maxApiCalls = args.maxApiCalls === -1 ? Infinity : args.maxApiCalls; this._nextQuery = args.query; this._reading = false; this._requestFn = requestFn; this._requestsMade = 0; this._resultsToSend = args.maxResults === -1 ? Infinity : args.maxResults; this._otherArgs = []; } /* eslint-disable @typescript-eslint/no-explicit-any */ end(...args) { this._ended = true; return super.end(...args); } _read() { if (this._reading) { return; } this._reading = true; // Wrap in a try/catch to catch input linting errors, e.g. // an invalid BigQuery query. These errors are thrown in an // async fashion, which makes them un-catchable by the user. try { this._requestFn(this._nextQuery, (err, results, nextQuery, ...otherArgs) => { if (err) { this.destroy(err); return; } this._otherArgs = otherArgs; this._nextQuery = nextQuery; if (this._resultsToSend !== Infinity) { results = results.splice(0, this._resultsToSend); this._resultsToSend -= results.length; } let more = true; for (const result of results) { if (this._ended) { break; } more = this.push(result); } const isFinished = !this._nextQuery || this._resultsToSend < 1; const madeMaxCalls = ++this._requestsMade >= this._maxApiCalls; if (isFinished || madeMaxCalls) { this.end(); } if (more && !this._ended) { setImmediate(() => this._read()); } this._reading = false; }); } catch (e) { this.destroy(e); } } } exports.ResourceStream = ResourceStream; //# sourceMappingURL=resource-stream.js.map /***/ }), /***/ 7635: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MissingProjectIdError = exports.replaceProjectIdToken = void 0; const stream_1 = __nccwpck_require__(2203); // Copyright 2014 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * Populate the `{{projectId}}` placeholder. * * @throws {Error} If a projectId is required, but one is not provided. * * @param {*} - Any input value that may contain a placeholder. Arrays and objects will be looped. * @param {string} projectId - A projectId. If not provided * @return {*} - The original argument with all placeholders populated. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function replaceProjectIdToken(value, projectId) { if (Array.isArray(value)) { value = value.map(v => replaceProjectIdToken(v, projectId)); } if (value !== null && typeof value === 'object' && !(value instanceof Buffer) && !(value instanceof stream_1.Stream) && typeof value.hasOwnProperty === 'function') { for (const opt in value) { // eslint-disable-next-line no-prototype-builtins if (value.hasOwnProperty(opt)) { value[opt] = replaceProjectIdToken(value[opt], projectId); } } } if (typeof value === 'string' && value.indexOf('{{projectId}}') > -1) { if (!projectId || projectId === '{{projectId}}') { throw new MissingProjectIdError(); } value = value.replace(/{{projectId}}/g, projectId); } return value; } exports.replaceProjectIdToken = replaceProjectIdToken; /** * Custom error type for missing project ID errors. */ class MissingProjectIdError extends Error { constructor() { super(...arguments); this.message = `Sorry, we cannot connect to Cloud Services without a project ID. You may specify one with an environment variable named "GOOGLE_CLOUD_PROJECT".`.replace(/ +/g, ' '); } } exports.MissingProjectIdError = MissingProjectIdError; //# sourceMappingURL=index.js.map /***/ }), /***/ 206: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* eslint-disable prefer-rest-params */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.callbackifyAll = exports.callbackify = exports.promisifyAll = exports.promisify = void 0; /** * Wraps a callback style function to conditionally return a promise. * * @param {function} originalMethod - The method to promisify. * @param {object=} options - Promise options. * @param {boolean} options.singular - Resolve the promise with single arg instead of an array. * @return {function} wrapped */ function promisify(originalMethod, options) { if (originalMethod.promisified_) { return originalMethod; } options = options || {}; const slice = Array.prototype.slice; // tslint:disable-next-line:no-any const wrapper = function () { let last; for (last = arguments.length - 1; last >= 0; last--) { const arg = arguments[last]; if (typeof arg === 'undefined') { continue; // skip trailing undefined. } if (typeof arg !== 'function') { break; // non-callback last argument found. } return originalMethod.apply(this, arguments); } // peel trailing undefined. const args = slice.call(arguments, 0, last + 1); // tslint:disable-next-line:variable-name let PromiseCtor = Promise; // Because dedupe will likely create a single install of // @google-cloud/common to be shared amongst all modules, we need to // localize it at the Service level. if (this && this.Promise) { PromiseCtor = this.Promise; } return new PromiseCtor((resolve, reject) => { // tslint:disable-next-line:no-any args.push((...args) => { const callbackArgs = slice.call(args); const err = callbackArgs.shift(); if (err) { return reject(err); } if (options.singular && callbackArgs.length === 1) { resolve(callbackArgs[0]); } else { resolve(callbackArgs); } }); originalMethod.apply(this, args); }); }; wrapper.promisified_ = true; return wrapper; } exports.promisify = promisify; /** * Promisifies certain Class methods. This will not promisify private or * streaming methods. * * @param {module:common/service} Class - Service class. * @param {object=} options - Configuration object. */ // tslint:disable-next-line:variable-name function promisifyAll(Class, options) { const exclude = (options && options.exclude) || []; const ownPropertyNames = Object.getOwnPropertyNames(Class.prototype); const methods = ownPropertyNames.filter(methodName => { // clang-format off return (!exclude.includes(methodName) && typeof Class.prototype[methodName] === 'function' && // is it a function? !/(^_|(Stream|_)|promise$)|^constructor$/.test(methodName) // is it promisable? ); // clang-format on }); methods.forEach(methodName => { const originalMethod = Class.prototype[methodName]; if (!originalMethod.promisified_) { Class.prototype[methodName] = exports.promisify(originalMethod, options); } }); } exports.promisifyAll = promisifyAll; /** * Wraps a promisy type function to conditionally call a callback function. * * @param {function} originalMethod - The method to callbackify. * @param {object=} options - Callback options. * @param {boolean} options.singular - Pass to the callback a single arg instead of an array. * @return {function} wrapped */ function callbackify(originalMethod) { if (originalMethod.callbackified_) { return originalMethod; } // tslint:disable-next-line:no-any const wrapper = function () { if (typeof arguments[arguments.length - 1] !== 'function') { return originalMethod.apply(this, arguments); } const cb = Array.prototype.pop.call(arguments); originalMethod.apply(this, arguments).then( // tslint:disable-next-line:no-any (res) => { res = Array.isArray(res) ? res : [res]; cb(null, ...res); }, (err) => cb(err)); }; wrapper.callbackified_ = true; return wrapper; } exports.callbackify = callbackify; /** * Callbackifies certain Class methods. This will not callbackify private or * streaming methods. * * @param {module:common/service} Class - Service class. * @param {object=} options - Configuration object. */ function callbackifyAll( // tslint:disable-next-line:variable-name Class, options) { const exclude = (options && options.exclude) || []; const ownPropertyNames = Object.getOwnPropertyNames(Class.prototype); const methods = ownPropertyNames.filter(methodName => { // clang-format off return (!exclude.includes(methodName) && typeof Class.prototype[methodName] === 'function' && // is it a function? !/^_|(Stream|_)|^constructor$/.test(methodName) // is it callbackifyable? ); // clang-format on }); methods.forEach(methodName => { const originalMethod = Class.prototype[methodName]; if (!originalMethod.callbackified_) { Class.prototype[methodName] = exports.callbackify(originalMethod); } }); } exports.callbackifyAll = callbackifyAll; //# sourceMappingURL=index.js.map /***/ }), /***/ 9977: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Queue = __nccwpck_require__(538); const pLimit = concurrency => { if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) { throw new TypeError('Expected `concurrency` to be a number from 1 and up'); } const queue = new Queue(); let activeCount = 0; const next = () => { activeCount--; if (queue.size > 0) { queue.dequeue()(); } }; const run = async (fn, resolve, ...args) => { activeCount++; const result = (async () => fn(...args))(); resolve(result); try { await result; } catch {} next(); }; const enqueue = (fn, resolve, ...args) => { queue.enqueue(run.bind(null, fn, resolve, ...args)); (async () => { // This function needs to wait until the next microtask before comparing // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously // when the run function is dequeued and called. The comparison in the if-statement // needs to happen asynchronously as well to get an up-to-date value for `activeCount`. await Promise.resolve(); if (activeCount < concurrency && queue.size > 0) { queue.dequeue()(); } })(); }; const generator = (fn, ...args) => new Promise(resolve => { enqueue(fn, resolve, ...args); }); Object.defineProperties(generator, { activeCount: { get: () => activeCount }, pendingCount: { get: () => queue.size }, clearQueue: { value: () => { queue.clear(); } } }); return generator; }; module.exports = pLimit; /***/ }), /***/ 9750: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ContextAPI = void 0; const NoopContextManager_1 = __nccwpck_require__(9522); const global_utils_1 = __nccwpck_require__(9923); const diag_1 = __nccwpck_require__(1230); const API_NAME = 'context'; const NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager(); /** * Singleton object which represents the entry point to the OpenTelemetry Context API */ class ContextAPI { /** Empty private constructor prevents end users from constructing a new instance of the API */ constructor() { } /** Get the singleton instance of the Context API */ static getInstance() { if (!this._instance) { this._instance = new ContextAPI(); } return this._instance; } /** * Set the current context manager. * * @returns true if the context manager was successfully registered, else false */ setGlobalContextManager(contextManager) { return (0, global_utils_1.registerGlobal)(API_NAME, contextManager, diag_1.DiagAPI.instance()); } /** * Get the currently active context */ active() { return this._getContextManager().active(); } /** * Execute a function with an active context * * @param context context to be active during function execution * @param fn function to execute in a context * @param thisArg optional receiver to be used for calling fn * @param args optional arguments forwarded to fn */ with(context, fn, thisArg, ...args) { return this._getContextManager().with(context, fn, thisArg, ...args); } /** * Bind a context to a target function or event emitter * * @param context context to bind to the event emitter or function. Defaults to the currently active context * @param target function or event emitter to bind */ bind(context, target) { return this._getContextManager().bind(context, target); } _getContextManager() { return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_CONTEXT_MANAGER; } /** Disable and remove the global context manager */ disable() { this._getContextManager().disable(); (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); } } exports.ContextAPI = ContextAPI; //# sourceMappingURL=context.js.map /***/ }), /***/ 1230: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DiagAPI = void 0; const ComponentLogger_1 = __nccwpck_require__(104); const logLevelLogger_1 = __nccwpck_require__(3514); const types_1 = __nccwpck_require__(2573); const global_utils_1 = __nccwpck_require__(9923); const API_NAME = 'diag'; /** * Singleton object which represents the entry point to the OpenTelemetry internal * diagnostic API */ class DiagAPI { /** * Private internal constructor * @private */ constructor() { function _logProxy(funcName) { return function (...args) { const logger = (0, global_utils_1.getGlobal)('diag'); // shortcut if logger not set if (!logger) return; return logger[funcName](...args); }; } // Using self local variable for minification purposes as 'this' cannot be minified const self = this; // DiagAPI specific functions const setLogger = (logger, optionsOrLogLevel = { logLevel: types_1.DiagLogLevel.INFO }) => { var _a, _b, _c; if (logger === self) { // There isn't much we can do here. // Logging to the console might break the user application. // Try to log to self. If a logger was previously registered it will receive the log. const err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'); self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message); return false; } if (typeof optionsOrLogLevel === 'number') { optionsOrLogLevel = { logLevel: optionsOrLogLevel, }; } const oldLogger = (0, global_utils_1.getGlobal)('diag'); const newLogger = (0, logLevelLogger_1.createLogLevelDiagLogger)((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : types_1.DiagLogLevel.INFO, logger); // There already is an logger registered. We'll let it know before overwriting it. if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ''; oldLogger.warn(`Current logger will be overwritten from ${stack}`); newLogger.warn(`Current logger will overwrite one already registered from ${stack}`); } return (0, global_utils_1.registerGlobal)('diag', newLogger, self, true); }; self.setLogger = setLogger; self.disable = () => { (0, global_utils_1.unregisterGlobal)(API_NAME, self); }; self.createComponentLogger = (options) => { return new ComponentLogger_1.DiagComponentLogger(options); }; self.verbose = _logProxy('verbose'); self.debug = _logProxy('debug'); self.info = _logProxy('info'); self.warn = _logProxy('warn'); self.error = _logProxy('error'); } /** Get the singleton instance of the DiagAPI API */ static instance() { if (!this._instance) { this._instance = new DiagAPI(); } return this._instance; } } exports.DiagAPI = DiagAPI; //# sourceMappingURL=diag.js.map /***/ }), /***/ 8692: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MetricsAPI = void 0; const NoopMeterProvider_1 = __nccwpck_require__(2896); const global_utils_1 = __nccwpck_require__(9923); const diag_1 = __nccwpck_require__(1230); const API_NAME = 'metrics'; /** * Singleton object which represents the entry point to the OpenTelemetry Metrics API */ class MetricsAPI { /** Empty private constructor prevents end users from constructing a new instance of the API */ constructor() { } /** Get the singleton instance of the Metrics API */ static getInstance() { if (!this._instance) { this._instance = new MetricsAPI(); } return this._instance; } /** * Set the current global meter provider. * Returns true if the meter provider was successfully registered, else false. */ setGlobalMeterProvider(provider) { return (0, global_utils_1.registerGlobal)(API_NAME, provider, diag_1.DiagAPI.instance()); } /** * Returns the global meter provider. */ getMeterProvider() { return (0, global_utils_1.getGlobal)(API_NAME) || NoopMeterProvider_1.NOOP_METER_PROVIDER; } /** * Returns a meter from the global meter provider. */ getMeter(name, version, options) { return this.getMeterProvider().getMeter(name, version, options); } /** Remove the global meter provider */ disable() { (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); } } exports.MetricsAPI = MetricsAPI; //# sourceMappingURL=metrics.js.map /***/ }), /***/ 7: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PropagationAPI = void 0; const global_utils_1 = __nccwpck_require__(9923); const NoopTextMapPropagator_1 = __nccwpck_require__(4353); const TextMapPropagator_1 = __nccwpck_require__(7865); const context_helpers_1 = __nccwpck_require__(52); const utils_1 = __nccwpck_require__(8558); const diag_1 = __nccwpck_require__(1230); const API_NAME = 'propagation'; const NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator(); /** * Singleton object which represents the entry point to the OpenTelemetry Propagation API */ class PropagationAPI { /** Empty private constructor prevents end users from constructing a new instance of the API */ constructor() { this.createBaggage = utils_1.createBaggage; this.getBaggage = context_helpers_1.getBaggage; this.getActiveBaggage = context_helpers_1.getActiveBaggage; this.setBaggage = context_helpers_1.setBaggage; this.deleteBaggage = context_helpers_1.deleteBaggage; } /** Get the singleton instance of the Propagator API */ static getInstance() { if (!this._instance) { this._instance = new PropagationAPI(); } return this._instance; } /** * Set the current propagator. * * @returns true if the propagator was successfully registered, else false */ setGlobalPropagator(propagator) { return (0, global_utils_1.registerGlobal)(API_NAME, propagator, diag_1.DiagAPI.instance()); } /** * Inject context into a carrier to be propagated inter-process * * @param context Context carrying tracing data to inject * @param carrier carrier to inject context into * @param setter Function used to set values on the carrier */ inject(context, carrier, setter = TextMapPropagator_1.defaultTextMapSetter) { return this._getGlobalPropagator().inject(context, carrier, setter); } /** * Extract context from a carrier * * @param context Context which the newly created context will inherit from * @param carrier Carrier to extract context from * @param getter Function used to extract keys from a carrier */ extract(context, carrier, getter = TextMapPropagator_1.defaultTextMapGetter) { return this._getGlobalPropagator().extract(context, carrier, getter); } /** * Return a list of all fields which may be used by the propagator. */ fields() { return this._getGlobalPropagator().fields(); } /** Remove the global propagator */ disable() { (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); } _getGlobalPropagator() { return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR; } } exports.PropagationAPI = PropagationAPI; //# sourceMappingURL=propagation.js.map /***/ }), /***/ 4508: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TraceAPI = void 0; const global_utils_1 = __nccwpck_require__(9923); const ProxyTracerProvider_1 = __nccwpck_require__(312); const spancontext_utils_1 = __nccwpck_require__(639); const context_utils_1 = __nccwpck_require__(2771); const diag_1 = __nccwpck_require__(1230); const API_NAME = 'trace'; /** * Singleton object which represents the entry point to the OpenTelemetry Tracing API */ class TraceAPI { /** Empty private constructor prevents end users from constructing a new instance of the API */ constructor() { this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); this.wrapSpanContext = spancontext_utils_1.wrapSpanContext; this.isSpanContextValid = spancontext_utils_1.isSpanContextValid; this.deleteSpan = context_utils_1.deleteSpan; this.getSpan = context_utils_1.getSpan; this.getActiveSpan = context_utils_1.getActiveSpan; this.getSpanContext = context_utils_1.getSpanContext; this.setSpan = context_utils_1.setSpan; this.setSpanContext = context_utils_1.setSpanContext; } /** Get the singleton instance of the Trace API */ static getInstance() { if (!this._instance) { this._instance = new TraceAPI(); } return this._instance; } /** * Set the current global tracer. * * @returns true if the tracer provider was successfully registered, else false */ setGlobalTracerProvider(provider) { const success = (0, global_utils_1.registerGlobal)(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance()); if (success) { this._proxyTracerProvider.setDelegate(provider); } return success; } /** * Returns the global tracer provider. */ getTracerProvider() { return (0, global_utils_1.getGlobal)(API_NAME) || this._proxyTracerProvider; } /** * Returns a tracer from the global tracer provider. */ getTracer(name, version) { return this.getTracerProvider().getTracer(name, version); } /** Remove the global tracer provider */ disable() { (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); } } exports.TraceAPI = TraceAPI; //# sourceMappingURL=trace.js.map /***/ }), /***/ 52: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.deleteBaggage = exports.setBaggage = exports.getActiveBaggage = exports.getBaggage = void 0; const context_1 = __nccwpck_require__(9750); const context_2 = __nccwpck_require__(7977); /** * Baggage key */ const BAGGAGE_KEY = (0, context_2.createContextKey)('OpenTelemetry Baggage Key'); /** * Retrieve the current baggage from the given context * * @param {Context} Context that manage all context values * @returns {Baggage} Extracted baggage from the context */ function getBaggage(context) { return context.getValue(BAGGAGE_KEY) || undefined; } exports.getBaggage = getBaggage; /** * Retrieve the current baggage from the active/current context * * @returns {Baggage} Extracted baggage from the context */ function getActiveBaggage() { return getBaggage(context_1.ContextAPI.getInstance().active()); } exports.getActiveBaggage = getActiveBaggage; /** * Store a baggage in the given context * * @param {Context} Context that manage all context values * @param {Baggage} baggage that will be set in the actual context */ function setBaggage(context, baggage) { return context.setValue(BAGGAGE_KEY, baggage); } exports.setBaggage = setBaggage; /** * Delete the baggage stored in the given context * * @param {Context} Context that manage all context values */ function deleteBaggage(context) { return context.deleteValue(BAGGAGE_KEY); } exports.deleteBaggage = deleteBaggage; //# sourceMappingURL=context-helpers.js.map /***/ }), /***/ 3274: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BaggageImpl = void 0; class BaggageImpl { constructor(entries) { this._entries = entries ? new Map(entries) : new Map(); } getEntry(key) { const entry = this._entries.get(key); if (!entry) { return undefined; } return Object.assign({}, entry); } getAllEntries() { return Array.from(this._entries.entries()).map(([k, v]) => [k, v]); } setEntry(key, entry) { const newBaggage = new BaggageImpl(this._entries); newBaggage._entries.set(key, entry); return newBaggage; } removeEntry(key) { const newBaggage = new BaggageImpl(this._entries); newBaggage._entries.delete(key); return newBaggage; } removeEntries(...keys) { const newBaggage = new BaggageImpl(this._entries); for (const key of keys) { newBaggage._entries.delete(key); } return newBaggage; } clear() { return new BaggageImpl(); } } exports.BaggageImpl = BaggageImpl; //# sourceMappingURL=baggage-impl.js.map /***/ }), /***/ 3997: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.baggageEntryMetadataSymbol = void 0; /** * Symbol used to make BaggageEntryMetadata an opaque type */ exports.baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata'); //# sourceMappingURL=symbol.js.map /***/ }), /***/ 8558: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.baggageEntryMetadataFromString = exports.createBaggage = void 0; const diag_1 = __nccwpck_require__(1230); const baggage_impl_1 = __nccwpck_require__(3274); const symbol_1 = __nccwpck_require__(3997); const diag = diag_1.DiagAPI.instance(); /** * Create a new Baggage with optional entries * * @param entries An array of baggage entries the new baggage should contain */ function createBaggage(entries = {}) { return new baggage_impl_1.BaggageImpl(new Map(Object.entries(entries))); } exports.createBaggage = createBaggage; /** * Create a serializable BaggageEntryMetadata object from a string. * * @param str string metadata. Format is currently not defined by the spec and has no special meaning. * */ function baggageEntryMetadataFromString(str) { if (typeof str !== 'string') { diag.error(`Cannot create baggage metadata from unknown type: ${typeof str}`); str = ''; } return { __TYPE__: symbol_1.baggageEntryMetadataSymbol, toString() { return str; }, }; } exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString; //# sourceMappingURL=utils.js.map /***/ }), /***/ 244: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.context = void 0; // Split module-level variable definition into separate files to allow // tree-shaking on each api instance. const context_1 = __nccwpck_require__(9750); /** Entrypoint for context API */ exports.context = context_1.ContextAPI.getInstance(); //# sourceMappingURL=context-api.js.map /***/ }), /***/ 9522: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopContextManager = void 0; const context_1 = __nccwpck_require__(7977); class NoopContextManager { active() { return context_1.ROOT_CONTEXT; } with(_context, fn, thisArg, ...args) { return fn.call(thisArg, ...args); } bind(_context, target) { return target; } enable() { return this; } disable() { return this; } } exports.NoopContextManager = NoopContextManager; //# sourceMappingURL=NoopContextManager.js.map /***/ }), /***/ 7977: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ROOT_CONTEXT = exports.createContextKey = void 0; /** Get a key to uniquely identify a context value */ function createContextKey(description) { // The specification states that for the same input, multiple calls should // return different keys. Due to the nature of the JS dependency management // system, this creates problems where multiple versions of some package // could hold different keys for the same property. // // Therefore, we use Symbol.for which returns the same key for the same input. return Symbol.for(description); } exports.createContextKey = createContextKey; class BaseContext { /** * Construct a new context which inherits values from an optional parent context. * * @param parentContext a context from which to inherit values */ constructor(parentContext) { // for minification const self = this; self._currentContext = parentContext ? new Map(parentContext) : new Map(); self.getValue = (key) => self._currentContext.get(key); self.setValue = (key, value) => { const context = new BaseContext(self._currentContext); context._currentContext.set(key, value); return context; }; self.deleteValue = (key) => { const context = new BaseContext(self._currentContext); context._currentContext.delete(key); return context; }; } } /** The root context is used as the default parent context when there is no active context */ exports.ROOT_CONTEXT = new BaseContext(); //# sourceMappingURL=context.js.map /***/ }), /***/ 1414: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.diag = void 0; // Split module-level variable definition into separate files to allow // tree-shaking on each api instance. const diag_1 = __nccwpck_require__(1230); /** * Entrypoint for Diag API. * Defines Diagnostic handler used for internal diagnostic logging operations. * The default provides a Noop DiagLogger implementation which may be changed via the * diag.setLogger(logger: DiagLogger) function. */ exports.diag = diag_1.DiagAPI.instance(); //# sourceMappingURL=diag-api.js.map /***/ }), /***/ 104: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DiagComponentLogger = void 0; const global_utils_1 = __nccwpck_require__(9923); /** * 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. * It will then forward all message to global diag logger * @example * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' }); * cLogger.debug('test'); * // @opentelemetry/instrumentation-http test */ class DiagComponentLogger { constructor(props) { this._namespace = props.namespace || 'DiagComponentLogger'; } debug(...args) { return logProxy('debug', this._namespace, args); } error(...args) { return logProxy('error', this._namespace, args); } info(...args) { return logProxy('info', this._namespace, args); } warn(...args) { return logProxy('warn', this._namespace, args); } verbose(...args) { return logProxy('verbose', this._namespace, args); } } exports.DiagComponentLogger = DiagComponentLogger; function logProxy(funcName, namespace, args) { const logger = (0, global_utils_1.getGlobal)('diag'); // shortcut if logger not set if (!logger) { return; } args.unshift(namespace); return logger[funcName](...args); } //# sourceMappingURL=ComponentLogger.js.map /***/ }), /***/ 6769: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DiagConsoleLogger = void 0; const consoleMap = [ { n: 'error', c: 'error' }, { n: 'warn', c: 'warn' }, { n: 'info', c: 'info' }, { n: 'debug', c: 'debug' }, { n: 'verbose', c: 'trace' }, ]; /** * A simple Immutable Console based diagnostic logger which will output any messages to the Console. * If you want to limit the amount of logging to a specific level or lower use the * {@link createLogLevelDiagLogger} */ class DiagConsoleLogger { constructor() { function _consoleFunc(funcName) { return function (...args) { if (console) { // Some environments only expose the console when the F12 developer console is open // eslint-disable-next-line no-console let theFunc = console[funcName]; if (typeof theFunc !== 'function') { // Not all environments support all functions // eslint-disable-next-line no-console theFunc = console.log; } // One last final check if (typeof theFunc === 'function') { return theFunc.apply(console, args); } } }; } for (let i = 0; i < consoleMap.length; i++) { this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c); } } } exports.DiagConsoleLogger = DiagConsoleLogger; //# sourceMappingURL=consoleLogger.js.map /***/ }), /***/ 3514: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createLogLevelDiagLogger = void 0; const types_1 = __nccwpck_require__(2573); function createLogLevelDiagLogger(maxLevel, logger) { if (maxLevel < types_1.DiagLogLevel.NONE) { maxLevel = types_1.DiagLogLevel.NONE; } else if (maxLevel > types_1.DiagLogLevel.ALL) { maxLevel = types_1.DiagLogLevel.ALL; } // In case the logger is null or undefined logger = logger || {}; function _filterFunc(funcName, theLevel) { const theFunc = logger[funcName]; if (typeof theFunc === 'function' && maxLevel >= theLevel) { return theFunc.bind(logger); } return function () { }; } return { error: _filterFunc('error', types_1.DiagLogLevel.ERROR), warn: _filterFunc('warn', types_1.DiagLogLevel.WARN), info: _filterFunc('info', types_1.DiagLogLevel.INFO), debug: _filterFunc('debug', types_1.DiagLogLevel.DEBUG), verbose: _filterFunc('verbose', types_1.DiagLogLevel.VERBOSE), }; } exports.createLogLevelDiagLogger = createLogLevelDiagLogger; //# sourceMappingURL=logLevelLogger.js.map /***/ }), /***/ 2573: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DiagLogLevel = void 0; /** * Defines the available internal logging levels for the diagnostic logger, the numeric values * of the levels are defined to match the original values from the initial LogLevel to avoid * compatibility/migration issues for any implementation that assume the numeric ordering. */ var DiagLogLevel; (function (DiagLogLevel) { /** Diagnostic Logging level setting to disable all logging (except and forced logs) */ DiagLogLevel[DiagLogLevel["NONE"] = 0] = "NONE"; /** Identifies an error scenario */ DiagLogLevel[DiagLogLevel["ERROR"] = 30] = "ERROR"; /** Identifies a warning scenario */ DiagLogLevel[DiagLogLevel["WARN"] = 50] = "WARN"; /** General informational log message */ DiagLogLevel[DiagLogLevel["INFO"] = 60] = "INFO"; /** General debug log message */ DiagLogLevel[DiagLogLevel["DEBUG"] = 70] = "DEBUG"; /** * Detailed trace level logging should only be used for development, should only be set * in a development environment. */ DiagLogLevel[DiagLogLevel["VERBOSE"] = 80] = "VERBOSE"; /** Used to set the logging level to include all logging */ DiagLogLevel[DiagLogLevel["ALL"] = 9999] = "ALL"; })(DiagLogLevel = exports.DiagLogLevel || (exports.DiagLogLevel = {})); //# sourceMappingURL=types.js.map /***/ }), /***/ 3914: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.trace = exports.propagation = exports.metrics = exports.diag = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.createTraceState = exports.TraceFlags = exports.SpanStatusCode = exports.SpanKind = exports.SamplingDecision = exports.ProxyTracerProvider = exports.ProxyTracer = exports.defaultTextMapSetter = exports.defaultTextMapGetter = exports.ValueType = exports.createNoopMeter = exports.DiagLogLevel = exports.DiagConsoleLogger = exports.ROOT_CONTEXT = exports.createContextKey = exports.baggageEntryMetadataFromString = void 0; var utils_1 = __nccwpck_require__(8558); Object.defineProperty(exports, "baggageEntryMetadataFromString", ({ enumerable: true, get: function () { return utils_1.baggageEntryMetadataFromString; } })); // Context APIs var context_1 = __nccwpck_require__(7977); Object.defineProperty(exports, "createContextKey", ({ enumerable: true, get: function () { return context_1.createContextKey; } })); Object.defineProperty(exports, "ROOT_CONTEXT", ({ enumerable: true, get: function () { return context_1.ROOT_CONTEXT; } })); // Diag APIs var consoleLogger_1 = __nccwpck_require__(6769); Object.defineProperty(exports, "DiagConsoleLogger", ({ enumerable: true, get: function () { return consoleLogger_1.DiagConsoleLogger; } })); var types_1 = __nccwpck_require__(2573); Object.defineProperty(exports, "DiagLogLevel", ({ enumerable: true, get: function () { return types_1.DiagLogLevel; } })); // Metrics APIs var NoopMeter_1 = __nccwpck_require__(7017); Object.defineProperty(exports, "createNoopMeter", ({ enumerable: true, get: function () { return NoopMeter_1.createNoopMeter; } })); var Metric_1 = __nccwpck_require__(3814); Object.defineProperty(exports, "ValueType", ({ enumerable: true, get: function () { return Metric_1.ValueType; } })); // Propagation APIs var TextMapPropagator_1 = __nccwpck_require__(7865); Object.defineProperty(exports, "defaultTextMapGetter", ({ enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapGetter; } })); Object.defineProperty(exports, "defaultTextMapSetter", ({ enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapSetter; } })); var ProxyTracer_1 = __nccwpck_require__(4833); Object.defineProperty(exports, "ProxyTracer", ({ enumerable: true, get: function () { return ProxyTracer_1.ProxyTracer; } })); var ProxyTracerProvider_1 = __nccwpck_require__(312); Object.defineProperty(exports, "ProxyTracerProvider", ({ enumerable: true, get: function () { return ProxyTracerProvider_1.ProxyTracerProvider; } })); var SamplingResult_1 = __nccwpck_require__(434); Object.defineProperty(exports, "SamplingDecision", ({ enumerable: true, get: function () { return SamplingResult_1.SamplingDecision; } })); var span_kind_1 = __nccwpck_require__(2347); Object.defineProperty(exports, "SpanKind", ({ enumerable: true, get: function () { return span_kind_1.SpanKind; } })); var status_1 = __nccwpck_require__(1524); Object.defineProperty(exports, "SpanStatusCode", ({ enumerable: true, get: function () { return status_1.SpanStatusCode; } })); var trace_flags_1 = __nccwpck_require__(7221); Object.defineProperty(exports, "TraceFlags", ({ enumerable: true, get: function () { return trace_flags_1.TraceFlags; } })); var utils_2 = __nccwpck_require__(969); Object.defineProperty(exports, "createTraceState", ({ enumerable: true, get: function () { return utils_2.createTraceState; } })); var spancontext_utils_1 = __nccwpck_require__(639); 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__(7088); Object.defineProperty(exports, "INVALID_SPANID", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPANID; } })); Object.defineProperty(exports, "INVALID_TRACEID", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_TRACEID; } })); Object.defineProperty(exports, "INVALID_SPAN_CONTEXT", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPAN_CONTEXT; } })); // Split module-level variable definition into separate files to allow // tree-shaking on each api instance. const context_api_1 = __nccwpck_require__(244); Object.defineProperty(exports, "context", ({ enumerable: true, get: function () { return context_api_1.context; } })); const diag_api_1 = __nccwpck_require__(1414); Object.defineProperty(exports, "diag", ({ enumerable: true, get: function () { return diag_api_1.diag; } })); const metrics_api_1 = __nccwpck_require__(2053); Object.defineProperty(exports, "metrics", ({ enumerable: true, get: function () { return metrics_api_1.metrics; } })); const propagation_api_1 = __nccwpck_require__(6389); Object.defineProperty(exports, "propagation", ({ enumerable: true, get: function () { return propagation_api_1.propagation; } })); const trace_api_1 = __nccwpck_require__(6542); Object.defineProperty(exports, "trace", ({ enumerable: true, get: function () { return trace_api_1.trace; } })); // Default export. exports["default"] = { context: context_api_1.context, diag: diag_api_1.diag, metrics: metrics_api_1.metrics, propagation: propagation_api_1.propagation, trace: trace_api_1.trace, }; //# sourceMappingURL=index.js.map /***/ }), /***/ 9923: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.unregisterGlobal = exports.getGlobal = exports.registerGlobal = void 0; const platform_1 = __nccwpck_require__(9932); const version_1 = __nccwpck_require__(9390); const semver_1 = __nccwpck_require__(5088); const major = version_1.VERSION.split('.')[0]; const GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`); const _global = platform_1._globalThis; function registerGlobal(type, instance, diag, allowOverride = false) { var _a; const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { version: version_1.VERSION, }); if (!allowOverride && api[type]) { // already registered an API of this type const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`); diag.error(err.stack || err.message); return false; } if (api.version !== version_1.VERSION) { // All registered APIs must be of the same version exactly const err = new Error('@opentelemetry/api: All API registration versions must match'); diag.error(err.stack || err.message); return false; } api[type] = instance; diag.debug(`@opentelemetry/api: Registered a global for ${type} v${version_1.VERSION}.`); return true; } exports.registerGlobal = registerGlobal; function getGlobal(type) { var _a, _b; const globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version; if (!globalVersion || !(0, semver_1.isCompatible)(globalVersion)) { return; } return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type]; } exports.getGlobal = getGlobal; function unregisterGlobal(type, diag) { diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${version_1.VERSION}.`); const api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; if (api) { delete api[type]; } } exports.unregisterGlobal = unregisterGlobal; //# sourceMappingURL=global-utils.js.map /***/ }), /***/ 5088: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isCompatible = exports._makeCompatibilityCheck = void 0; const version_1 = __nccwpck_require__(9390); const re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; /** * Create a function to test an API version to see if it is compatible with the provided ownVersion. * * The returned function has the following semantics: * - Exact match is always compatible * - Major versions must match exactly * - 1.x package cannot use global 2.x package * - 2.x package cannot use global 1.x package * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor * - Patch and build tag differences are not considered at this time * * @param ownVersion version which should be checked against */ function _makeCompatibilityCheck(ownVersion) { const acceptedVersions = new Set([ownVersion]); const rejectedVersions = new Set(); const myVersionMatch = ownVersion.match(re); if (!myVersionMatch) { // we cannot guarantee compatibility so we always return noop return () => false; } const ownVersionParsed = { major: +myVersionMatch[1], minor: +myVersionMatch[2], patch: +myVersionMatch[3], prerelease: myVersionMatch[4], }; // if ownVersion has a prerelease tag, versions must match exactly if (ownVersionParsed.prerelease != null) { return function isExactmatch(globalVersion) { return globalVersion === ownVersion; }; } function _reject(v) { rejectedVersions.add(v); return false; } function _accept(v) { acceptedVersions.add(v); return true; } return function isCompatible(globalVersion) { if (acceptedVersions.has(globalVersion)) { return true; } if (rejectedVersions.has(globalVersion)) { return false; } const globalVersionMatch = globalVersion.match(re); if (!globalVersionMatch) { // cannot parse other version // we cannot guarantee compatibility so we always noop return _reject(globalVersion); } const globalVersionParsed = { major: +globalVersionMatch[1], minor: +globalVersionMatch[2], patch: +globalVersionMatch[3], prerelease: globalVersionMatch[4], }; // if globalVersion has a prerelease tag, versions must match exactly if (globalVersionParsed.prerelease != null) { return _reject(globalVersion); } // major versions must match if (ownVersionParsed.major !== globalVersionParsed.major) { return _reject(globalVersion); } if (ownVersionParsed.major === 0) { if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) { return _accept(globalVersion); } return _reject(globalVersion); } if (ownVersionParsed.minor <= globalVersionParsed.minor) { return _accept(globalVersion); } return _reject(globalVersion); }; } exports._makeCompatibilityCheck = _makeCompatibilityCheck; /** * Test an API version to see if it is compatible with this API. * * - Exact match is always compatible * - Major versions must match exactly * - 1.x package cannot use global 2.x package * - 2.x package cannot use global 1.x package * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor * - Patch and build tag differences are not considered at this time * * @param version version of the API requesting an instance of the global API */ exports.isCompatible = _makeCompatibilityCheck(version_1.VERSION); //# sourceMappingURL=semver.js.map /***/ }), /***/ 2053: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.metrics = void 0; // Split module-level variable definition into separate files to allow // tree-shaking on each api instance. const metrics_1 = __nccwpck_require__(8692); /** Entrypoint for metrics API */ exports.metrics = metrics_1.MetricsAPI.getInstance(); //# sourceMappingURL=metrics-api.js.map /***/ }), /***/ 3814: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ValueType = void 0; /** The Type of value. It describes how the data is reported. */ var ValueType; (function (ValueType) { ValueType[ValueType["INT"] = 0] = "INT"; ValueType[ValueType["DOUBLE"] = 1] = "DOUBLE"; })(ValueType = exports.ValueType || (exports.ValueType = {})); //# sourceMappingURL=Metric.js.map /***/ }), /***/ 7017: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createNoopMeter = exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = exports.NOOP_OBSERVABLE_GAUGE_METRIC = exports.NOOP_OBSERVABLE_COUNTER_METRIC = exports.NOOP_UP_DOWN_COUNTER_METRIC = exports.NOOP_HISTOGRAM_METRIC = exports.NOOP_COUNTER_METRIC = exports.NOOP_METER = exports.NoopObservableUpDownCounterMetric = exports.NoopObservableGaugeMetric = exports.NoopObservableCounterMetric = exports.NoopObservableMetric = exports.NoopHistogramMetric = exports.NoopUpDownCounterMetric = exports.NoopCounterMetric = exports.NoopMetric = exports.NoopMeter = void 0; /** * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses * constant NoopMetrics for all of its methods. */ class NoopMeter { constructor() { } /** * @see {@link Meter.createHistogram} */ createHistogram(_name, _options) { return exports.NOOP_HISTOGRAM_METRIC; } /** * @see {@link Meter.createCounter} */ createCounter(_name, _options) { return exports.NOOP_COUNTER_METRIC; } /** * @see {@link Meter.createUpDownCounter} */ createUpDownCounter(_name, _options) { return exports.NOOP_UP_DOWN_COUNTER_METRIC; } /** * @see {@link Meter.createObservableGauge} */ createObservableGauge(_name, _options) { return exports.NOOP_OBSERVABLE_GAUGE_METRIC; } /** * @see {@link Meter.createObservableCounter} */ createObservableCounter(_name, _options) { return exports.NOOP_OBSERVABLE_COUNTER_METRIC; } /** * @see {@link Meter.createObservableUpDownCounter} */ createObservableUpDownCounter(_name, _options) { return exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC; } /** * @see {@link Meter.addBatchObservableCallback} */ addBatchObservableCallback(_callback, _observables) { } /** * @see {@link Meter.removeBatchObservableCallback} */ removeBatchObservableCallback(_callback) { } } exports.NoopMeter = NoopMeter; class NoopMetric { } exports.NoopMetric = NoopMetric; class NoopCounterMetric extends NoopMetric { add(_value, _attributes) { } } exports.NoopCounterMetric = NoopCounterMetric; class NoopUpDownCounterMetric extends NoopMetric { add(_value, _attributes) { } } exports.NoopUpDownCounterMetric = NoopUpDownCounterMetric; class NoopHistogramMetric extends NoopMetric { record(_value, _attributes) { } } exports.NoopHistogramMetric = NoopHistogramMetric; class NoopObservableMetric { addCallback(_callback) { } removeCallback(_callback) { } } exports.NoopObservableMetric = NoopObservableMetric; class NoopObservableCounterMetric extends NoopObservableMetric { } exports.NoopObservableCounterMetric = NoopObservableCounterMetric; class NoopObservableGaugeMetric extends NoopObservableMetric { } exports.NoopObservableGaugeMetric = NoopObservableGaugeMetric; class NoopObservableUpDownCounterMetric extends NoopObservableMetric { } exports.NoopObservableUpDownCounterMetric = NoopObservableUpDownCounterMetric; exports.NOOP_METER = new NoopMeter(); // Synchronous instruments exports.NOOP_COUNTER_METRIC = new NoopCounterMetric(); exports.NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric(); exports.NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric(); // Asynchronous instruments exports.NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric(); exports.NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric(); exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric(); /** * Create a no-op Meter */ function createNoopMeter() { return exports.NOOP_METER; } exports.createNoopMeter = createNoopMeter; //# sourceMappingURL=NoopMeter.js.map /***/ }), /***/ 2896: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NOOP_METER_PROVIDER = exports.NoopMeterProvider = void 0; const NoopMeter_1 = __nccwpck_require__(7017); /** * An implementation of the {@link MeterProvider} which returns an impotent Meter * for all calls to `getMeter` */ class NoopMeterProvider { getMeter(_name, _version, _options) { return NoopMeter_1.NOOP_METER; } } exports.NoopMeterProvider = NoopMeterProvider; exports.NOOP_METER_PROVIDER = new NoopMeterProvider(); //# sourceMappingURL=NoopMeterProvider.js.map /***/ }), /***/ 9932: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 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 __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__(2921), exports); //# sourceMappingURL=index.js.map /***/ }), /***/ 114: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports._globalThis = void 0; /** only globals that common to node and browsers are allowed */ // eslint-disable-next-line node/no-unsupported-features/es-builtins exports._globalThis = typeof globalThis === 'object' ? globalThis : global; //# sourceMappingURL=globalThis.js.map /***/ }), /***/ 2921: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 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 __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__(114), exports); //# sourceMappingURL=index.js.map /***/ }), /***/ 6389: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.propagation = void 0; // Split module-level variable definition into separate files to allow // tree-shaking on each api instance. const propagation_1 = __nccwpck_require__(7); /** Entrypoint for propagation API */ exports.propagation = propagation_1.PropagationAPI.getInstance(); //# sourceMappingURL=propagation-api.js.map /***/ }), /***/ 4353: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopTextMapPropagator = void 0; /** * No-op implementations of {@link TextMapPropagator}. */ class NoopTextMapPropagator { /** Noop inject function does nothing */ inject(_context, _carrier) { } /** Noop extract function does nothing and returns the input context */ extract(context, _carrier) { return context; } fields() { return []; } } exports.NoopTextMapPropagator = NoopTextMapPropagator; //# sourceMappingURL=NoopTextMapPropagator.js.map /***/ }), /***/ 7865: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.defaultTextMapSetter = exports.defaultTextMapGetter = void 0; exports.defaultTextMapGetter = { get(carrier, key) { if (carrier == null) { return undefined; } return carrier[key]; }, keys(carrier) { if (carrier == null) { return []; } return Object.keys(carrier); }, }; exports.defaultTextMapSetter = { set(carrier, key, value) { if (carrier == null) { return; } carrier[key] = value; }, }; //# sourceMappingURL=TextMapPropagator.js.map /***/ }), /***/ 6542: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.trace = void 0; // Split module-level variable definition into separate files to allow // tree-shaking on each api instance. const trace_1 = __nccwpck_require__(4508); /** Entrypoint for trace API */ exports.trace = trace_1.TraceAPI.getInstance(); //# sourceMappingURL=trace-api.js.map /***/ }), /***/ 7168: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NonRecordingSpan = void 0; const invalid_span_constants_1 = __nccwpck_require__(7088); /** * The NonRecordingSpan is the default {@link Span} that is used when no Span * implementation is available. All operations are no-op including context * propagation. */ class NonRecordingSpan { constructor(_spanContext = invalid_span_constants_1.INVALID_SPAN_CONTEXT) { this._spanContext = _spanContext; } // Returns a SpanContext. spanContext() { return this._spanContext; } // By default does nothing setAttribute(_key, _value) { return this; } // By default does nothing setAttributes(_attributes) { return this; } // By default does nothing addEvent(_name, _attributes) { return this; } // By default does nothing setStatus(_status) { return this; } // By default does nothing updateName(_name) { return this; } // By default does nothing end(_endTime) { } // isRecording always returns false for NonRecordingSpan. isRecording() { return false; } // By default does nothing recordException(_exception, _time) { } } exports.NonRecordingSpan = NonRecordingSpan; //# sourceMappingURL=NonRecordingSpan.js.map /***/ }), /***/ 9051: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopTracer = void 0; const context_1 = __nccwpck_require__(9750); const context_utils_1 = __nccwpck_require__(2771); const NonRecordingSpan_1 = __nccwpck_require__(7168); const spancontext_utils_1 = __nccwpck_require__(639); const contextApi = context_1.ContextAPI.getInstance(); /** * No-op implementations of {@link Tracer}. */ class NoopTracer { // startSpan starts a noop span. startSpan(name, options, context = contextApi.active()) { const root = Boolean(options === null || options === void 0 ? void 0 : options.root); if (root) { return new NonRecordingSpan_1.NonRecordingSpan(); } const parentFromContext = context && (0, context_utils_1.getSpanContext)(context); if (isSpanContext(parentFromContext) && (0, spancontext_utils_1.isSpanContextValid)(parentFromContext)) { return new NonRecordingSpan_1.NonRecordingSpan(parentFromContext); } else { return new NonRecordingSpan_1.NonRecordingSpan(); } } startActiveSpan(name, arg2, arg3, arg4) { let opts; let ctx; let fn; if (arguments.length < 2) { return; } else if (arguments.length === 2) { fn = arg2; } else if (arguments.length === 3) { opts = arg2; fn = arg3; } else { opts = arg2; ctx = arg3; fn = arg4; } const parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active(); const span = this.startSpan(name, opts, parentContext); const contextWithSpanSet = (0, context_utils_1.setSpan)(parentContext, span); return contextApi.with(contextWithSpanSet, fn, undefined, span); } } exports.NoopTracer = NoopTracer; function isSpanContext(spanContext) { return (typeof spanContext === 'object' && typeof spanContext['spanId'] === 'string' && typeof spanContext['traceId'] === 'string' && typeof spanContext['traceFlags'] === 'number'); } //# sourceMappingURL=NoopTracer.js.map /***/ }), /***/ 4602: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopTracerProvider = void 0; const NoopTracer_1 = __nccwpck_require__(9051); /** * An implementation of the {@link TracerProvider} which returns an impotent * Tracer for all calls to `getTracer`. * * All operations are no-op. */ class NoopTracerProvider { getTracer(_name, _version, _options) { return new NoopTracer_1.NoopTracer(); } } exports.NoopTracerProvider = NoopTracerProvider; //# sourceMappingURL=NoopTracerProvider.js.map /***/ }), /***/ 4833: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProxyTracer = void 0; const NoopTracer_1 = __nccwpck_require__(9051); const NOOP_TRACER = new NoopTracer_1.NoopTracer(); /** * Proxy tracer provided by the proxy tracer provider */ class ProxyTracer { constructor(_provider, name, version, options) { this._provider = _provider; this.name = name; this.version = version; this.options = options; } startSpan(name, options, context) { return this._getTracer().startSpan(name, options, context); } startActiveSpan(_name, _options, _context, _fn) { const tracer = this._getTracer(); return Reflect.apply(tracer.startActiveSpan, tracer, arguments); } /** * Try to get a tracer from the proxy tracer provider. * If the proxy tracer provider has no delegate, return a noop tracer. */ _getTracer() { if (this._delegate) { return this._delegate; } const tracer = this._provider.getDelegateTracer(this.name, this.version, this.options); if (!tracer) { return NOOP_TRACER; } this._delegate = tracer; return this._delegate; } } exports.ProxyTracer = ProxyTracer; //# sourceMappingURL=ProxyTracer.js.map /***/ }), /***/ 312: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProxyTracerProvider = void 0; const ProxyTracer_1 = __nccwpck_require__(4833); const NoopTracerProvider_1 = __nccwpck_require__(4602); const NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider(); /** * Tracer provider which provides {@link ProxyTracer}s. * * Before a delegate is set, tracers provided are NoOp. * When a delegate is set, traces are provided from the delegate. * When a delegate is set after tracers have already been provided, * all tracers already provided will use the provided delegate implementation. */ class ProxyTracerProvider { /** * Get a {@link ProxyTracer} */ getTracer(name, version, options) { var _a; return ((_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer_1.ProxyTracer(this, name, version, options)); } getDelegate() { var _a; return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER; } /** * Set the delegate tracer provider */ setDelegate(delegate) { this._delegate = delegate; } getDelegateTracer(name, version, options) { var _a; return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options); } } exports.ProxyTracerProvider = ProxyTracerProvider; //# sourceMappingURL=ProxyTracerProvider.js.map /***/ }), /***/ 434: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SamplingDecision = void 0; /** * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead. * A sampling decision that determines how a {@link Span} will be recorded * and collected. */ var SamplingDecision; (function (SamplingDecision) { /** * `Span.isRecording() === false`, span will not be recorded and all events * and attributes will be dropped. */ SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD"; /** * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags} * MUST NOT be set. */ SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD"; /** * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags} * MUST be set. */ SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED"; })(SamplingDecision = exports.SamplingDecision || (exports.SamplingDecision = {})); //# sourceMappingURL=SamplingResult.js.map /***/ }), /***/ 2771: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getActiveSpan = exports.getSpan = void 0; const context_1 = __nccwpck_require__(7977); const NonRecordingSpan_1 = __nccwpck_require__(7168); const context_2 = __nccwpck_require__(9750); /** * span key */ const SPAN_KEY = (0, context_1.createContextKey)('OpenTelemetry Context Key SPAN'); /** * Return the span if one exists * * @param context context to get span from */ function getSpan(context) { return context.getValue(SPAN_KEY) || undefined; } exports.getSpan = getSpan; /** * Gets the span from the current context, if one exists. */ function getActiveSpan() { return getSpan(context_2.ContextAPI.getInstance().active()); } exports.getActiveSpan = getActiveSpan; /** * Set the span on a context * * @param context context to use as parent * @param span span to set active */ function setSpan(context, span) { return context.setValue(SPAN_KEY, span); } exports.setSpan = setSpan; /** * Remove current span stored in the context * * @param context context to delete span from */ function deleteSpan(context) { return context.deleteValue(SPAN_KEY); } exports.deleteSpan = deleteSpan; /** * 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 setSpan(context, new NonRecordingSpan_1.NonRecordingSpan(spanContext)); } exports.setSpanContext = setSpanContext; /** * Get the span context of the span if it exists. * * @param context context to get values from */ function getSpanContext(context) { var _a; return (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.spanContext(); } exports.getSpanContext = getSpanContext; //# sourceMappingURL=context-utils.js.map /***/ }), /***/ 7903: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TraceStateImpl = void 0; const tracestate_validators_1 = __nccwpck_require__(5618); const MAX_TRACE_STATE_ITEMS = 32; const MAX_TRACE_STATE_LEN = 512; const LIST_MEMBERS_SEPARATOR = ','; const LIST_MEMBER_KEY_VALUE_SPLITTER = '='; /** * TraceState must be a class and not a simple object type because of the spec * requirement (https://www.w3.org/TR/trace-context/#tracestate-field). * * Here is the list of allowed mutations: * - New key-value pair should be added into the beginning of the list * - The value of any key can be updated. Modified keys MUST be moved to the * beginning of the list. */ class TraceStateImpl { constructor(rawTraceState) { this._internalState = new Map(); if (rawTraceState) this._parse(rawTraceState); } set(key, value) { // TODO: Benchmark the different approaches(map vs list) and // use the faster one. const traceState = this._clone(); if (traceState._internalState.has(key)) { traceState._internalState.delete(key); } traceState._internalState.set(key, value); return traceState; } unset(key) { const traceState = this._clone(); traceState._internalState.delete(key); return traceState; } get(key) { return this._internalState.get(key); } serialize() { return this._keys() .reduce((agg, key) => { agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key)); return agg; }, []) .join(LIST_MEMBERS_SEPARATOR); } _parse(rawTraceState) { if (rawTraceState.length > MAX_TRACE_STATE_LEN) return; this._internalState = rawTraceState .split(LIST_MEMBERS_SEPARATOR) .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning .reduce((agg, part) => { const listMember = part.trim(); // Optional Whitespace (OWS) handling const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER); if (i !== -1) { const key = listMember.slice(0, i); const value = listMember.slice(i + 1, part.length); if ((0, tracestate_validators_1.validateKey)(key) && (0, tracestate_validators_1.validateValue)(value)) { agg.set(key, value); } else { // TODO: Consider to add warning log } } return agg; }, new Map()); // Because of the reverse() requirement, trunc must be done after map is created if (this._internalState.size > MAX_TRACE_STATE_ITEMS) { this._internalState = new Map(Array.from(this._internalState.entries()) .reverse() // Use reverse same as original tracestate parse chain .slice(0, MAX_TRACE_STATE_ITEMS)); } } _keys() { return Array.from(this._internalState.keys()).reverse(); } _clone() { const traceState = new TraceStateImpl(); traceState._internalState = new Map(this._internalState); return traceState; } } exports.TraceStateImpl = TraceStateImpl; //# sourceMappingURL=tracestate-impl.js.map /***/ }), /***/ 5618: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.validateValue = exports.validateKey = void 0; const VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]'; const VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`; const VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`; const VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`); const VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/; const INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/; /** * Key is opaque string up to 256 characters printable. It MUST begin with a * lowercase letter, and can only contain lowercase letters a-z, digits 0-9, * underscores _, dashes -, asterisks *, and forward slashes /. * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key. * see https://www.w3.org/TR/trace-context/#key */ function validateKey(key) { return VALID_KEY_REGEX.test(key); } exports.validateKey = validateKey; /** * Value is opaque string up to 256 characters printable ASCII RFC0020 * characters (i.e., the range 0x20 to 0x7E) except comma , and =. */ function validateValue(value) { return (VALID_VALUE_BASE_REGEX.test(value) && !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)); } exports.validateValue = validateValue; //# sourceMappingURL=tracestate-validators.js.map /***/ }), /***/ 969: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createTraceState = void 0; const tracestate_impl_1 = __nccwpck_require__(7903); function createTraceState(rawTraceState) { return new tracestate_impl_1.TraceStateImpl(rawTraceState); } exports.createTraceState = createTraceState; //# sourceMappingURL=utils.js.map /***/ }), /***/ 7088: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0; const trace_flags_1 = __nccwpck_require__(7221); exports.INVALID_SPANID = '0000000000000000'; exports.INVALID_TRACEID = '00000000000000000000000000000000'; exports.INVALID_SPAN_CONTEXT = { traceId: exports.INVALID_TRACEID, spanId: exports.INVALID_SPANID, traceFlags: trace_flags_1.TraceFlags.NONE, }; //# sourceMappingURL=invalid-span-constants.js.map /***/ }), /***/ 2347: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SpanKind = void 0; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var SpanKind; (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"; })(SpanKind = exports.SpanKind || (exports.SpanKind = {})); //# sourceMappingURL=span_kind.js.map /***/ }), /***/ 639: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.wrapSpanContext = exports.isSpanContextValid = exports.isValidSpanId = exports.isValidTraceId = void 0; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const invalid_span_constants_1 = __nccwpck_require__(7088); const NonRecordingSpan_1 = __nccwpck_require__(7168); const VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; const VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; function isValidTraceId(traceId) { return VALID_TRACEID_REGEX.test(traceId) && traceId !== invalid_span_constants_1.INVALID_TRACEID; } exports.isValidTraceId = isValidTraceId; function isValidSpanId(spanId) { return VALID_SPANID_REGEX.test(spanId) && spanId !== invalid_span_constants_1.INVALID_SPANID; } exports.isValidSpanId = isValidSpanId; /** * Returns true if this {@link SpanContext} is valid. * @return true if this {@link SpanContext} is valid. */ function isSpanContextValid(spanContext) { return (isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId)); } exports.isSpanContextValid = isSpanContextValid; /** * Wrap the given {@link SpanContext} in a new non-recording {@link Span} * * @param spanContext span context to be wrapped * @returns a new non-recording {@link Span} with the provided context */ function wrapSpanContext(spanContext) { return new NonRecordingSpan_1.NonRecordingSpan(spanContext); } exports.wrapSpanContext = wrapSpanContext; //# sourceMappingURL=spancontext-utils.js.map /***/ }), /***/ 1524: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SpanStatusCode = void 0; /** * An enumeration of status codes. */ var SpanStatusCode; (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"; })(SpanStatusCode = exports.SpanStatusCode || (exports.SpanStatusCode = {})); //# sourceMappingURL=status.js.map /***/ }), /***/ 7221: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TraceFlags = void 0; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var TraceFlags; (function (TraceFlags) { /** Represents no flag set. */ TraceFlags[TraceFlags["NONE"] = 0] = "NONE"; /** Bit to represent whether trace is sampled in trace flags. */ TraceFlags[TraceFlags["SAMPLED"] = 1] = "SAMPLED"; })(TraceFlags = exports.TraceFlags || (exports.TraceFlags = {})); //# sourceMappingURL=trace_flags.js.map /***/ }), /***/ 9390: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.VERSION = void 0; // this is autogenerated file, see scripts/version-update.js exports.VERSION = '1.4.0'; //# sourceMappingURL=version.js.map /***/ }), /***/ 7889: /***/ (function(__unused_webpack_module, exports) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.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; /***/ }), /***/ 1409: /***/ ((__unused_webpack_module, exports) => { "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 = {})); /** * 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; /***/ }), /***/ 6826: /***/ (function(__unused_webpack_module, exports) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DuplexStreamingCall = void 0; /** * 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. */ 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; } /** * 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; /***/ }), /***/ 4420: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // 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__(6892); Object.defineProperty(exports, "ServiceType", ({ enumerable: true, get: function () { return service_type_1.ServiceType; } })); var reflection_info_1 = __nccwpck_require__(2496); 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__(8636); Object.defineProperty(exports, "RpcError", ({ enumerable: true, get: function () { return rpc_error_1.RpcError; } })); var rpc_options_1 = __nccwpck_require__(8576); Object.defineProperty(exports, "mergeRpcOptions", ({ enumerable: true, get: function () { return rpc_options_1.mergeRpcOptions; } })); var rpc_output_stream_1 = __nccwpck_require__(2726); Object.defineProperty(exports, "RpcOutputStreamController", ({ enumerable: true, get: function () { return rpc_output_stream_1.RpcOutputStreamController; } })); var test_transport_1 = __nccwpck_require__(9122); Object.defineProperty(exports, "TestTransport", ({ enumerable: true, get: function () { return test_transport_1.TestTransport; } })); var deferred_1 = __nccwpck_require__(1409); 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__(6826); Object.defineProperty(exports, "DuplexStreamingCall", ({ enumerable: true, get: function () { return duplex_streaming_call_1.DuplexStreamingCall; } })); var client_streaming_call_1 = __nccwpck_require__(7889); Object.defineProperty(exports, "ClientStreamingCall", ({ enumerable: true, get: function () { return client_streaming_call_1.ClientStreamingCall; } })); var server_streaming_call_1 = __nccwpck_require__(6173); Object.defineProperty(exports, "ServerStreamingCall", ({ enumerable: true, get: function () { return server_streaming_call_1.ServerStreamingCall; } })); var unary_call_1 = __nccwpck_require__(9288); Object.defineProperty(exports, "UnaryCall", ({ enumerable: true, get: function () { return unary_call_1.UnaryCall; } })); var rpc_interceptor_1 = __nccwpck_require__(2849); 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__(3352); Object.defineProperty(exports, "ServerCallContextController", ({ enumerable: true, get: function () { return server_call_context_1.ServerCallContextController; } })); /***/ }), /***/ 2496: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.readServiceOption = exports.readMethodOption = exports.readMethodOptions = exports.normalizeMethodInfo = void 0; const runtime_1 = __nccwpck_require__(8886); /** * 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. * * @deprecated use readMethodOption() */ 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; } const optionVal = options[extensionName]; if (optionVal === undefined) { return optionVal; } return extensionType ? extensionType.fromJson(optionVal) : optionVal; } 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; /***/ }), /***/ 8636: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.RpcError = void 0; /** * An error that occurred while calling a RPC method. */ 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'); } } exports.RpcError = RpcError; /***/ }), /***/ 2849: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.stackDuplexStreamingInterceptors = exports.stackClientStreamingInterceptors = exports.stackServerStreamingInterceptors = exports.stackUnaryInterceptors = exports.stackIntercept = void 0; const runtime_1 = __nccwpck_require__(8886); /** * Creates a "stack" of of all interceptors specified in the given `RpcOptions`. * Used by generated client implementations. * @internal */ 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; /***/ }), /***/ 8576: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.mergeRpcOptions = void 0; const runtime_1 = __nccwpck_require__(8886); /** * 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; 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; } } /***/ }), /***/ 2726: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.RpcOutputStreamController = void 0; const deferred_1 = __nccwpck_require__(1409); const runtime_1 = __nccwpck_require__(8886); /** * A `RpcOutputStream` that you control. */ 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; /***/ }), /***/ 3352: /***/ ((__unused_webpack_module, exports) => { "use strict"; 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; } /** * 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; /***/ }), /***/ 6173: /***/ (function(__unused_webpack_module, exports) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ServerStreamingCall = void 0; /** * A server streaming RPC call. The client provides exactly one input message * but the server may respond with 0, 1, or more messages. */ 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; /***/ }), /***/ 6892: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ServiceType = void 0; const reflection_info_1 = __nccwpck_require__(2496); 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; /***/ }), /***/ 9122: /***/ (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.TestTransport = void 0; const rpc_error_1 = __nccwpck_require__(8636); const runtime_1 = __nccwpck_require__(8886); const rpc_output_stream_1 = __nccwpck_require__(2726); const rpc_options_1 = __nccwpck_require__(8576); const unary_call_1 = __nccwpck_require__(9288); const server_streaming_call_1 = __nccwpck_require__(6173); const client_streaming_call_1 = __nccwpck_require__(7889); const duplex_streaming_call_1 = __nccwpck_require__(6826); /** * 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 : {}; } /** * Sent message(s) during the last operation. */ get sentMessages() { if (this.lastInput instanceof TestInputStream) { return this.lastInput.sent; } else if (typeof this.lastInput == "object") { return [this.lastInput.single]; } return []; } /** * 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); } } 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")); }); } } }); } 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)); } } /***/ }), /***/ 9288: /***/ (function(__unused_webpack_module, exports) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.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; /***/ }), /***/ 8602: /***/ ((__unused_webpack_module, exports) => { "use strict"; 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; /***/ }), /***/ 6335: /***/ ((__unused_webpack_module, exports) => { "use strict"; 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; } } 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; /***/ }), /***/ 4816: /***/ ((__unused_webpack_module, exports) => { "use strict"; 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 = {})); /***/ }), /***/ 2889: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BinaryReader = exports.binaryReadOptions = void 0; const binary_format_contract_1 = __nccwpck_require__(4816); const pb_long_1 = __nccwpck_require__(1753); const goog_varint_1 = __nccwpck_require__(3223); 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; } 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; /***/ }), /***/ 3957: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BinaryWriter = exports.binaryWriteOptions = void 0; const pb_long_1 = __nccwpck_require__(1753); const goog_varint_1 = __nccwpck_require__(3223); const assert_1 = __nccwpck_require__(8602); 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; /***/ }), /***/ 257: /***/ ((__unused_webpack_module, exports) => { "use strict"; 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; } 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; } 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); } 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; /***/ }), /***/ 3223: /***/ ((__unused_webpack_module, exports) => { "use strict"; // 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]; } } 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]; } } 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; } } 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; /***/ }), /***/ 8886: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // 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__(9999); 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__(6335); 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__(8950); 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__(4816); 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__(2889); 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__(3957); 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__(1753); 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__(9367); 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__(3785); 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__(5106); 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__(7910); 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__(5167); Object.defineProperty(exports, "ReflectionTypeCheck", ({ enumerable: true, get: function () { return reflection_type_check_1.ReflectionTypeCheck; } })); var reflection_create_1 = __nccwpck_require__(5726); Object.defineProperty(exports, "reflectionCreate", ({ enumerable: true, get: function () { return reflection_create_1.reflectionCreate; } })); var reflection_scalar_default_1 = __nccwpck_require__(9526); Object.defineProperty(exports, "reflectionScalarDefault", ({ enumerable: true, get: function () { return reflection_scalar_default_1.reflectionScalarDefault; } })); var reflection_merge_partial_1 = __nccwpck_require__(8044); Object.defineProperty(exports, "reflectionMergePartial", ({ enumerable: true, get: function () { return reflection_merge_partial_1.reflectionMergePartial; } })); var reflection_equals_1 = __nccwpck_require__(4827); Object.defineProperty(exports, "reflectionEquals", ({ enumerable: true, get: function () { return reflection_equals_1.reflectionEquals; } })); var reflection_binary_reader_1 = __nccwpck_require__(9611); Object.defineProperty(exports, "ReflectionBinaryReader", ({ enumerable: true, get: function () { return reflection_binary_reader_1.ReflectionBinaryReader; } })); var reflection_binary_writer_1 = __nccwpck_require__(6907); Object.defineProperty(exports, "ReflectionBinaryWriter", ({ enumerable: true, get: function () { return reflection_binary_writer_1.ReflectionBinaryWriter; } })); var reflection_json_reader_1 = __nccwpck_require__(6790); Object.defineProperty(exports, "ReflectionJsonReader", ({ enumerable: true, get: function () { return reflection_json_reader_1.ReflectionJsonReader; } })); var reflection_json_writer_1 = __nccwpck_require__(1094); Object.defineProperty(exports, "ReflectionJsonWriter", ({ enumerable: true, get: function () { return reflection_json_writer_1.ReflectionJsonWriter; } })); var reflection_contains_message_type_1 = __nccwpck_require__(7565); Object.defineProperty(exports, "containsMessageType", ({ enumerable: true, get: function () { return reflection_contains_message_type_1.containsMessageType; } })); // Oneof helpers var oneof_1 = __nccwpck_require__(8063); 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__(257); 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__(4073); 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__(8602); 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; } })); /***/ }), /***/ 9367: /***/ ((__unused_webpack_module, exports) => { "use strict"; 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; /***/ }), /***/ 9999: /***/ ((__unused_webpack_module, exports) => { "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; /***/ }), /***/ 4073: /***/ ((__unused_webpack_module, exports) => { "use strict"; 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; /***/ }), /***/ 3785: /***/ ((__unused_webpack_module, exports) => { "use strict"; 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"); /***/ }), /***/ 5106: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MessageType = void 0; const message_type_contract_1 = __nccwpck_require__(3785); const reflection_info_1 = __nccwpck_require__(7910); const reflection_type_check_1 = __nccwpck_require__(5167); const reflection_json_reader_1 = __nccwpck_require__(6790); const reflection_json_writer_1 = __nccwpck_require__(1094); const reflection_binary_reader_1 = __nccwpck_require__(9611); const reflection_binary_writer_1 = __nccwpck_require__(6907); const reflection_create_1 = __nccwpck_require__(5726); const reflection_merge_partial_1 = __nccwpck_require__(8044); const json_typings_1 = __nccwpck_require__(9999); const json_format_contract_1 = __nccwpck_require__(9367); const reflection_equals_1 = __nccwpck_require__(4827); const binary_writer_1 = __nccwpck_require__(3957); const binary_reader_1 = __nccwpck_require__(2889); 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); } 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; } } exports.MessageType = MessageType; /***/ }), /***/ 8063: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); 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; } } exports.isOneofGroup = isOneofGroup; /** * Returns the value of the given field in a oneof group. */ function getOneofValue(oneof, kind) { return oneof[kind]; } 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; } } 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; } } 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; } 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; /***/ }), /***/ 1753: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PbLong = exports.PbULong = exports.detectBi = void 0; const goog_varint_1 = __nccwpck_require__(3223); 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; } } /** * 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 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); } } 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); } /** * Do we have a minus sign? */ isNegative() { return (this.hi & HALF_2_PWR_32) !== 0; } /** * 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); } /** * 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); } /** * 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); /***/ }), /***/ 8950: /***/ ((__unused_webpack_module, exports) => { "use strict"; // 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; } } if (parts.length) { if (i) parts.push(fromCharCodes(chunk.slice(0, i))); return parts.join(""); } return fromCharCodes(chunk.slice(0, i)); } exports.utf8read = utf8read; /***/ }), /***/ 9611: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReflectionBinaryReader = void 0; const binary_format_contract_1 = __nccwpck_require__(4816); const reflection_info_1 = __nccwpck_require__(7910); const reflection_long_convert_1 = __nccwpck_require__(3402); const reflection_scalar_default_1 = __nccwpck_require__(9526); /** * Reads proto3 messages in binary format using reflection information. * * https://developers.google.com/protocol-buffers/docs/encoding */ class ReflectionBinaryReader { constructor(info) { this.info = info; } 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])); } } /** * 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; } } } /** * 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]; } 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; /***/ }), /***/ 6907: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReflectionBinaryWriter = void 0; const binary_format_contract_1 = __nccwpck_require__(4816); const reflection_info_1 = __nccwpck_require__(7910); const assert_1 = __nccwpck_require__(8602); const pb_long_1 = __nccwpck_require__(1753); /** * 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; /***/ }), /***/ 7565: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.containsMessageType = void 0; const message_type_contract_1 = __nccwpck_require__(3785); /** * 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; /***/ }), /***/ 5726: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.reflectionCreate = void 0; const reflection_scalar_default_1 = __nccwpck_require__(9526); const message_type_contract_1 = __nccwpck_require__(3785); /** * 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; /***/ }), /***/ 4827: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.reflectionEquals = void 0; const reflection_info_1 = __nccwpck_require__(7910); /** * 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; } 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; } /***/ }), /***/ 7910: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.readMessageOption = exports.readFieldOption = exports.readFieldOptions = exports.normalizeFieldInfo = exports.RepeatType = exports.LongType = exports.ScalarType = void 0; const lower_camel_case_1 = __nccwpck_require__(4073); /** * 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; /***/ }), /***/ 6790: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReflectionJsonReader = void 0; const json_typings_1 = __nccwpck_require__(9999); const base64_1 = __nccwpck_require__(6335); const reflection_info_1 = __nccwpck_require__(7910); const pb_long_1 = __nccwpck_require__(1753); const assert_1 = __nccwpck_require__(8602); const reflection_long_convert_1 = __nccwpck_require__(3402); /** * 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; /***/ }), /***/ 1094: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReflectionJsonWriter = void 0; const base64_1 = __nccwpck_require__(6335); const pb_long_1 = __nccwpck_require__(1753); const reflection_info_1 = __nccwpck_require__(7910); const assert_1 = __nccwpck_require__(8602); /** * 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 : []; } /** * 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; /***/ }), /***/ 3402: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.reflectionLongConvert = void 0; const reflection_info_1 = __nccwpck_require__(7910); /** * 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; /***/ }), /***/ 8044: /***/ ((__unused_webpack_module, exports) => { "use strict"; 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; /***/ }), /***/ 9526: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.reflectionScalarDefault = void 0; const reflection_info_1 = __nccwpck_require__(7910); const reflection_long_convert_1 = __nccwpck_require__(3402); const pb_long_1 = __nccwpck_require__(1753); /** * 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; /***/ }), /***/ 5167: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReflectionTypeCheck = void 0; const reflection_info_1 = __nccwpck_require__(7910); const oneof_1 = __nccwpck_require__(8063); // 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); } } } exports.ReflectionTypeCheck = ReflectionTypeCheck; /***/ }), /***/ 8662: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); function once(emitter, name, { signal } = {}) { return new Promise((resolve, reject) => { function cleanup() { signal === null || signal === void 0 ? void 0 : signal.removeEventListener('abort', cleanup); emitter.removeListener(name, onEvent); emitter.removeListener('error', onError); } function onEvent(...args) { cleanup(); resolve(args); } function onError(err) { cleanup(); reject(err); } signal === null || signal === void 0 ? void 0 : signal.addEventListener('abort', cleanup); emitter.on(name, onEvent); emitter.on('error', onError); }); } exports["default"] = once; //# sourceMappingURL=index.js.map /***/ }), /***/ 7413: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; /** * @author Toru Nagashima * See LICENSE file in root directory for full license. */ Object.defineProperty(exports, "__esModule", ({ value: true })); var eventTargetShim = __nccwpck_require__(6577); /** * 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", }); } /** * 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", }); } exports.AbortController = AbortController; exports.AbortSignal = AbortSignal; exports["default"] = AbortController; module.exports = AbortController module.exports.AbortController = module.exports["default"] = AbortController module.exports.AbortSignal = AbortSignal //# sourceMappingURL=abort-controller.js.map /***/ }), /***/ 5183: /***/ (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.req = exports.json = exports.toBuffer = void 0; const http = __importStar(__nccwpck_require__(8611)); const https = __importStar(__nccwpck_require__(5692)); async function toBuffer(stream) { let length = 0; const chunks = []; for await (const chunk of stream) { length += chunk.length; chunks.push(chunk); } return Buffer.concat(chunks, length); } exports.toBuffer = toBuffer; // eslint-disable-next-line @typescript-eslint/no-explicit-any async function json(stream) { const buf = await toBuffer(stream); const str = buf.toString('utf8'); try { return JSON.parse(str); } catch (_err) { const err = _err; err.message += ` (input: ${str})`; throw err; } } exports.json = json; function req(url, opts = {}) { const href = typeof url === 'string' ? url : url.href; const req = (href.startsWith('https:') ? https : http).request(url, opts); const promise = new Promise((resolve, reject) => { req .once('response', resolve) .once('error', reject) .end(); }); req.then = promise.then.bind(promise); return req; } exports.req = req; //# sourceMappingURL=helpers.js.map /***/ }), /***/ 8894: /***/ (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 __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.Agent = void 0; const net = __importStar(__nccwpck_require__(9278)); const http = __importStar(__nccwpck_require__(8611)); const https_1 = __nccwpck_require__(5692); __exportStar(__nccwpck_require__(5183), exports); const INTERNAL = Symbol('AgentBaseInternalState'); class Agent extends http.Agent { constructor(opts) { super(opts); this[INTERNAL] = {}; } /** * Determine whether this is an `http` or `https` request. */ isSecureEndpoint(options) { if (options) { // First check the `secureEndpoint` property explicitly, since this // means that a parent `Agent` is "passing through" to this instance. // eslint-disable-next-line @typescript-eslint/no-explicit-any if (typeof options.secureEndpoint === 'boolean') { return options.secureEndpoint; } // If no explicit `secure` endpoint, check if `protocol` property is // set. This will usually be the case since using a full string URL // or `URL` instance should be the most common usage. if (typeof options.protocol === 'string') { return options.protocol === 'https:'; } } // Finally, if no `protocol` property was set, then fall back to // checking the stack trace of the current call stack, and try to // detect the "https" module. const { stack } = new Error(); if (typeof stack !== 'string') return false; return stack .split('\n') .some((l) => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1); } // In order to support async signatures in `connect()` and Node's native // connection pooling in `http.Agent`, the array of sockets for each origin // has to be updated synchronously. This is so the length of the array is // accurate when `addRequest()` is next called. We achieve this by creating a // fake socket and adding it to `sockets[origin]` and incrementing // `totalSocketCount`. incrementSockets(name) { // If `maxSockets` and `maxTotalSockets` are both Infinity then there is no // need to create a fake socket because Node.js native connection pooling // will never be invoked. if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) { return null; } // All instances of `sockets` are expected TypeScript errors. The // alternative is to add it as a private property of this class but that // will break TypeScript subclassing. if (!this.sockets[name]) { // @ts-expect-error `sockets` is readonly in `@types/node` this.sockets[name] = []; } const fakeSocket = new net.Socket({ writable: false }); this.sockets[name].push(fakeSocket); // @ts-expect-error `totalSocketCount` isn't defined in `@types/node` this.totalSocketCount++; return fakeSocket; } decrementSockets(name, socket) { if (!this.sockets[name] || socket === null) { return; } const sockets = this.sockets[name]; const index = sockets.indexOf(socket); if (index !== -1) { sockets.splice(index, 1); // @ts-expect-error `totalSocketCount` isn't defined in `@types/node` this.totalSocketCount--; if (sockets.length === 0) { // @ts-expect-error `sockets` is readonly in `@types/node` delete this.sockets[name]; } } } // In order to properly update the socket pool, we need to call `getName()` on // the core `https.Agent` if it is a secureEndpoint. getName(options) { const secureEndpoint = typeof options.secureEndpoint === 'boolean' ? options.secureEndpoint : this.isSecureEndpoint(options); if (secureEndpoint) { // @ts-expect-error `getName()` isn't defined in `@types/node` return https_1.Agent.prototype.getName.call(this, options); } // @ts-expect-error `getName()` isn't defined in `@types/node` return super.getName(options); } createSocket(req, options, cb) { const connectOpts = { ...options, secureEndpoint: this.isSecureEndpoint(options), }; const name = this.getName(connectOpts); const fakeSocket = this.incrementSockets(name); Promise.resolve() .then(() => this.connect(req, connectOpts)) .then((socket) => { this.decrementSockets(name, fakeSocket); if (socket instanceof http.Agent) { try { // @ts-expect-error `addRequest()` isn't defined in `@types/node` return socket.addRequest(req, connectOpts); } catch (err) { return cb(err); } } this[INTERNAL].currentSocket = socket; // @ts-expect-error `createSocket()` isn't defined in `@types/node` super.createSocket(req, options, cb); }, (err) => { this.decrementSockets(name, fakeSocket); cb(err); }); } createConnection() { const socket = this[INTERNAL].currentSocket; this[INTERNAL].currentSocket = undefined; if (!socket) { throw new Error('No socket was returned in the `connect()` function'); } return socket; } get defaultPort() { return (this[INTERNAL].defaultPort ?? (this.protocol === 'https:' ? 443 : 80)); } set defaultPort(v) { if (this[INTERNAL]) { this[INTERNAL].defaultPort = v; } } get protocol() { return (this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? 'https:' : 'http:')); } set protocol(v) { if (this[INTERNAL]) { this[INTERNAL].protocol = v; } } } exports.Agent = Agent; //# sourceMappingURL=index.js.map /***/ }), /***/ 6251: /***/ ((module) => { "use strict"; const arrify = value => { if (value === null || value === undefined) { return []; } if (Array.isArray(value)) { return value; } if (typeof value === 'string') { return [value]; } if (typeof value[Symbol.iterator] === 'function') { return [...value]; } return [value]; }; module.exports = arrify; /***/ }), /***/ 5195: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Packages var retrier = __nccwpck_require__(5546); function retry(fn, opts) { function run(resolve, reject) { var options = opts || {}; var op; // Default `randomize` to true if (!('randomize' in options)) { options.randomize = true; } op = retrier.operation(options); // We allow the user to abort retrying // this makes sense in the cases where // knowledge is obtained that retrying // would be futile (e.g.: auth errors) function bail(err) { reject(err || new Error('Aborted')); } function onError(err, num) { if (err.bail) { bail(err); return; } if (!op.retry(err)) { reject(op.mainError()); } else if (options.onRetry) { options.onRetry(err, num); } } function runAttempt(num) { var val; try { val = fn(bail, num); } catch (err) { onError(err, num); return; } Promise.resolve(val) .then(resolve) .catch(function catchIt(err) { onError(err, num); }); } op.attempt(runAttempt); } return new Promise(run); } module.exports = retry; /***/ }), /***/ 1324: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = { parallel : __nccwpck_require__(3857), serial : __nccwpck_require__(1054), serialOrdered : __nccwpck_require__(3961) }; /***/ }), /***/ 4818: /***/ ((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)); // reset leftover jobs state.jobs = {}; } /** * 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](); } } /***/ }), /***/ 8452: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var defer = __nccwpck_require__(9200); // API module.exports = async; /** * 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; // check if async happened defer(function() { isAsync = true; }); return function async_callback(err, result) { if (isAsync) { callback(err, result); } else { defer(function nextTick_callback() { callback(err, result); }); } }; } /***/ }), /***/ 9200: /***/ ((module) => { module.exports = defer; /** * Runs provided function on next iteration of the event loop * * @param {function} fn - function to run */ function defer(fn) { var nextTick = typeof setImmediate == 'function' ? setImmediate : ( typeof process == 'object' && typeof process.nextTick == 'function' ? process.nextTick : null ); if (nextTick) { nextTick(fn); } else { setTimeout(fn, 0); } } /***/ }), /***/ 4902: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var async = __nccwpck_require__(8452) , abort = __nccwpck_require__(4818) ; // API module.exports = iterate; /** * Iterates over each job object * * @param {array|object} list - array or object (named list) to iterate over * @param {function} iterator - iterator to run * @param {object} state - current job status * @param {function} callback - invoked when all elements processed */ function iterate(list, iterator, state, callback) { // store current index var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; 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); } else { state.results[key] = output; } // return salvaged results callback(error, state.results); }); } /** * 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; } /***/ }), /***/ 1721: /***/ ((module) => { // API module.exports = state; /** * Creates initial state object * for iteration over list * * @param {array|object} list - list to iterate over * @param {function|null} sortMethod - function to use for keys sort, * or `null` to keep them as is * @returns {object} - initial state object */ function state(list, sortMethod) { var isNamedList = !Array.isArray(list) , initState = { index : 0, keyedList: isNamedList || sortMethod ? Object.keys(list) : null, jobs : {}, results : isNamedList ? {} : [], size : isNamedList ? Object.keys(list).length : list.length } ; 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; } /***/ }), /***/ 3351: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var abort = __nccwpck_require__(4818) , async = __nccwpck_require__(8452) ; // API module.exports = terminator; /** * Terminates jobs in the attached state context * * @this AsyncKitState# * @param {function} callback - final callback to invoke after termination */ function terminator(callback) { if (!Object.keys(this.jobs).length) { return; } // fast forward iteration index this.index = this.size; // abort jobs abort(this); // send back results we have so far async(callback)(null, this.results); } /***/ }), /***/ 3857: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var iterate = __nccwpck_require__(4902) , initState = __nccwpck_require__(1721) , terminator = __nccwpck_require__(3351) ; // Public API module.exports = parallel; /** * Runs iterator over provided array elements in parallel * * @param {array|object} list - array or object (named list) to iterate over * @param {function} iterator - iterator to run * @param {function} callback - invoked when all elements processed * @returns {function} - jobs terminator */ function parallel(list, iterator, callback) { var state = initState(list); while (state.index < (state['keyedList'] || list).length) { iterate(list, iterator, state, function(error, result) { if (error) { callback(error, result); return; } // looks like it's the last one if (Object.keys(state.jobs).length === 0) { callback(null, state.results); return; } }); state.index++; } return terminator.bind(state, callback); } /***/ }), /***/ 1054: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var serialOrdered = __nccwpck_require__(3961); // Public API module.exports = serial; /** * Runs iterator over provided array elements in series * * @param {array|object} list - array or object (named list) to iterate over * @param {function} iterator - iterator to run * @param {function} callback - invoked when all elements processed * @returns {function} - jobs terminator */ function serial(list, iterator, callback) { return serialOrdered(list, iterator, null, callback); } /***/ }), /***/ 3961: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var iterate = __nccwpck_require__(4902) , initState = __nccwpck_require__(1721) , terminator = __nccwpck_require__(3351) ; // Public API module.exports = serialOrdered; // sorting helpers module.exports.ascending = ascending; module.exports.descending = descending; /** * 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; } state.index++; // are we there yet? if (state.index < (state['keyedList'] || list).length) { iterate(list, iterator, state, iteratorHandler); return; } // done here callback(null, state.results); }); return terminator.bind(state, callback); } /* * -- Sort methods */ /** * 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; } /** * sort helper to sort array elements in descending order * * @param {mixed} a - an item to compare * @param {mixed} b - an item to compare * @returns {number} - comparison result */ function descending(a, b) { return -1 * ascending(a, b); } /***/ }), /***/ 9380: /***/ ((module) => { "use strict"; module.exports = balanced; function balanced(a, b, str) { if (a instanceof RegExp) a = maybeMatch(a, str); if (b instanceof RegExp) b = maybeMatch(b, str); var r = range(a, b, str); return r && { start: r[0], end: r[1], pre: str.slice(0, r[0]), body: str.slice(r[0] + a.length, r[1]), post: str.slice(r[1] + b.length) }; } function maybeMatch(reg, str) { var m = str.match(reg); return m ? m[0] : null; } balanced.range = range; function range(a, b, str) { var begs, beg, left, right, result; var ai = str.indexOf(a); var bi = str.indexOf(b, ai + 1); var i = ai; if (ai >= 0 && bi > 0) { if(a===b) { return [ai, bi]; } 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; } bi = str.indexOf(b, i + 1); } i = ai < bi && ai >= 0 ? ai : bi; } if (begs.length) { result = [ left, right ]; } } return result; } /***/ }), /***/ 8793: /***/ ((__unused_webpack_module, exports) => { "use strict"; exports.byteLength = byteLength exports.toByteArray = toByteArray exports.fromByteArray = fromByteArray var lookup = [] var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i] revLookup[code.charCodeAt(i)] = i } // Support decoding URL-safe base64 strings, as Node.js does. // See: https://en.wikipedia.org/wiki/Base64#URL_applications revLookup['-'.charCodeAt(0)] = 62 revLookup['_'.charCodeAt(0)] = 63 function getLens (b64) { var len = b64.length if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // Trim off extra bytes after placeholder bytes are found // See: https://github.com/beatgammit/base64-js/issues/42 var validLen = b64.indexOf('=') if (validLen === -1) validLen = len var placeHoldersLen = validLen === len ? 0 : 4 - (validLen % 4) return [validLen, placeHoldersLen] } // base64 is 4/3 + up to two characters of the original data function byteLength (b64) { var lens = getLens(b64) var validLen = lens[0] var placeHoldersLen = lens[1] return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen } function _byteLength (b64, validLen, placeHoldersLen) { return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen } function toByteArray (b64) { var tmp var lens = getLens(b64) var validLen = lens[0] var placeHoldersLen = lens[1] var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) var curByte = 0 // if there are placeholders, only get up to the last complete 4 chars var len = placeHoldersLen > 0 ? validLen - 4 : validLen var i for (i = 0; i < len; i += 4) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] arr[curByte++] = (tmp >> 16) & 0xFF arr[curByte++] = (tmp >> 8) & 0xFF arr[curByte++] = tmp & 0xFF } if (placeHoldersLen === 2) { tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) arr[curByte++] = tmp & 0xFF } if (placeHoldersLen === 1) { tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) arr[curByte++] = (tmp >> 8) & 0xFF arr[curByte++] = tmp & 0xFF } return arr } function tripletToBase64 (num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] } function encodeChunk (uint8, start, end) { var tmp var output = [] for (var i = start; i < end; i += 3) { tmp = ((uint8[i] << 16) & 0xFF0000) + ((uint8[i + 1] << 8) & 0xFF00) + (uint8[i + 2] & 0xFF) output.push(tripletToBase64(tmp)) } return output.join('') } function fromByteArray (uint8) { var tmp var len = uint8.length var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes var parts = [] var maxChunkLength = 16383 // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1] parts.push( lookup[tmp >> 2] + lookup[(tmp << 4) & 0x3F] + '==' ) } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + uint8[len - 1] parts.push( lookup[tmp >> 10] + lookup[(tmp >> 4) & 0x3F] + lookup[(tmp << 2) & 0x3F] + '=' ) } return parts.join('') } /***/ }), /***/ 1259: /***/ (function(module) { ;(function (globalObject) { 'use strict'; /* * bignumber.js v9.2.1 * A JavaScript library for arbitrary-precision arithmetic. * https://github.com/MikeMcl/bignumber.js * Copyright (c) 2025 Michael Mclaughlin * MIT Licensed. * * BigNumber.prototype methods | BigNumber methods * | * absoluteValue abs | clone * comparedTo | config set * decimalPlaces dp | DECIMAL_PLACES * dividedBy div | ROUNDING_MODE * dividedToIntegerBy idiv | EXPONENTIAL_AT * exponentiatedBy pow | RANGE * integerValue | CRYPTO * isEqualTo eq | MODULO_MODE * isFinite | POW_PRECISION * isGreaterThan gt | FORMAT * isGreaterThanOrEqualTo gte | ALPHABET * isInteger | isBigNumber * isLessThan lt | maximum max * isLessThanOrEqualTo lte | minimum min * isNaN | random * isNegative | sum * isPositive | * isZero | * minus | * modulo mod | * multipliedBy times | * negated | * plus | * precision sd | * shiftedBy | * squareRoot sqrt | * toExponential | * toFixed | * toFormat | * toFraction | * toJSON | * toNumber | * toPrecision | * toString | * valueOf | * */ var BigNumber, isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, mathceil = Math.ceil, mathfloor = Math.floor, bignumberError = '[BigNumber Error] ', tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', BASE = 1e14, LOG_BASE = 14, MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 // MAX_INT32 = 0x7fffffff, // 2^31 - 1 POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], SQRT_BASE = 1e7, // EDITABLE // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and // the arguments to toExponential, toFixed, toFormat, and toPrecision. MAX = 1E9; // 0 to MAX_INT32 /* * Create and return a BigNumber constructor. */ function clone(configObject) { var div, convertBase, parseNumeric, P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null }, ONE = new BigNumber(1), //----------------------------- EDITABLE CONFIG DEFAULTS ------------------------------- // The default values below must be integers within the inclusive ranges stated. // The values can also be changed at run-time using BigNumber.set. // The maximum number of decimal places for operations involving division. DECIMAL_PLACES = 20, // 0 to MAX // The rounding mode used when rounding to the above decimal places, and when using // toExponential, toFixed, toFormat and toPrecision, and round (default value). // UP 0 Away from zero. // DOWN 1 Towards zero. // CEIL 2 Towards +Infinity. // FLOOR 3 Towards -Infinity. // HALF_UP 4 Towards nearest neighbour. If equidistant, up. // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. ROUNDING_MODE = 4, // 0 to 8 // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] // The exponent value at and beneath which toString returns exponential notation. // Number type: -7 TO_EXP_NEG = -7, // 0 to -MAX // The exponent value at and above which toString returns exponential notation. // Number type: 21 TO_EXP_POS = 21, // 0 to MAX // RANGE : [MIN_EXP, MAX_EXP] // The minimum exponent value, beneath which underflow to zero occurs. // Number type: -324 (5e-324) MIN_EXP = -1e7, // -1 to -MAX // The maximum exponent value, above which overflow to Infinity occurs. // Number type: 308 (1.7976931348623157e+308) // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. MAX_EXP = 1e7, // 1 to MAX // Whether to use cryptographically-secure random number generation, if available. CRYPTO = false, // true or false // The modulo mode used when calculating the modulus: a mod n. // The quotient (q = a / n) is calculated according to the corresponding rounding mode. // The remainder (r) is calculated as: r = a - n * q. // // UP 0 The remainder is positive if the dividend is negative, else is negative. // DOWN 1 The remainder has the same sign as the dividend. // This modulo mode is commonly known as 'truncated division' and is // equivalent to (a % n) in JavaScript. // FLOOR 3 The remainder has the same sign as the divisor (Python %). // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). // The remainder is always positive. // // The truncated division, floored division, Euclidian division and IEEE 754 remainder // modes are commonly used for the modulus operation. // Although the other rounding modes can also be used, they may not give useful results. MODULO_MODE = 1, // 0 to 9 // The maximum number of significant digits of the result of the exponentiatedBy operation. // If POW_PRECISION is 0, there will be unlimited significant digits. POW_PRECISION = 0, // 0 to MAX // The format specification used by the BigNumber.prototype.toFormat method. FORMAT = { prefix: '', groupSize: 3, secondaryGroupSize: 0, groupSeparator: ',', decimalSeparator: '.', fractionGroupSize: 0, fractionGroupSeparator: '\xA0', // non-breaking space suffix: '' }, // The alphabet used for base conversion. It must be at least 2 characters long, with no '+', // '-', '.', whitespace, or repeated character. // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz', alphabetHasNormalDecimalDigits = true; //------------------------------------------------------------------------------------------ // CONSTRUCTOR /* * The BigNumber constructor and exported function. * Create and return a new instance of a BigNumber object. * * v {number|string|BigNumber} A numeric value. * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive. */ function BigNumber(v, b) { var alphabet, c, caseChanged, e, i, isNum, len, str, x = this; // Enable constructor call without `new`. if (!(x instanceof BigNumber)) return new BigNumber(v, b); if (b == null) { if (v && v._isBigNumber === true) { x.s = v.s; if (!v.c || v.e > MAX_EXP) { x.c = x.e = null; } else if (v.e < MIN_EXP) { x.c = [x.e = 0]; } else { x.e = v.e; x.c = v.c.slice(); } return; } if ((isNum = typeof v == 'number') && v * 0 == 0) { // Use `1 / n` to handle minus zero also. x.s = 1 / v < 0 ? (v = -v, -1) : 1; // Fast path for integers, where n < 2147483648 (2**31). if (v === ~~v) { for (e = 0, i = v; i >= 10; i /= 10, e++); if (e > MAX_EXP) { x.c = x.e = null; } else { x.e = e; x.c = [v]; } return; } str = String(v); } else { if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum); x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; } // Decimal point? if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); // Exponential form? if ((i = str.search(/e/i)) > 0) { // Determine exponent. if (e < 0) e = i; e += +str.slice(i + 1); str = str.substring(0, i); } else if (e < 0) { // Integer. e = str.length; } } else { // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' intCheck(b, 2, ALPHABET.length, 'Base'); // Allow exponential notation to be used with base 10 argument, while // also rounding to DECIMAL_PLACES as with other bases. if (b == 10 && alphabetHasNormalDecimalDigits) { x = new BigNumber(v); return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); } str = String(v); if (isNum = typeof v == 'number') { // Avoid potential interpretation of Infinity and NaN as base 44+ values. if (v * 0 != 0) return parseNumeric(x, str, isNum, b); x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) { throw Error (tooManyDigits + v); } } else { x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; } alphabet = ALPHABET.slice(0, b); e = i = 0; // Check that str is a valid base b number. // Don't use RegExp, so alphabet can contain special characters. for (len = str.length; i < len; i++) { if (alphabet.indexOf(c = str.charAt(i)) < 0) { if (c == '.') { // If '.' is not the first character and it has not be found before. if (i > e) { e = len; continue; } } else if (!caseChanged) { // Allow e.g. hexadecimal 'FF' as well as 'ff'. if (str == str.toUpperCase() && (str = str.toLowerCase()) || str == str.toLowerCase() && (str = str.toUpperCase())) { caseChanged = true; i = -1; e = 0; continue; } } return parseNumeric(x, String(v), isNum, b); } } // Prevent later check for length on converted number. isNum = false; str = convertBase(str, b, 10, x.s); // Decimal point? if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); else e = str.length; } // Determine leading zeros. for (i = 0; str.charCodeAt(i) === 48; i++); // Determine trailing zeros. for (len = str.length; str.charCodeAt(--len) === 48;); if (str = str.slice(i, ++len)) { len -= i; // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' if (isNum && BigNumber.DEBUG && len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { throw Error (tooManyDigits + (x.s * v)); } // Overflow? if ((e = e - i - 1) > MAX_EXP) { // Infinity. x.c = x.e = null; // Underflow? } else if (e < MIN_EXP) { // Zero. x.c = [x.e = 0]; } else { x.e = e; x.c = []; // Transform base // e is the base 10 exponent. // i is where to slice str to get the first element of the coefficient array. i = (e + 1) % LOG_BASE; if (e < 0) i += LOG_BASE; // i < 1 if (i < len) { if (i) x.c.push(+str.slice(0, i)); for (len -= LOG_BASE; i < len;) { x.c.push(+str.slice(i, i += LOG_BASE)); } i = LOG_BASE - (str = str.slice(i)).length; } else { i -= len; } for (; i--; str += '0'); x.c.push(+str); } } else { // Zero. x.c = [x.e = 0]; } } // CONSTRUCTOR PROPERTIES BigNumber.clone = clone; BigNumber.ROUND_UP = 0; BigNumber.ROUND_DOWN = 1; BigNumber.ROUND_CEIL = 2; BigNumber.ROUND_FLOOR = 3; BigNumber.ROUND_HALF_UP = 4; BigNumber.ROUND_HALF_DOWN = 5; BigNumber.ROUND_HALF_EVEN = 6; BigNumber.ROUND_HALF_CEIL = 7; BigNumber.ROUND_HALF_FLOOR = 8; BigNumber.EUCLID = 9; /* * Configure infrequently-changing library-wide settings. * * Accept an object with the following optional properties (if the value of a property is * a number, it must be an integer within the inclusive range stated): * * DECIMAL_PLACES {number} 0 to MAX * ROUNDING_MODE {number} 0 to 8 * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX] * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX] * CRYPTO {boolean} true or false * MODULO_MODE {number} 0 to 9 * POW_PRECISION {number} 0 to MAX * ALPHABET {string} A string of two or more unique characters which does * not contain '.'. * FORMAT {object} An object with some of the following properties: * prefix {string} * groupSize {number} * secondaryGroupSize {number} * groupSeparator {string} * decimalSeparator {string} * fractionGroupSize {number} * fractionGroupSeparator {string} * suffix {string} * * (The values assigned to the above FORMAT object properties are not checked for validity.) * * E.g. * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) * * Ignore properties/parameters set to null or undefined, except for ALPHABET. * * Return an object with the properties current values. */ BigNumber.config = BigNumber.set = function (obj) { var p, v; if (obj != null) { if (typeof obj == 'object') { // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}' if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) { v = obj[p]; intCheck(v, 0, MAX, p); DECIMAL_PLACES = v; } // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}' if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) { v = obj[p]; intCheck(v, 0, 8, p); ROUNDING_MODE = v; } // EXPONENTIAL_AT {number|number[]} // Integer, -MAX to MAX inclusive or // [integer -MAX to 0 inclusive, 0 to MAX inclusive]. // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}' if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) { v = obj[p]; if (v && v.pop) { intCheck(v[0], -MAX, 0, p); intCheck(v[1], 0, MAX, p); TO_EXP_NEG = v[0]; TO_EXP_POS = v[1]; } else { intCheck(v, -MAX, MAX, p); TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); } } // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}' if (obj.hasOwnProperty(p = 'RANGE')) { v = obj[p]; if (v && v.pop) { intCheck(v[0], -MAX, -1, p); intCheck(v[1], 1, MAX, p); MIN_EXP = v[0]; MAX_EXP = v[1]; } else { intCheck(v, -MAX, MAX, p); if (v) { MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); } else { throw Error (bignumberError + p + ' cannot be zero: ' + v); } } } // CRYPTO {boolean} true or false. // '[BigNumber Error] CRYPTO not true or false: {v}' // '[BigNumber Error] crypto unavailable' if (obj.hasOwnProperty(p = 'CRYPTO')) { v = obj[p]; if (v === !!v) { if (v) { if (typeof crypto != 'undefined' && crypto && (crypto.getRandomValues || crypto.randomBytes)) { CRYPTO = v; } else { CRYPTO = !v; throw Error (bignumberError + 'crypto unavailable'); } } else { CRYPTO = v; } } else { throw Error (bignumberError + p + ' not true or false: ' + v); } } // MODULO_MODE {number} Integer, 0 to 9 inclusive. // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}' if (obj.hasOwnProperty(p = 'MODULO_MODE')) { v = obj[p]; intCheck(v, 0, 9, p); MODULO_MODE = v; } // POW_PRECISION {number} Integer, 0 to MAX inclusive. // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}' if (obj.hasOwnProperty(p = 'POW_PRECISION')) { v = obj[p]; intCheck(v, 0, MAX, p); POW_PRECISION = v; } // FORMAT {object} // '[BigNumber Error] FORMAT not an object: {v}' if (obj.hasOwnProperty(p = 'FORMAT')) { v = obj[p]; if (typeof v == 'object') FORMAT = v; else throw Error (bignumberError + p + ' not an object: ' + v); } // ALPHABET {string} // '[BigNumber Error] ALPHABET invalid: {v}' if (obj.hasOwnProperty(p = 'ALPHABET')) { v = obj[p]; // Disallow if less than two characters, // or if it contains '+', '-', '.', whitespace, or a repeated character. if (typeof v == 'string' && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) { alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789'; ALPHABET = v; } else { throw Error (bignumberError + p + ' invalid: ' + v); } } } else { // '[BigNumber Error] Object expected: {v}' throw Error (bignumberError + 'Object expected: ' + obj); } } return { DECIMAL_PLACES: DECIMAL_PLACES, ROUNDING_MODE: ROUNDING_MODE, EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], RANGE: [MIN_EXP, MAX_EXP], CRYPTO: CRYPTO, MODULO_MODE: MODULO_MODE, POW_PRECISION: POW_PRECISION, FORMAT: FORMAT, ALPHABET: ALPHABET }; }; /* * Return true if v is a BigNumber instance, otherwise return false. * * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed. * * v {any} * * '[BigNumber Error] Invalid BigNumber: {v}' */ BigNumber.isBigNumber = function (v) { if (!v || v._isBigNumber !== true) return false; if (!BigNumber.DEBUG) return true; var i, n, c = v.c, e = v.e, s = v.s; out: if ({}.toString.call(c) == '[object Array]') { if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) { // If the first element is zero, the BigNumber value must be zero. if (c[0] === 0) { if (e === 0 && c.length === 1) return true; break out; } // Calculate number of digits that c[0] should have, based on the exponent. i = (e + 1) % LOG_BASE; if (i < 1) i += LOG_BASE; // Calculate number of digits of c[0]. //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) { if (String(c[0]).length == i) { for (i = 0; i < c.length; i++) { n = c[i]; if (n < 0 || n >= BASE || n !== mathfloor(n)) break out; } // Last element cannot be zero, unless it is the only element. if (n !== 0) return true; } } // Infinity/NaN } else if (c === null && e === null && (s === null || s === 1 || s === -1)) { return true; } throw Error (bignumberError + 'Invalid BigNumber: ' + v); }; /* * Return a new BigNumber whose value is the maximum of the arguments. * * arguments {number|string|BigNumber} */ BigNumber.maximum = BigNumber.max = function () { return maxOrMin(arguments, -1); }; /* * Return a new BigNumber whose value is the minimum of the arguments. * * arguments {number|string|BigNumber} */ BigNumber.minimum = BigNumber.min = function () { return maxOrMin(arguments, 1); }; /* * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing * zeros are produced). * * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. * * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}' * '[BigNumber Error] crypto unavailable' */ BigNumber.random = (function () { var pow2_53 = 0x20000000000000; // Return a 53 bit integer n, where 0 <= n < 9007199254740992. // Check if Math.random() produces more than 32 bits of randomness. // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. var random53bitInt = (Math.random() * pow2_53) & 0x1fffff ? function () { return mathfloor(Math.random() * pow2_53); } : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + (Math.random() * 0x800000 | 0); }; return function (dp) { var a, b, e, k, v, i = 0, c = [], rand = new BigNumber(ONE); if (dp == null) dp = DECIMAL_PLACES; else intCheck(dp, 0, MAX); k = mathceil(dp / LOG_BASE); if (CRYPTO) { // Browsers supporting crypto.getRandomValues. if (crypto.getRandomValues) { a = crypto.getRandomValues(new Uint32Array(k *= 2)); for (; i < k;) { // 53 bits: // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) // 11111 11111111 11111111 11111111 11100000 00000000 00000000 // ((Math.pow(2, 32) - 1) >>> 11).toString(2) // 11111 11111111 11111111 // 0x20000 is 2^21. v = a[i] * 0x20000 + (a[i + 1] >>> 11); // Rejection sampling: // 0 <= v < 9007199254740992 // Probability that v >= 9e15, is // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 if (v >= 9e15) { b = crypto.getRandomValues(new Uint32Array(2)); a[i] = b[0]; a[i + 1] = b[1]; } else { // 0 <= v <= 8999999999999999 // 0 <= (v % 1e14) <= 99999999999999 c.push(v % 1e14); i += 2; } } i = k / 2; // Node.js supporting crypto.randomBytes. } else if (crypto.randomBytes) { // buffer a = crypto.randomBytes(k *= 7); for (; i < k;) { // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 // 0x100000000 is 2^32, 0x1000000 is 2^24 // 11111 11111111 11111111 11111111 11111111 11111111 11111111 // 0 <= v < 9007199254740992 v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) + (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; if (v >= 9e15) { crypto.randomBytes(7).copy(a, i); } else { // 0 <= (v % 1e14) <= 99999999999999 c.push(v % 1e14); i += 7; } } i = k / 7; } else { CRYPTO = false; throw Error (bignumberError + 'crypto unavailable'); } } // Use Math.random. if (!CRYPTO) { for (; i < k;) { v = random53bitInt(); if (v < 9e15) c[i++] = v % 1e14; } } k = c[--i]; dp %= LOG_BASE; // Convert trailing digits to zeros according to dp. if (k && dp) { v = POWS_TEN[LOG_BASE - dp]; c[i] = mathfloor(k / v) * v; } // Remove trailing elements which are zero. for (; c[i] === 0; c.pop(), i--); // Zero? if (i < 0) { c = [e = 0]; } else { // Remove leading elements which are zero and adjust exponent accordingly. for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); // Count the digits of the first element of c to determine leading zeros, and... for (i = 1, v = c[0]; v >= 10; v /= 10, i++); // adjust the exponent accordingly. if (i < LOG_BASE) e -= LOG_BASE - i; } rand.e = e; rand.c = c; return rand; }; })(); /* * Return a BigNumber whose value is the sum of the arguments. * * arguments {number|string|BigNumber} */ BigNumber.sum = function () { var i = 1, args = arguments, sum = new BigNumber(args[0]); for (; i < args.length;) sum = sum.plus(args[i++]); return sum; }; // PRIVATE FUNCTIONS // Called by BigNumber and BigNumber.prototype.toString. convertBase = (function () { var decimal = '0123456789'; /* * Convert string of baseIn to an array of numbers of baseOut. * Eg. toBaseOut('255', 10, 16) returns [15, 15]. * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5]. */ function toBaseOut(str, baseIn, baseOut, alphabet) { var j, arr = [0], arrL, i = 0, len = str.length; for (; i < len;) { for (arrL = arr.length; arrL--; arr[arrL] *= baseIn); arr[0] += alphabet.indexOf(str.charAt(i++)); for (j = 0; j < arr.length; j++) { if (arr[j] > baseOut - 1) { if (arr[j + 1] == null) arr[j + 1] = 0; arr[j + 1] += arr[j] / baseOut | 0; arr[j] %= baseOut; } } } return arr.reverse(); } // Convert a numeric string of baseIn to a numeric string of baseOut. // If the caller is toString, we are converting from base 10 to baseOut. // If the caller is BigNumber, we are converting from baseIn to base 10. return function (str, baseIn, baseOut, sign, callerIsToString) { var alphabet, d, e, k, r, x, xc, y, i = str.indexOf('.'), dp = DECIMAL_PLACES, rm = ROUNDING_MODE; // Non-integer. if (i >= 0) { k = POW_PRECISION; // Unlimited precision. POW_PRECISION = 0; str = str.replace('.', ''); y = new BigNumber(baseIn); x = y.pow(str.length - i); POW_PRECISION = k; // Convert str as if an integer, then restore the fraction part by dividing the // result by its base raised to a power. y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'), 10, baseOut, decimal); y.e = y.c.length; } // Convert the number as integer. xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet = ALPHABET, decimal) : (alphabet = decimal, ALPHABET)); // xc now represents str as an integer and converted to baseOut. e is the exponent. e = k = xc.length; // Remove trailing zeros. for (; xc[--k] == 0; xc.pop()); // Zero? if (!xc[0]) return alphabet.charAt(0); // Does str represent an integer? If so, no need for the division. if (i < 0) { --e; } else { x.c = xc; x.e = e; // The sign is needed for correct rounding. x.s = sign; x = div(x, y, dp, rm, baseOut); xc = x.c; r = x.r; e = x.e; } // xc now represents str converted to baseOut. // The index of the rounding digit. d = e + dp + 1; // The rounding digit: the digit to the right of the digit that may be rounded up. i = xc[d]; // Look at the rounding digits and mode to determine whether to round up. k = baseOut / 2; r = r || d < 0 || xc[d + 1] != null; r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 || rm == (x.s < 0 ? 8 : 7)); // If the index of the rounding digit is not greater than zero, or xc represents // zero, then the result of the base conversion is zero or, if rounding up, a value // such as 0.00001. if (d < 1 || !xc[0]) { // 1^-dp or 0 str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); } else { // Truncate xc to the required number of decimal places. xc.length = d; // Round up? if (r) { // Rounding up may mean the previous digit has to be rounded up and so on. for (--baseOut; ++xc[--d] > baseOut;) { xc[d] = 0; if (!d) { ++e; xc = [1].concat(xc); } } } // Determine trailing zeros. for (k = xc.length; !xc[--k];); // E.g. [4, 11, 15] becomes 4bf. for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++])); // Add leading zeros, decimal point and trailing zeros as required. str = toFixedPoint(str, e, alphabet.charAt(0)); } // The caller will add the sign. return str; }; })(); // Perform division in the specified base. Called by div and convertBase. div = (function () { // Assume non-zero x and k. function multiply(x, k, base) { var m, temp, xlo, xhi, carry = 0, i = x.length, klo = k % SQRT_BASE, khi = k / SQRT_BASE | 0; for (x = x.slice(); i--;) { xlo = x[i] % SQRT_BASE; xhi = x[i] / SQRT_BASE | 0; m = khi * xlo + xhi * klo; temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry; carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; x[i] = temp % base; } if (carry) x = [carry].concat(x); return x; } function compare(a, b, aL, bL) { var i, cmp; if (aL != bL) { cmp = aL > bL ? 1 : -1; } else { for (i = cmp = 0; i < aL; i++) { if (a[i] != b[i]) { cmp = a[i] > b[i] ? 1 : -1; break; } } } return cmp; } function subtract(a, b, aL, base) { var i = 0; // Subtract b from a. for (; aL--;) { a[aL] -= i; i = a[aL] < b[aL] ? 1 : 0; a[aL] = i * base + a[aL] - b[aL]; } // Remove leading zeros. for (; !a[0] && a.length > 1; a.splice(0, 1)); } // x: dividend, y: divisor. return function (x, y, dp, rm, base) { var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s = x.s == y.s ? 1 : -1, xc = x.c, yc = y.c; // Either NaN, Infinity or 0? if (!xc || !xc[0] || !yc || !yc[0]) { return new BigNumber( // Return NaN if either NaN, or both Infinity or 0. !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. xc && xc[0] == 0 || !yc ? s * 0 : s / 0 ); } q = new BigNumber(s); qc = q.c = []; e = x.e - y.e; s = dp + e + 1; if (!base) { base = BASE; e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); s = s / LOG_BASE | 0; } // Result exponent may be one less then the current value of e. // The coefficients of the BigNumbers from convertBase may have trailing zeros. for (i = 0; yc[i] == (xc[i] || 0); i++); if (yc[i] > (xc[i] || 0)) e--; if (s < 0) { qc.push(1); more = true; } else { xL = xc.length; yL = yc.length; i = 0; s += 2; // Normalise xc and yc so highest order digit of yc is >= base / 2. n = mathfloor(base / (yc[0] + 1)); // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1. // if (n > 1 || n++ == 1 && yc[0] < base / 2) { if (n > 1) { yc = multiply(yc, n, base); xc = multiply(xc, n, base); yL = yc.length; xL = xc.length; } xi = yL; rem = xc.slice(0, yL); remL = rem.length; // Add zeros to make remainder as long as divisor. for (; remL < yL; rem[remL++] = 0); yz = yc.slice(); yz = [0].concat(yz); yc0 = yc[0]; if (yc[1] >= base / 2) yc0++; // Not necessary, but to prevent trial digit n > base, when using base 3. // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15; do { n = 0; // Compare divisor and remainder. cmp = compare(yc, rem, yL, remL); // If divisor < remainder. if (cmp < 0) { // Calculate trial digit, n. rem0 = rem[0]; if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); // n is how many times the divisor goes into the current remainder. n = mathfloor(rem0 / yc0); // Algorithm: // product = divisor multiplied by trial digit (n). // Compare product and remainder. // If product is greater than remainder: // Subtract divisor from product, decrement trial digit. // Subtract product from remainder. // If product was less than remainder at the last compare: // Compare new remainder and divisor. // If remainder is greater than divisor: // Subtract divisor from remainder, increment trial digit. if (n > 1) { // n may be > base only when base is 3. if (n >= base) n = base - 1; // product = divisor * trial digit. prod = multiply(yc, n, base); prodL = prod.length; remL = rem.length; // Compare product and remainder. // If product > remainder then trial digit n too high. // n is 1 too high about 5% of the time, and is not known to have // ever been more than 1 too high. while (compare(prod, rem, prodL, remL) == 1) { n--; // Subtract divisor from product. subtract(prod, yL < prodL ? yz : yc, prodL, base); prodL = prod.length; cmp = 1; } } else { // n is 0 or 1, cmp is -1. // If n is 0, there is no need to compare yc and rem again below, // so change cmp to 1 to avoid it. // If n is 1, leave cmp as -1, so yc and rem are compared again. if (n == 0) { // divisor < remainder, so n must be at least 1. cmp = n = 1; } // product = divisor prod = yc.slice(); prodL = prod.length; } if (prodL < remL) prod = [0].concat(prod); // Subtract product from remainder. subtract(rem, prod, remL, base); remL = rem.length; // If product was < remainder. if (cmp == -1) { // Compare divisor and new remainder. // If divisor < new remainder, subtract divisor from remainder. // Trial digit n too low. // n is 1 too low about 5% of the time, and very rarely 2 too low. while (compare(yc, rem, yL, remL) < 1) { n++; // Subtract divisor from remainder. subtract(rem, yL < remL ? yz : yc, remL, base); remL = rem.length; } } } else if (cmp === 0) { n++; rem = [0]; } // else cmp === 1 and n will be 0 // Add the next digit, n, to the result array. qc[i++] = n; // Update the remainder. if (rem[0]) { rem[remL++] = xc[xi] || 0; } else { rem = [xc[xi]]; remL = 1; } } while ((xi++ < xL || rem[0] != null) && s--); more = rem[0] != null; // Leading zero? if (!qc[0]) qc.splice(0, 1); } if (base == BASE) { // To calculate q.e, first get the number of digits of qc[0]. for (i = 1, s = qc[0]; s >= 10; s /= 10, i++); round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more); // Caller is convertBase. } else { q.e = e; q.r = +more; } return q; }; })(); /* * Return a string representing the value of BigNumber n in fixed-point or exponential * notation rounded to the specified decimal places or significant digits. * * n: a BigNumber. * i: the index of the last digit required (i.e. the digit that may be rounded up). * rm: the rounding mode. * id: 1 (toExponential) or 2 (toPrecision). */ function format(n, i, rm, id) { var c0, e, ne, len, str; if (rm == null) rm = ROUNDING_MODE; else intCheck(rm, 0, 8); if (!n.c) return n.toString(); c0 = n.c[0]; ne = n.e; if (i == null) { str = coeffToString(n.c); str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) ? toExponential(str, ne) : toFixedPoint(str, ne, '0'); } else { n = round(new BigNumber(n), i, rm); // n.e may have changed if the value was rounded up. e = n.e; str = coeffToString(n.c); len = str.length; // toPrecision returns exponential notation if the number of significant digits // specified is less than the number of digits necessary to represent the integer // part of the value in fixed-point notation. // Exponential notation. if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) { // Append zeros? for (; len < i; str += '0', len++); str = toExponential(str, e); // Fixed-point notation. } else { i -= ne; str = toFixedPoint(str, e, '0'); // Append zeros? if (e + 1 > len) { if (--i > 0) for (str += '.'; i--; str += '0'); } else { i += e - len; if (i > 0) { if (e + 1 == len) str += '.'; for (; i--; str += '0'); } } } } return n.s < 0 && c0 ? '-' + str : str; } // Handle BigNumber.max and BigNumber.min. // If any number is NaN, return NaN. function maxOrMin(args, n) { var k, y, i = 1, x = new BigNumber(args[0]); for (; i < args.length; i++) { y = new BigNumber(args[i]); if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) { x = y; } } return x; } /* * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. * Called by minus, plus and times. */ function normalise(n, c, e) { var i = 1, j = c.length; // Remove trailing zeros. for (; !c[--j]; c.pop()); // Calculate the base 10 exponent. First get the number of digits of c[0]. for (j = c[0]; j >= 10; j /= 10, i++); // Overflow? if ((e = i + e * LOG_BASE - 1) > MAX_EXP) { // Infinity. n.c = n.e = null; // Underflow? } else if (e < MIN_EXP) { // Zero. n.c = [n.e = 0]; } else { n.e = e; n.c = c; } return n; } // Handle values that fail the validity test in BigNumber. parseNumeric = (function () { var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; return function (x, str, isNum, b) { var base, s = isNum ? str : str.replace(whitespaceOrPlus, ''); // No exception on ±Infinity or NaN. if (isInfinityOrNaN.test(s)) { x.s = isNaN(s) ? null : s < 0 ? -1 : 1; } else { if (!isNum) { // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i s = s.replace(basePrefix, function (m, p1, p2) { base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8; return !b || b == base ? p1 : m; }); if (b) { base = b; // E.g. '1.' to '1', '.1' to '0.1' s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1'); } if (str != s) return new BigNumber(s, base); } // '[BigNumber Error] Not a number: {n}' // '[BigNumber Error] Not a base {b} number: {n}' if (BigNumber.DEBUG) { throw Error (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str); } // NaN x.s = null; } x.c = x.e = null; } })(); /* * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. * If r is truthy, it is known that there are more digits after the rounding digit. */ function round(x, sd, rm, r) { var d, i, j, k, n, ni, rd, xc = x.c, pows10 = POWS_TEN; // if x is not Infinity or NaN... if (xc) { // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. // n is a base 1e14 number, the value of the element of array x.c containing rd. // ni is the index of n within x.c. // d is the number of digits of n. // i is the index of rd within n including leading zeros. // j is the actual index of rd within n (if < 0, rd is a leading zero). out: { // Get the number of digits of the first element of xc. for (d = 1, k = xc[0]; k >= 10; k /= 10, d++); i = sd - d; // If the rounding digit is in the first element of xc... if (i < 0) { i += LOG_BASE; j = sd; n = xc[ni = 0]; // Get the rounding digit at index j of n. rd = mathfloor(n / pows10[d - j - 1] % 10); } else { ni = mathceil((i + 1) / LOG_BASE); if (ni >= xc.length) { if (r) { // Needed by sqrt. for (; xc.length <= ni; xc.push(0)); n = rd = 0; d = 1; i %= LOG_BASE; j = i - LOG_BASE + 1; } else { break out; } } else { n = k = xc[ni]; // Get the number of digits of n. for (d = 1; k >= 10; k /= 10, d++); // Get the index of rd within n. i %= LOG_BASE; // Get the index of rd within n, adjusted for leading zeros. // The number of leading zeros of n is given by LOG_BASE - d. j = i - LOG_BASE + d; // Get the rounding digit at index j of n. rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10); } } r = r || sd < 0 || // Are there any non-zero digits after the rounding digit? // The expression n % pows10[d - j - 1] returns all digits of n to the right // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); r = rm < 4 ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && // Check whether the digit to the left of the rounding digit is odd. ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 || rm == (x.s < 0 ? 8 : 7)); if (sd < 1 || !xc[0]) { xc.length = 0; if (r) { // Convert sd to decimal places. sd -= x.e + 1; // 1, 0.1, 0.01, 0.001, 0.0001 etc. xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; x.e = -sd || 0; } else { // Zero. xc[0] = x.e = 0; } return x; } // Remove excess digits. if (i == 0) { xc.length = ni; k = 1; ni--; } else { xc.length = ni + 1; k = pows10[LOG_BASE - i]; // E.g. 56700 becomes 56000 if 7 is the rounding digit. // j > 0 means i > number of leading zeros of n. xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; } // Round up? if (r) { for (; ;) { // If the digit to be rounded up is in the first element of xc... if (ni == 0) { // i will be the length of xc[0] before k is added. for (i = 1, j = xc[0]; j >= 10; j /= 10, i++); j = xc[0] += k; for (k = 1; j >= 10; j /= 10, k++); // if i != k the length has increased. if (i != k) { x.e++; if (xc[0] == BASE) xc[0] = 1; } break; } else { xc[ni] += k; if (xc[ni] != BASE) break; xc[ni--] = 0; k = 1; } } } // Remove trailing zeros. for (i = xc.length; xc[--i] === 0; xc.pop()); } // Overflow? Infinity. if (x.e > MAX_EXP) { x.c = x.e = null; // Underflow? Zero. } else if (x.e < MIN_EXP) { x.c = [x.e = 0]; } } return x; } function valueOf(n) { var str, e = n.e; if (e === null) return n.toString(); str = coeffToString(n.c); str = e <= TO_EXP_NEG || e >= TO_EXP_POS ? toExponential(str, e) : toFixedPoint(str, e, '0'); return n.s < 0 ? '-' + str : str; } // PROTOTYPE/INSTANCE METHODS /* * Return a new BigNumber whose value is the absolute value of this BigNumber. */ P.absoluteValue = P.abs = function () { var x = new BigNumber(this); if (x.s < 0) x.s = 1; return x; }; /* * Return * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), * 0 if they have the same value, * or null if the value of either is NaN. */ P.comparedTo = function (y, b) { return compare(this, new BigNumber(y, b)); }; /* * If dp is undefined or null or true or false, return the number of decimal places of the * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. * * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or * ROUNDING_MODE if rm is omitted. * * [dp] {number} Decimal places: integer, 0 to MAX inclusive. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. * * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' */ P.decimalPlaces = P.dp = function (dp, rm) { var c, n, v, x = this; if (dp != null) { intCheck(dp, 0, MAX); if (rm == null) rm = ROUNDING_MODE; else intCheck(rm, 0, 8); return round(new BigNumber(x), dp + x.e + 1, rm); } if (!(c = x.c)) return null; n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; // Subtract the number of trailing zeros of the last number. if (v = c[v]) for (; v % 10 == 0; v /= 10, n--); if (n < 0) n = 0; return n; }; /* * n / 0 = I * n / N = N * n / I = 0 * 0 / n = 0 * 0 / 0 = N * 0 / N = N * 0 / I = 0 * N / n = N * N / 0 = N * N / N = N * N / I = N * I / n = I * I / 0 = I * I / N = N * I / I = N * * Return a new BigNumber whose value is the value of this BigNumber divided by the value of * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. */ P.dividedBy = P.div = function (y, b) { return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); }; /* * Return a new BigNumber whose value is the integer part of dividing the value of this * BigNumber by the value of BigNumber(y, b). */ P.dividedToIntegerBy = P.idiv = function (y, b) { return div(this, new BigNumber(y, b), 0, 1); }; /* * Return a BigNumber whose value is the value of this BigNumber exponentiated by n. * * If m is present, return the result modulo m. * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE. * * The modular power operation works efficiently when x, n, and m are integers, otherwise it * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0. * * n {number|string|BigNumber} The exponent. An integer. * [m] {number|string|BigNumber} The modulus. * * '[BigNumber Error] Exponent not an integer: {n}' */ P.exponentiatedBy = P.pow = function (n, m) { var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, x = this; n = new BigNumber(n); // Allow NaN and ±Infinity, but not other non-integers. if (n.c && !n.isInteger()) { throw Error (bignumberError + 'Exponent not an integer: ' + valueOf(n)); } if (m != null) m = new BigNumber(m); // Exponent of MAX_SAFE_INTEGER is 15. nIsBig = n.e > 14; // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0. if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { // The sign of the result of pow when x is negative depends on the evenness of n. // If +n overflows to ±Infinity, the evenness of n would be not be known. y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n))); return m ? y.mod(m) : y; } nIsNeg = n.s < 0; if (m) { // x % m returns NaN if abs(m) is zero, or m is NaN. if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN); isModExp = !nIsNeg && x.isInteger() && m.isInteger(); if (isModExp) x = x.mod(m); // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15. // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15. } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 // [1, 240000000] ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 // [80000000000000] [99999750000000] : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) { // If x is negative and n is odd, k = -0, else k = 0. k = x.s < 0 && isOdd(n) ? -0 : 0; // If x >= 1, k = ±Infinity. if (x.e > -1) k = 1 / k; // If n is negative return ±0, else return ±Infinity. return new BigNumber(nIsNeg ? 1 / k : k); } else if (POW_PRECISION) { // Truncating each coefficient array to a length of k after each multiplication // equates to truncating significant digits to POW_PRECISION + [28, 41], // i.e. there will be a minimum of 28 guard digits retained. k = mathceil(POW_PRECISION / LOG_BASE + 2); } if (nIsBig) { half = new BigNumber(0.5); if (nIsNeg) n.s = 1; nIsOdd = isOdd(n); } else { i = Math.abs(+valueOf(n)); nIsOdd = i % 2; } y = new BigNumber(ONE); // Performs 54 loop iterations for n of 9007199254740991. for (; ;) { if (nIsOdd) { y = y.times(x); if (!y.c) break; if (k) { if (y.c.length > k) y.c.length = k; } else if (isModExp) { y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m)); } } if (i) { i = mathfloor(i / 2); if (i === 0) break; nIsOdd = i % 2; } else { n = n.times(half); round(n, n.e + 1, 1); if (n.e > 14) { nIsOdd = isOdd(n); } else { i = +valueOf(n); if (i === 0) break; nIsOdd = i % 2; } } x = x.times(x); if (k) { if (x.c && x.c.length > k) x.c.length = k; } else if (isModExp) { x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m)); } } if (isModExp) return y; if (nIsNeg) y = ONE.div(y); return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; }; /* * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer * using rounding mode rm, or ROUNDING_MODE if rm is omitted. * * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. * * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}' */ P.integerValue = function (rm) { var n = new BigNumber(this); if (rm == null) rm = ROUNDING_MODE; else intCheck(rm, 0, 8); return round(n, n.e + 1, rm); }; /* * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), * otherwise return false. */ P.isEqualTo = P.eq = function (y, b) { return compare(this, new BigNumber(y, b)) === 0; }; /* * Return true if the value of this BigNumber is a finite number, otherwise return false. */ P.isFinite = function () { return !!this.c; }; /* * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), * otherwise return false. */ P.isGreaterThan = P.gt = function (y, b) { return compare(this, new BigNumber(y, b)) > 0; }; /* * Return true if the value of this BigNumber is greater than or equal to the value of * BigNumber(y, b), otherwise return false. */ P.isGreaterThanOrEqualTo = P.gte = function (y, b) { return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; }; /* * Return true if the value of this BigNumber is an integer, otherwise return false. */ P.isInteger = function () { return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; }; /* * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), * otherwise return false. */ P.isLessThan = P.lt = function (y, b) { return compare(this, new BigNumber(y, b)) < 0; }; /* * Return true if the value of this BigNumber is less than or equal to the value of * BigNumber(y, b), otherwise return false. */ P.isLessThanOrEqualTo = P.lte = function (y, b) { return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; }; /* * Return true if the value of this BigNumber is NaN, otherwise return false. */ P.isNaN = function () { return !this.s; }; /* * Return true if the value of this BigNumber is negative, otherwise return false. */ P.isNegative = function () { return this.s < 0; }; /* * Return true if the value of this BigNumber is positive, otherwise return false. */ P.isPositive = function () { return this.s > 0; }; /* * Return true if the value of this BigNumber is 0 or -0, otherwise return false. */ P.isZero = function () { return !!this.c && this.c[0] == 0; }; /* * n - 0 = n * n - N = N * n - I = -I * 0 - n = -n * 0 - 0 = 0 * 0 - N = N * 0 - I = -I * N - n = N * N - 0 = N * N - N = N * N - I = N * I - n = I * I - 0 = I * I - N = N * I - I = N * * Return a new BigNumber whose value is the value of this BigNumber minus the value of * BigNumber(y, b). */ P.minus = function (y, b) { var i, j, t, xLTy, x = this, a = x.s; y = new BigNumber(y, b); b = y.s; // Either NaN? if (!a || !b) return new BigNumber(NaN); // Signs differ? if (a != b) { y.s = -b; return x.plus(y); } var xe = x.e / LOG_BASE, ye = y.e / LOG_BASE, xc = x.c, yc = y.c; if (!xe || !ye) { // Either Infinity? if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); // Either zero? if (!xc[0] || !yc[0]) { // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity ROUNDING_MODE == 3 ? -0 : 0); } } xe = bitFloor(xe); ye = bitFloor(ye); xc = xc.slice(); // Determine which is the bigger number. if (a = xe - ye) { if (xLTy = a < 0) { a = -a; t = xc; } else { ye = xe; t = yc; } t.reverse(); // Prepend zeros to equalise exponents. for (b = a; b--; t.push(0)); t.reverse(); } else { // Exponents equal. Check digit by digit. j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; for (a = b = 0; b < j; b++) { if (xc[b] != yc[b]) { xLTy = xc[b] < yc[b]; break; } } } // x < y? Point xc to the array of the bigger number. if (xLTy) { t = xc; xc = yc; yc = t; y.s = -y.s; } b = (j = yc.length) - (i = xc.length); // Append zeros to xc if shorter. // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. if (b > 0) for (; b--; xc[i++] = 0); b = BASE - 1; // Subtract yc from xc. for (; j > a;) { if (xc[--j] < yc[j]) { for (i = j; i && !xc[--i]; xc[i] = b); --xc[i]; xc[j] += BASE; } xc[j] -= yc[j]; } // Remove leading zeros and adjust exponent accordingly. for (; xc[0] == 0; xc.splice(0, 1), --ye); // Zero? if (!xc[0]) { // Following IEEE 754 (2008) 6.3, // n - n = +0 but n - n = -0 when rounding towards -Infinity. y.s = ROUNDING_MODE == 3 ? -1 : 1; y.c = [y.e = 0]; return y; } // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity // for finite x and y. return normalise(y, xc, ye); }; /* * n % 0 = N * n % N = N * n % I = n * 0 % n = 0 * -0 % n = -0 * 0 % 0 = N * 0 % N = N * 0 % I = 0 * N % n = N * N % 0 = N * N % N = N * N % I = N * I % n = N * I % 0 = N * I % N = N * I % I = N * * Return a new BigNumber whose value is the value of this BigNumber modulo the value of * BigNumber(y, b). The result depends on the value of MODULO_MODE. */ P.modulo = P.mod = function (y, b) { var q, s, x = this; y = new BigNumber(y, b); // Return NaN if x is Infinity or NaN, or y is NaN or zero. if (!x.c || !y.s || y.c && !y.c[0]) { return new BigNumber(NaN); // Return x if y is Infinity or x is zero. } else if (!y.c || x.c && !x.c[0]) { return new BigNumber(x); } if (MODULO_MODE == 9) { // Euclidian division: q = sign(y) * floor(x / abs(y)) // r = x - qy where 0 <= r < abs(y) s = y.s; y.s = 1; q = div(x, y, 0, 3); y.s = s; q.s *= s; } else { q = div(x, y, 0, MODULO_MODE); } y = x.minus(q.times(y)); // To match JavaScript %, ensure sign of zero is sign of dividend. if (!y.c[0] && MODULO_MODE == 1) y.s = x.s; return y; }; /* * n * 0 = 0 * n * N = N * n * I = I * 0 * n = 0 * 0 * 0 = 0 * 0 * N = N * 0 * I = N * N * n = N * N * 0 = N * N * N = N * N * I = N * I * n = I * I * 0 = N * I * N = N * I * I = I * * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value * of BigNumber(y, b). */ P.multipliedBy = P.times = function (y, b) { var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, base, sqrtBase, x = this, xc = x.c, yc = (y = new BigNumber(y, b)).c; // Either NaN, ±Infinity or ±0? if (!xc || !yc || !xc[0] || !yc[0]) { // Return NaN if either is NaN, or one is 0 and the other is Infinity. if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { y.c = y.e = y.s = null; } else { y.s *= x.s; // Return ±Infinity if either is ±Infinity. if (!xc || !yc) { y.c = y.e = null; // Return ±0 if either is ±0. } else { y.c = [0]; y.e = 0; } } return y; } e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); y.s *= x.s; xcL = xc.length; ycL = yc.length; // Ensure xc points to longer array and xcL to its length. if (xcL < ycL) { zc = xc; xc = yc; yc = zc; i = xcL; xcL = ycL; ycL = i; } // Initialise the result array with zeros. for (i = xcL + ycL, zc = []; i--; zc.push(0)); base = BASE; sqrtBase = SQRT_BASE; for (i = ycL; --i >= 0;) { c = 0; ylo = yc[i] % sqrtBase; yhi = yc[i] / sqrtBase | 0; for (k = xcL, j = i + k; j > i;) { xlo = xc[--k] % sqrtBase; xhi = xc[k] / sqrtBase | 0; m = yhi * xlo + xhi * ylo; xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c; c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; zc[j--] = xlo % base; } zc[j] = c; } if (c) { ++e; } else { zc.splice(0, 1); } return normalise(y, zc, e); }; /* * Return a new BigNumber whose value is the value of this BigNumber negated, * i.e. multiplied by -1. */ P.negated = function () { var x = new BigNumber(this); x.s = -x.s || null; return x; }; /* * n + 0 = n * n + N = N * n + I = I * 0 + n = n * 0 + 0 = 0 * 0 + N = N * 0 + I = I * N + n = N * N + 0 = N * N + N = N * N + I = N * I + n = I * I + 0 = I * I + N = N * I + I = I * * Return a new BigNumber whose value is the value of this BigNumber plus the value of * BigNumber(y, b). */ P.plus = function (y, b) { var t, x = this, a = x.s; y = new BigNumber(y, b); b = y.s; // Either NaN? if (!a || !b) return new BigNumber(NaN); // Signs differ? if (a != b) { y.s = -b; return x.minus(y); } var xe = x.e / LOG_BASE, ye = y.e / LOG_BASE, xc = x.c, yc = y.c; if (!xe || !ye) { // Return ±Infinity if either ±Infinity. if (!xc || !yc) return new BigNumber(a / 0); // Either zero? // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); } xe = bitFloor(xe); ye = bitFloor(ye); xc = xc.slice(); // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. if (a = xe - ye) { if (a > 0) { ye = xe; t = yc; } else { a = -a; t = xc; } t.reverse(); for (; a--; t.push(0)); t.reverse(); } a = xc.length; b = yc.length; // Point xc to the longer array, and b to the shorter length. if (a - b < 0) { t = yc; yc = xc; xc = t; b = a; } // Only start adding at yc.length - 1 as the further digits of xc can be ignored. for (a = 0; b;) { a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; } if (a) { xc = [a].concat(xc); ++ye; } // No need to check for zero, as +x + +y != 0 && -x + -y != 0 // ye = MAX_EXP + 1 possible return normalise(y, xc, ye); }; /* * If sd is undefined or null or true or false, return the number of significant digits of * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. * If sd is true include integer-part trailing zeros in the count. * * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or * ROUNDING_MODE if rm is omitted. * * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive. * boolean: whether to count integer-part trailing zeros: true or false. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. * * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' */ P.precision = P.sd = function (sd, rm) { var c, n, v, x = this; if (sd != null && sd !== !!sd) { intCheck(sd, 1, MAX); if (rm == null) rm = ROUNDING_MODE; else intCheck(rm, 0, 8); return round(new BigNumber(x), sd, rm); } if (!(c = x.c)) return null; v = c.length - 1; n = v * LOG_BASE + 1; if (v = c[v]) { // Subtract the number of trailing zeros of the last element. for (; v % 10 == 0; v /= 10, n--); // Add the number of digits of the first element. for (v = c[0]; v >= 10; v /= 10, n++); } if (sd && x.e + 1 > n) n = x.e + 1; return n; }; /* * Return a new BigNumber whose value is the value of this BigNumber shifted by k places * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. * * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. * * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}' */ P.shiftedBy = function (k) { intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); return this.times('1e' + k); }; /* * sqrt(-n) = N * sqrt(N) = N * sqrt(-I) = N * sqrt(I) = I * sqrt(0) = 0 * sqrt(-0) = -0 * * Return a new BigNumber whose value is the square root of the value of this BigNumber, * rounded according to DECIMAL_PLACES and ROUNDING_MODE. */ P.squareRoot = P.sqrt = function () { var m, n, r, rep, t, x = this, c = x.c, s = x.s, e = x.e, dp = DECIMAL_PLACES + 4, half = new BigNumber('0.5'); // Negative/NaN/Infinity/zero? if (s !== 1 || !c || !c[0]) { return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); } // Initial estimate. s = Math.sqrt(+valueOf(x)); // Math.sqrt underflow/overflow? // Pass x to Math.sqrt as integer, then adjust the exponent of the result. if (s == 0 || s == 1 / 0) { n = coeffToString(c); if ((n.length + e) % 2 == 0) n += '0'; s = Math.sqrt(+n); e = bitFloor((e + 1) / 2) - (e < 0 || e % 2); if (s == 1 / 0) { n = '5e' + e; } else { n = s.toExponential(); n = n.slice(0, n.indexOf('e') + 1) + e; } r = new BigNumber(n); } else { r = new BigNumber(s + ''); } // Check for zero. // r could be zero if MIN_EXP is changed after the this value was created. // This would cause a division by zero (x/t) and hence Infinity below, which would cause // coeffToString to throw. if (r.c[0]) { e = r.e; s = e + dp; if (s < 3) s = 0; // Newton-Raphson iteration. for (; ;) { t = r; r = half.times(t.plus(div(x, t, dp, 1))); if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) { // The exponent of r may here be one less than the final result exponent, // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits // are indexed correctly. if (r.e < e) --s; n = n.slice(s - 3, s + 1); // The 4th rounding digit may be in error by -1 so if the 4 rounding digits // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the // iteration. if (n == '9999' || !rep && n == '4999') { // On the first iteration only, check to see if rounding up gives the // exact result as the nines may infinitely repeat. if (!rep) { round(t, t.e + DECIMAL_PLACES + 2, 0); if (t.times(t).eq(x)) { r = t; break; } } dp += 4; s += 4; rep = 1; } else { // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact // result. If not, then there are further digits and m will be truthy. if (!+n || !+n.slice(1) && n.charAt(0) == '5') { // Truncate to the first rounding digit. round(r, r.e + DECIMAL_PLACES + 2, 1); m = !r.times(r).eq(x); } break; } } } } return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); }; /* * Return a string representing the value of this BigNumber in exponential notation and * rounded using ROUNDING_MODE to dp fixed decimal places. * * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. * * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' */ P.toExponential = function (dp, rm) { if (dp != null) { intCheck(dp, 0, MAX); dp++; } return format(this, dp, rm, 1); }; /* * Return a string representing the value of this BigNumber in fixed-point notation rounding * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. * * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', * but e.g. (-0.00001).toFixed(0) is '-0'. * * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. * * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' */ P.toFixed = function (dp, rm) { if (dp != null) { intCheck(dp, 0, MAX); dp = dp + this.e + 1; } return format(this, dp, rm); }; /* * Return a string representing the value of this BigNumber in fixed-point notation rounded * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties * of the format or FORMAT object (see BigNumber.set). * * The formatting object may contain some or all of the properties shown below. * * FORMAT = { * prefix: '', * groupSize: 3, * secondaryGroupSize: 0, * groupSeparator: ',', * decimalSeparator: '.', * fractionGroupSize: 0, * fractionGroupSeparator: '\xA0', // non-breaking space * suffix: '' * }; * * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. * [format] {object} Formatting options. See FORMAT pbject above. * * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' * '[BigNumber Error] Argument not an object: {format}' */ P.toFormat = function (dp, rm, format) { var str, x = this; if (format == null) { if (dp != null && rm && typeof rm == 'object') { format = rm; rm = null; } else if (dp && typeof dp == 'object') { format = dp; dp = rm = null; } else { format = FORMAT; } } else if (typeof format != 'object') { throw Error (bignumberError + 'Argument not an object: ' + format); } str = x.toFixed(dp, rm); if (x.c) { var i, arr = str.split('.'), g1 = +format.groupSize, g2 = +format.secondaryGroupSize, groupSeparator = format.groupSeparator || '', intPart = arr[0], fractionPart = arr[1], isNeg = x.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length; if (g2) { i = g1; g1 = g2; g2 = i; len -= i; } if (g1 > 0 && len > 0) { i = len % g1 || g1; intPart = intDigits.substr(0, i); for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1); if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); if (isNeg) intPart = '-' + intPart; } str = fractionPart ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize) ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), '$&' + (format.fractionGroupSeparator || '')) : fractionPart) : intPart; } return (format.prefix || '') + str + (format.suffix || ''); }; /* * Return an array of two BigNumbers representing the value of this BigNumber as a simple * fraction with an integer numerator and an integer denominator. * The denominator will be a positive non-zero value less than or equal to the specified * maximum denominator. If a maximum denominator is not specified, the denominator will be * the lowest value necessary to represent the number exactly. * * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator. * * '[BigNumber Error] Argument {not an integer|out of range} : {md}' */ P.toFraction = function (md) { var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, x = this, xc = x.c; if (md != null) { n = new BigNumber(md); // Throw if md is less than one or is not an integer, unless it is Infinity. if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { throw Error (bignumberError + 'Argument ' + (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n)); } } if (!xc) return new BigNumber(x); d = new BigNumber(ONE); n1 = d0 = new BigNumber(ONE); d1 = n0 = new BigNumber(ONE); s = coeffToString(xc); // Determine initial denominator. // d is a power of 10 and the minimum max denominator that specifies the value exactly. e = d.e = s.length - x.e - 1; d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n; exp = MAX_EXP; MAX_EXP = 1 / 0; n = new BigNumber(s); // n0 = d1 = 0 n0.c[0] = 0; for (; ;) { q = div(n, d, 0, 1); d2 = d0.plus(q.times(d1)); if (d2.comparedTo(md) == 1) break; d0 = d1; d1 = d2; n1 = n0.plus(q.times(d2 = n1)); n0 = d2; d = n.minus(q.times(d2 = d)); n = d2; } d2 = div(md.minus(d0), d1, 0, 1); n0 = n0.plus(d2.times(n1)); d0 = d0.plus(d2.times(d1)); n0.s = n1.s = x.s; e = e * 2; // Determine which fraction is closer to x, n0/d0 or n1/d1 r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo( div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; MAX_EXP = exp; return r; }; /* * Return the value of this BigNumber converted to a number primitive. */ P.toNumber = function () { return +valueOf(this); }; /* * Return a string representing the value of this BigNumber rounded to sd significant digits * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits * necessary to represent the integer part of the value in fixed-point notation, then use * exponential notation. * * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. * * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' */ P.toPrecision = function (sd, rm) { if (sd != null) intCheck(sd, 1, MAX); return format(this, sd, rm, 2); }; /* * Return a string representing the value of this BigNumber in base b, or base 10 if b is * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than * TO_EXP_NEG, return exponential notation. * * [b] {number} Integer, 2 to ALPHABET.length inclusive. * * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' */ P.toString = function (b) { var str, n = this, s = n.s, e = n.e; // Infinity or NaN? if (e === null) { if (s) { str = 'Infinity'; if (s < 0) str = '-' + str; } else { str = 'NaN'; } } else { if (b == null) { str = e <= TO_EXP_NEG || e >= TO_EXP_POS ? toExponential(coeffToString(n.c), e) : toFixedPoint(coeffToString(n.c), e, '0'); } else if (b === 10 && alphabetHasNormalDecimalDigits) { n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE); str = toFixedPoint(coeffToString(n.c), n.e, '0'); } else { intCheck(b, 2, ALPHABET.length, 'Base'); str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true); } if (s < 0 && n.c[0]) str = '-' + str; } return str; }; /* * Return as toString, but do not accept a base argument, and include the minus sign for * negative zero. */ P.valueOf = P.toJSON = function () { return valueOf(this); }; P._isBigNumber = true; if (configObject != null) BigNumber.set(configObject); return BigNumber; } // PRIVATE HELPER FUNCTIONS // These functions don't need access to variables, // e.g. DECIMAL_PLACES, in the scope of the `clone` function above. function bitFloor(n) { var i = n | 0; return n > 0 || n === i ? i : i - 1; } // Return a coefficient array as a string of base 10 digits. function coeffToString(a) { var s, z, i = 1, j = a.length, r = a[0] + ''; for (; i < j;) { s = a[i++] + ''; z = LOG_BASE - s.length; for (; z--; s = '0' + s); r += s; } // Determine trailing zeros. for (j = r.length; r.charCodeAt(--j) === 48;); return r.slice(0, j + 1 || 1); } // Compare the value of BigNumbers x and y. function compare(x, y) { var a, b, xc = x.c, yc = y.c, i = x.s, j = y.s, k = x.e, l = y.e; // Either NaN? if (!i || !j) return null; a = xc && !xc[0]; b = yc && !yc[0]; // Either zero? if (a || b) return a ? b ? 0 : -j : i; // Signs differ? if (i != j) return i; a = i < 0; b = k == l; // Either Infinity? if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; // Compare exponents. if (!b) return k > l ^ a ? 1 : -1; j = (k = xc.length) < (l = yc.length) ? k : l; // Compare digit by digit. for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1; // Compare lengths. return k == l ? 0 : k > l ^ a ? 1 : -1; } /* * Check that n is a primitive number, an integer, and in range, otherwise throw. */ function intCheck(n, min, max, name) { if (n < min || n > max || n !== mathfloor(n)) { throw Error (bignumberError + (name || 'Argument') + (typeof n == 'number' ? n < min || n > max ? ' out of range: ' : ' not an integer: ' : ' not a primitive number: ') + String(n)); } } // Assumes finite n. function isOdd(n) { var k = n.c.length - 1; return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; } function toExponential(str, e) { return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + (e < 0 ? 'e' : 'e+') + e; } function toFixedPoint(str, e, z) { var len, zs; // Negative exponent? if (e < 0) { // Prepend zeros. for (zs = z + '.'; ++e; zs += z); str = zs + str; // Positive exponent } else { len = str.length; // Append zeros. if (++e > len) { for (zs = z, e -= len; --e; zs += z); str += zs; } else if (e < len) { str = str.slice(0, e) + '.' + str.slice(e); } } return str; } // EXPORT BigNumber = clone(); BigNumber['default'] = BigNumber.BigNumber = BigNumber; // AMD. if (typeof define == 'function' && define.amd) { define(function () { return BigNumber; }); // Node.js and other environments that support module.exports. } else if ( true && module.exports) { module.exports = BigNumber; // Browser. } else { if (!globalObject) { globalObject = typeof self != 'undefined' && self ? self : window; } globalObject.BigNumber = BigNumber; } })(this); /***/ }), /***/ 4691: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var concatMap = __nccwpck_require__(7087); var balanced = __nccwpck_require__(9380); module.exports = expandTop; var escSlash = '\0SLASH'+Math.random()+'\0'; var escOpen = '\0OPEN'+Math.random()+'\0'; var escClose = '\0CLOSE'+Math.random()+'\0'; var escComma = '\0COMMA'+Math.random()+'\0'; var escPeriod = '\0PERIOD'+Math.random()+'\0'; function numeric(str) { return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0); } function escapeBraces(str) { return str.split('\\\\').join(escSlash) .split('\\{').join(escOpen) .split('\\}').join(escClose) .split('\\,').join(escComma) .split('\\.').join(escPeriod); } function unescapeBraces(str) { return str.split(escSlash).join('\\') .split(escOpen).join('{') .split(escClose).join('}') .split(escComma).join(',') .split(escPeriod).join('.'); } // Basically just str.split(","), but handling cases // where we have nested braced sections, which should be // treated as individual members, like {a,{b,c},d} function parseCommaParts(str) { if (!str) return ['']; var parts = []; var m = balanced('{', '}', str); if (!m) return str.split(','); var pre = m.pre; var body = m.body; var post = m.post; var p = pre.split(','); p[p.length-1] += '{' + body + '}'; var postParts = parseCommaParts(post); if (post.length) { p[p.length-1] += postParts.shift(); p.push.apply(p, postParts); } parts.push.apply(parts, p); return parts; } 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); } function identity(e) { return e; } function embrace(str) { return '{' + str + '}'; } function isPadded(el) { return /^-?0\d/.test(el); } function lte(i, y) { return i <= y; } function gte(i, y) { return i >= y; } 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) : ['']; var N; if (isSequence) { var x = numeric(n[0]); var y = numeric(n[1]); var width = Math.max(n[0].length, n[1].length) var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1; var test = lte; var reverse = y < x; if (reverse) { incr *= -1; test = gte; } var pad = n.some(isPadded); N = []; for (var i = x; test(i, y); i += incr) { var c; if (isAlphaSequence) { c = String.fromCharCode(i); if (c === '\\') c = ''; } else { c = String(i); if (pad) { var need = width - c.length; if (need > 0) { var z = new Array(need + 1).join('0'); if (i < 0) c = '-' + z + c.slice(1); else c = z + c; } } } N.push(c); } } else { N = 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); } } return expansions; } /***/ }), /***/ 9732: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /*jshint node:true */ var Buffer = (__nccwpck_require__(181).Buffer); // browserify var SlowBuffer = (__nccwpck_require__(181).SlowBuffer); module.exports = bufferEq; function bufferEq(a, b) { // shortcutting on type is necessary for correctness if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { return false; } // buffer sizes should be well-known information, so despite this // shortcutting, it doesn't leak any information about the *contents* of the // buffers. if (a.length !== b.length) { return false; } var c = 0; for (var i = 0; i < a.length; i++) { /*jshint bitwise:false */ c |= a[i] ^ b[i]; // XOR } return c === 0; } bufferEq.install = function() { Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) { return bufferEq(this, that); }; }; var origBufEqual = Buffer.prototype.equal; var origSlowBufEqual = SlowBuffer.prototype.equal; bufferEq.restore = function() { Buffer.prototype.equal = origBufEqual; SlowBuffer.prototype.equal = origSlowBufEqual; }; /***/ }), /***/ 5630: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var util = __nccwpck_require__(9023); var Stream = (__nccwpck_require__(2203).Stream); var DelayedStream = __nccwpck_require__(2710); 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]; } 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; } this._handleErrors(stream); if (this.pauseStreams) { stream.pause(); } } 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 } this._insideLoop = true; try { do { this._pendingNext = false; this._realGetNext(); } while (this._pendingNext); } finally { this._insideLoop = false; } }; CombinedStream.prototype._realGetNext = function() { var stream = this._streams.shift(); if (typeof stream == 'undefined') { this.end(); return; } if (typeof stream !== 'function') { this._pipeNext(stream); return; } var getStream = stream; getStream(function(stream) { var isStreamLike = CombinedStream.isStreamLike(stream); if (isStreamLike) { stream.on('data', this._checkDataSize.bind(this)); this._handleErrors(stream); } this._pipeNext(stream); }.bind(this)); }; CombinedStream.prototype._pipeNext = function(stream) { this._currentStream = stream; var isStreamLike = CombinedStream.isStreamLike(stream); if (isStreamLike) { stream.on('end', this._getNext.bind(this)); stream.pipe(this, {end: false}); return; } var value = stream; this.write(value); this._getNext(); }; CombinedStream.prototype._handleErrors = function(stream) { var self = this; stream.on('error', function(err) { self._emitError(err); }); }; CombinedStream.prototype.write = function(data) { this.emit('data', data); }; CombinedStream.prototype.pause = function() { if (!this.pauseStreams) { return; } if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); this.emit('pause'); }; CombinedStream.prototype.resume = function() { if (!this._released) { this._released = true; this.writable = true; this._getNext(); } if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); this.emit('resume'); }; CombinedStream.prototype.end = function() { this._reset(); this.emit('end'); }; CombinedStream.prototype.destroy = function() { this._reset(); this.emit('close'); }; CombinedStream.prototype._reset = function() { this.writable = false; this._streams = []; this._currentStream = null; }; 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)); }; CombinedStream.prototype._updateDataSize = function() { this.dataSize = 0; var self = this; this._streams.forEach(function(stream) { if (!stream.dataSize) { return; } self.dataSize += stream.dataSize; }); if (this._currentStream && this._currentStream.dataSize) { this.dataSize += this._currentStream.dataSize; } }; CombinedStream.prototype._emitError = function(err) { this._reset(); this.emit('error', err); }; /***/ }), /***/ 7087: /***/ ((module) => { module.exports = function (xs, fn) { var res = []; for (var i = 0; i < xs.length; i++) { var x = fn(xs[i], i); if (isArray(x)) res.push.apply(res, x); else res.push(x); } return res; }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; /***/ }), /***/ 6110: /***/ ((module, exports, __nccwpck_require__) => { /* eslint-env browser */ /** * This is the web browser implementation of `debug()`. */ exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = localstorage(); exports.destroy = (() => { let warned = false; return () => { if (!warned) { warned = true; console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } }; })(); /** * Colors. */ exports.colors = [ '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ // eslint-disable-next-line complexity function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { return true; } // Internet Explorer and Edge do not support colors. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { return false; } // Is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // Is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // Is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || // Double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff); if (!this.useColors) { return; } const c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into let index = 0; let lastC = 0; args[0].replace(/%[a-zA-Z%]/g, match => { if (match === '%%') { return; } index++; if (match === '%c') { // We only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.debug()` when available. * No-op when `console.debug` is not a "function". * If `console.debug` is not available, falls back * to `console.log`. * * @api public */ exports.log = console.debug || console.log || (() => {}); /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (namespaces) { exports.storage.setItem('debug', namespaces); } else { exports.storage.removeItem('debug'); } } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { let r; try { r = exports.storage.getItem('debug'); } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context // The Browser also has localStorage in the global context. return localStorage; } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } module.exports = __nccwpck_require__(897)(exports); const {formatters} = module.exports; /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ formatters.j = function (v) { try { return JSON.stringify(v); } catch (error) { return '[UnexpectedJSONParseError]: ' + error.message; } }; /***/ }), /***/ 897: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. */ function setup(env) { createDebug.debug = createDebug; createDebug.default = createDebug; createDebug.coerce = coerce; createDebug.disable = disable; createDebug.enable = enable; createDebug.enabled = enabled; createDebug.humanize = __nccwpck_require__(744); createDebug.destroy = destroy; Object.keys(env).forEach(key => { createDebug[key] = env[key]; }); /** * The currently active debug mode names, and names to skip. */ createDebug.names = []; createDebug.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ createDebug.formatters = {}; /** * Selects a color for a debug namespace * @param {String} namespace The namespace string for the debug instance to be colored * @return {Number|String} An ANSI color code for the given namespace * @api private */ function selectColor(namespace) { let hash = 0; for (let i = 0; i < namespace.length; i++) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; } createDebug.selectColor = selectColor; /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { let prevTime; let enableOverride = null; let namespacesCache; let enabledCache; function debug(...args) { // Disabled? if (!debug.enabled) { return; } const self = debug; // Set `diff` timestamp const curr = Number(new Date()); const ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; args[0] = createDebug.coerce(args[0]); if (typeof args[0] !== 'string') { // Anything else let's inspect with %O args.unshift('%O'); } // Apply any `formatters` transformations let index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { // If we encounter an escaped % then don't increase the array index if (match === '%%') { return '%'; } index++; const formatter = createDebug.formatters[format]; if (typeof formatter === 'function') { const val = args[index]; match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // Apply env-specific formatting (colors, etc.) createDebug.formatArgs.call(self, args); const logFn = self.log || createDebug.log; logFn.apply(self, args); } debug.namespace = namespace; debug.useColors = createDebug.useColors(); debug.color = createDebug.selectColor(namespace); debug.extend = extend; debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. Object.defineProperty(debug, 'enabled', { enumerable: true, configurable: false, get: () => { if (enableOverride !== null) { return enableOverride; } if (namespacesCache !== createDebug.namespaces) { namespacesCache = createDebug.namespaces; enabledCache = createDebug.enabled(namespace); } return enabledCache; }, set: v => { enableOverride = v; } }); // Env-specific initialization logic for debug instances if (typeof createDebug.init === 'function') { createDebug.init(debug); } return debug; } function extend(namespace, delimiter) { const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); newDebug.log = this.log; return newDebug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { createDebug.save(namespaces); createDebug.namespaces = namespaces; createDebug.names = []; createDebug.skips = []; let i; const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); const len = split.length; for (i = 0; i < len; i++) { if (!split[i]) { // ignore empty strings continue; } namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); } else { createDebug.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @return {String} namespaces * @api public */ function disable() { const namespaces = [ ...createDebug.names.map(toNamespace), ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) ].join(','); createDebug.enable(''); return namespaces; } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { if (name[name.length - 1] === '*') { return true; } let i; let len; for (i = 0, len = createDebug.skips.length; i < len; i++) { if (createDebug.skips[i].test(name)) { return false; } } for (i = 0, len = createDebug.names.length; i < len; i++) { if (createDebug.names[i].test(name)) { return true; } } return false; } /** * Convert regexp to namespace * * @param {RegExp} regxep * @return {String} namespace * @api private */ function toNamespace(regexp) { return regexp.toString() .substring(2, regexp.toString().length - 2) .replace(/\.\*\?$/, '*'); } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) { return val.stack || val.message; } return val; } /** * XXX DO NOT USE. This is a temporary stub function. * XXX It WILL be removed in the next major release. */ function destroy() { console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } createDebug.enable(createDebug.load()); return createDebug; } module.exports = setup; /***/ }), /***/ 2830: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** * Detect Electron renderer / nwjs process, which is node, but we should * treat as a browser. */ if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { module.exports = __nccwpck_require__(6110); } else { module.exports = __nccwpck_require__(5108); } /***/ }), /***/ 5108: /***/ ((module, exports, __nccwpck_require__) => { /** * Module dependencies. */ const tty = __nccwpck_require__(2018); const util = __nccwpck_require__(9023); /** * This is the Node.js implementation of `debug()`. */ exports.init = init; exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.destroy = util.deprecate( () => {}, 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' ); /** * Colors. */ exports.colors = [6, 2, 3, 4, 5, 1]; try { // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) // eslint-disable-next-line import/no-extraneous-dependencies const supportsColor = __nccwpck_require__(1450); if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { exports.colors = [ 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221 ]; } } catch (error) { // Swallow - we only care if `supports-color` is available; it doesn't have to be. } /** * Build up the default `inspectOpts` object from the environment variables. * * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ exports.inspectOpts = Object.keys(process.env).filter(key => { return /^debug_/i.test(key); }).reduce((obj, key) => { // Camel-case const prop = key .substring(6) .toLowerCase() .replace(/_([a-z])/g, (_, k) => { return k.toUpperCase(); }); // Coerce string value into JS value let val = process.env[key]; if (/^(yes|on|true|enabled)$/i.test(val)) { val = true; } else if (/^(no|off|false|disabled)$/i.test(val)) { val = false; } else if (val === 'null') { val = null; } else { val = Number(val); } obj[prop] = val; return obj; }, {}); /** * Is stdout a TTY? Colored output is enabled when `true`. */ function useColors() { return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd); } /** * Adds ANSI color escape codes if enabled. * * @api public */ function formatArgs(args) { const {namespace: name, useColors} = this; if (useColors) { const c = this.color; const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); const prefix = ` ${colorCode};1m${name} \u001B[0m`; args[0] = prefix + args[0].split('\n').join('\n' + prefix); args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); } else { args[0] = getDate() + name + ' ' + args[0]; } } function getDate() { if (exports.inspectOpts.hideDate) { return ''; } return new Date().toISOString() + ' '; } /** * Invokes `util.format()` with the specified arguments and writes to stderr. */ function log(...args) { return process.stderr.write(util.format(...args) + '\n'); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { if (namespaces) { process.env.DEBUG = namespaces; } else { // If you set a process.env field to null or undefined, it gets cast to the // string 'null' or 'undefined'. Just delete instead. delete process.env.DEBUG; } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { return process.env.DEBUG; } /** * Init logic for `debug` instances. * * Create a new `inspectOpts` object in case `useColors` is set * differently for a particular `debug` instance. */ function init(debug) { debug.inspectOpts = {}; const keys = Object.keys(exports.inspectOpts); for (let i = 0; i < keys.length; i++) { debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; } } module.exports = __nccwpck_require__(897)(exports); const {formatters} = module.exports; /** * Map %o to `util.inspect()`, all on a single line. */ formatters.o = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts) .split('\n') .map(str => str.trim()) .join(' '); }; /** * Map %O to `util.inspect()`, allowing multiple lines if needed. */ formatters.O = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts); }; /***/ }), /***/ 2710: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var Stream = (__nccwpck_require__(2203).Stream); var util = __nccwpck_require__(9023); 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)); }; /***/ }), /***/ 9112: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var stream = __nccwpck_require__(6131) var eos = __nccwpck_require__(1424) var inherits = __nccwpck_require__(9598) var shift = __nccwpck_require__(4633) var SIGNAL_FLUSH = (Buffer.from && Buffer.from !== Uint8Array.from) ? Buffer.from([0]) : new Buffer([0]) var onuncork = function(self, fn) { if (self._corked) self.once('uncork', fn) else fn() } var autoDestroy = function (self, err) { if (self._autoDestroy) self.destroy(err) } var destroyer = function(self, end) { return function(err) { if (err) autoDestroy(self, err.message === 'premature close' ? null : err) else if (end && !self._ended) self.end() } } var end = function(ws, fn) { if (!ws) return fn() if (ws._writableState && ws._writableState.finished) return fn() if (ws._writableState) return ws.end(fn) ws.end() fn() } var noop = function() {} var toStreams2 = function(rs) { return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs) } var Duplexify = function(writable, readable, opts) { if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts) stream.Duplex.call(this, opts) this._writable = null this._readable = null this._readable2 = null this._autoDestroy = !opts || opts.autoDestroy !== false this._forwardDestroy = !opts || opts.destroy !== false this._forwardEnd = !opts || opts.end !== false this._corked = 1 // start corked this._ondrain = null this._drained = false this._forwarding = false this._unwrite = null this._unread = null this._ended = false this.destroyed = false if (writable) this.setWritable(writable) if (readable) this.setReadable(readable) } inherits(Duplexify, stream.Duplex) Duplexify.obj = function(writable, readable, opts) { if (!opts) opts = {} opts.objectMode = true opts.highWaterMark = 16 return new Duplexify(writable, readable, opts) } Duplexify.prototype.cork = function() { if (++this._corked === 1) this.emit('cork') } Duplexify.prototype.uncork = function() { if (this._corked && --this._corked === 0) this.emit('uncork') } Duplexify.prototype.setWritable = function(writable) { if (this._unwrite) this._unwrite() if (this.destroyed) { if (writable && writable.destroy) writable.destroy() return } if (writable === null || writable === false) { this.end() return } var self = this var unend = eos(writable, {writable:true, readable:false}, destroyer(this, this._forwardEnd)) var ondrain = function() { var ondrain = self._ondrain self._ondrain = null if (ondrain) ondrain() } var clear = function() { self._writable.removeListener('drain', ondrain) unend() } if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks this._writable = writable this._writable.on('drain', ondrain) this._unwrite = clear this.uncork() // always uncork setWritable } Duplexify.prototype.setReadable = function(readable) { if (this._unread) this._unread() if (this.destroyed) { if (readable && readable.destroy) readable.destroy() return } if (readable === null || readable === false) { this.push(null) this.resume() return } var self = this var unend = eos(readable, {writable:false, readable:true}, destroyer(this)) var onreadable = function() { self._forward() } var onend = function() { self.push(null) } var clear = function() { self._readable2.removeListener('readable', onreadable) self._readable2.removeListener('end', onend) unend() } this._drained = true this._readable = readable this._readable2 = readable._readableState ? readable : toStreams2(readable) this._readable2.on('readable', onreadable) this._readable2.on('end', onend) this._unread = clear this._forward() } Duplexify.prototype._read = function() { this._drained = true this._forward() } Duplexify.prototype._forward = function() { if (this._forwarding || !this._readable2 || !this._drained) return this._forwarding = true var data while (this._drained && (data = shift(this._readable2)) !== null) { if (this.destroyed) continue this._drained = this.push(data) } this._forwarding = false } Duplexify.prototype.destroy = function(err, cb) { if (!cb) cb = noop if (this.destroyed) return cb(null) this.destroyed = true var self = this process.nextTick(function() { self._destroy(err) cb(null) }) } Duplexify.prototype._destroy = function(err) { if (err) { var ondrain = this._ondrain this._ondrain = null if (ondrain) ondrain(err) else this.emit('error', err) } if (this._forwardDestroy) { if (this._readable && this._readable.destroy) this._readable.destroy() if (this._writable && this._writable.destroy) this._writable.destroy() } this.emit('close') } Duplexify.prototype._write = function(data, enc, cb) { if (this.destroyed) return if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb)) if (data === SIGNAL_FLUSH) return this._finish(cb) if (!this._writable) return cb() if (this._writable.write(data) === false) this._ondrain = cb else if (!this.destroyed) cb() } Duplexify.prototype._finish = function(cb) { var self = this this.emit('preend') onuncork(this, function() { end(self._forwardEnd && self._writable, function() { // haxx to not emit prefinish twice if (self._writableState.prefinished === false) self._writableState.prefinished = true self.emit('prefinish') onuncork(self, cb) }) }) } Duplexify.prototype.end = function(data, enc, cb) { if (typeof data === 'function') return this.end(null, null, data) if (typeof enc === 'function') return this.end(data, null, enc) this._ended = true if (data) this.write(data) if (!this._writableState.ending && !this._writableState.destroyed) this.write(SIGNAL_FLUSH) return stream.Writable.prototype.end.call(this, cb) } module.exports = Duplexify /***/ }), /***/ 325: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var Buffer = (__nccwpck_require__(3058).Buffer); var getParamBytesForAlg = __nccwpck_require__(5028); var MAX_OCTET = 0x80, CLASS_UNIVERSAL = 0, PRIMITIVE_BIT = 0x20, TAG_SEQ = 0x10, TAG_INT = 0x02, ENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6), ENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6); function base64Url(base64) { return base64 .replace(/=/g, '') .replace(/\+/g, '-') .replace(/\//g, '_'); } function signatureAsBuffer(signature) { if (Buffer.isBuffer(signature)) { return signature; } else if ('string' === typeof signature) { return Buffer.from(signature, 'base64'); } throw new TypeError('ECDSA signature must be a Base64 string or a Buffer'); } function derToJose(signature, alg) { signature = signatureAsBuffer(signature); var paramBytes = getParamBytesForAlg(alg); // the DER encoded param should at most be the param size, plus a padding // zero, since due to being a signed integer var maxEncodedParamLength = paramBytes + 1; var inputLength = signature.length; var offset = 0; if (signature[offset++] !== ENCODED_TAG_SEQ) { throw new Error('Could not find expected "seq"'); } var seqLength = signature[offset++]; if (seqLength === (MAX_OCTET | 1)) { seqLength = signature[offset++]; } if (inputLength - offset < seqLength) { throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining'); } if (signature[offset++] !== ENCODED_TAG_INT) { throw new Error('Could not find expected "int" for "r"'); } var rLength = signature[offset++]; if (inputLength - offset - 2 < rLength) { throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available'); } if (maxEncodedParamLength < rLength) { throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); } var rOffset = offset; offset += rLength; if (signature[offset++] !== ENCODED_TAG_INT) { throw new Error('Could not find expected "int" for "s"'); } var sLength = signature[offset++]; if (inputLength - offset !== sLength) { throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"'); } if (maxEncodedParamLength < sLength) { throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); } var sOffset = offset; offset += sLength; if (offset !== inputLength) { throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain'); } var rPadding = paramBytes - rLength, sPadding = paramBytes - sLength; var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength); for (offset = 0; offset < rPadding; ++offset) { dst[offset] = 0; } signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength); offset = paramBytes; for (var o = offset; offset < o + sPadding; ++offset) { dst[offset] = 0; } signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength); dst = dst.toString('base64'); dst = base64Url(dst); return dst; } function countPadding(buf, start, stop) { var padding = 0; while (start + padding < stop && buf[start + padding] === 0) { ++padding; } var needsSign = buf[start + padding] >= MAX_OCTET; if (needsSign) { --padding; } return padding; } function joseToDer(signature, alg) { signature = signatureAsBuffer(signature); var paramBytes = getParamBytesForAlg(alg); var signatureBytes = signature.length; if (signatureBytes !== paramBytes * 2) { throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"'); } var rPadding = countPadding(signature, 0, paramBytes); var sPadding = countPadding(signature, paramBytes, signature.length); var rLength = paramBytes - rPadding; var sLength = paramBytes - sPadding; var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength; var shortLength = rsBytes < MAX_OCTET; var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes); var offset = 0; dst[offset++] = ENCODED_TAG_SEQ; if (shortLength) { // Bit 8 has value "0" // bits 7-1 give the length. dst[offset++] = rsBytes; } else { // Bit 8 of first octet has value "1" // bits 7-1 give the number of additional length octets. dst[offset++] = MAX_OCTET | 1; // length, base 256 dst[offset++] = rsBytes & 0xff; } dst[offset++] = ENCODED_TAG_INT; dst[offset++] = rLength; if (rPadding < 0) { dst[offset++] = 0; offset += signature.copy(dst, offset, 0, paramBytes); } else { offset += signature.copy(dst, offset, rPadding, paramBytes); } dst[offset++] = ENCODED_TAG_INT; dst[offset++] = sLength; if (sPadding < 0) { dst[offset++] = 0; signature.copy(dst, offset, paramBytes); } else { signature.copy(dst, offset, paramBytes + sPadding); } return dst; } module.exports = { derToJose: derToJose, joseToDer: joseToDer }; /***/ }), /***/ 5028: /***/ ((module) => { "use strict"; function getParamSize(keySize) { var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1); return result; } var paramBytesForAlg = { ES256: getParamSize(256), ES384: getParamSize(384), ES512: getParamSize(521) }; function getParamBytesForAlg(alg) { var paramBytes = paramBytesForAlg[alg]; if (paramBytes) { return paramBytes; } throw new Error('Unknown algorithm "' + alg + '"'); } module.exports = getParamBytesForAlg; /***/ }), /***/ 1424: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var once = __nccwpck_require__(5560); var noop = function() {}; var isRequest = function(stream) { return stream.setHeader && typeof stream.abort === 'function'; }; var isChildProcess = function(stream) { return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 }; var eos = function(stream, opts, callback) { if (typeof opts === 'function') return eos(stream, null, opts); if (!opts) opts = {}; callback = once(callback || noop); var ws = stream._writableState; var rs = stream._readableState; var readable = opts.readable || (opts.readable !== false && stream.readable); var writable = opts.writable || (opts.writable !== false && stream.writable); var cancelled = false; var onlegacyfinish = function() { if (!stream.writable) onfinish(); }; var onfinish = function() { writable = false; if (!readable) callback.call(stream); }; var onend = function() { readable = false; if (!writable) callback.call(stream); }; var onexit = function(exitCode) { callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); }; var onerror = function(err) { callback.call(stream, err); }; var onclose = function() { process.nextTick(onclosenexttick); }; var onclosenexttick = function() { if (cancelled) return; if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close')); if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close')); }; var onrequest = function() { stream.req.on('finish', onfinish); }; if (isRequest(stream)) { stream.on('complete', onfinish); stream.on('abort', onclose); if (stream.req) onrequest(); else stream.on('request', onrequest); } else if (writable && !ws) { // legacy streams stream.on('end', onlegacyfinish); stream.on('close', onlegacyfinish); } if (isChildProcess(stream)) stream.on('exit', onexit); stream.on('end', onend); stream.on('finish', onfinish); if (opts.error !== false) stream.on('error', onerror); stream.on('close', onclose); return function() { cancelled = true; stream.removeListener('complete', onfinish); stream.removeListener('abort', onclose); stream.removeListener('request', onrequest); if (stream.req) stream.req.removeListener('finish', onfinish); stream.removeListener('end', onlegacyfinish); stream.removeListener('close', onlegacyfinish); stream.removeListener('finish', onfinish); stream.removeListener('exit', onexit); stream.removeListener('end', onend); stream.removeListener('error', onerror); stream.removeListener('close', onclose); }; }; module.exports = eos; /***/ }), /***/ 6577: /***/ ((module, exports) => { "use strict"; /** * @author Toru Nagashima * @copyright 2015 Toru Nagashima. All rights reserved. * See LICENSE file in root directory for full license. */ Object.defineProperty(exports, "__esModule", ({ value: true })); /** * @typedef {object} PrivateData * @property {EventTarget} eventTarget The event target. * @property {{type:string}} event The original event object. * @property {number} eventPhase The current event phase. * @property {EventTarget|null} currentTarget The current event target. * @property {boolean} canceled The flag to prevent default. * @property {boolean} stopped The flag to stop propagation. * @property {boolean} immediateStopped The flag to stop propagation immediately. * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null. * @property {number} timeStamp The unix time. * @private */ /** * Private data for event wrappers. * @type {WeakMap} * @private */ const privateData = new WeakMap(); /** * Cache for wrapper classes. * @type {WeakMap} * @private */ const wrappers = new WeakMap(); /** * Get private data. * @param {Event} event The event object to get private data. * @returns {PrivateData} The private data of the event. * @private */ function pd(event) { const retv = privateData.get(event); console.assert( retv != null, "'this' is expected an Event object, but got", event ); return retv } /** * https://dom.spec.whatwg.org/#set-the-canceled-flag * @param data {PrivateData} private data. */ function setCancelFlag(data) { if (data.passiveListener != null) { if ( typeof console !== "undefined" && typeof console.error === "function" ) { console.error( "Unable to preventDefault inside passive event listener invocation.", data.passiveListener ); } return } if (!data.event.cancelable) { return } data.canceled = true; if (typeof data.event.preventDefault === "function") { data.event.preventDefault(); } } /** * @see https://dom.spec.whatwg.org/#interface-event * @private */ /** * The event wrapper. * @constructor * @param {EventTarget} eventTarget The event target of this dispatching. * @param {Event|{type:string}} event The original event to wrap. */ function Event(eventTarget, event) { privateData.set(this, { eventTarget, event, eventPhase: 2, currentTarget: eventTarget, canceled: false, stopped: false, immediateStopped: false, passiveListener: null, timeStamp: event.timeStamp || Date.now(), }); // https://heycam.github.io/webidl/#Unforgeable Object.defineProperty(this, "isTrusted", { value: false, enumerable: true }); // Define accessors const keys = Object.keys(event); for (let i = 0; i < keys.length; ++i) { const key = keys[i]; if (!(key in this)) { Object.defineProperty(this, key, defineRedirectDescriptor(key)); } } } // Should be enumerable, but class methods are not enumerable. Event.prototype = { /** * The type of this event. * @type {string} */ get type() { return pd(this).event.type }, /** * The target of this event. * @type {EventTarget} */ get target() { return pd(this).eventTarget }, /** * The target of this event. * @type {EventTarget} */ get currentTarget() { return pd(this).currentTarget }, /** * @returns {EventTarget[]} The composed path of this event. */ composedPath() { const currentTarget = pd(this).currentTarget; if (currentTarget == null) { return [] } return [currentTarget] }, /** * Constant of NONE. * @type {number} */ get NONE() { return 0 }, /** * Constant of CAPTURING_PHASE. * @type {number} */ get CAPTURING_PHASE() { return 1 }, /** * Constant of AT_TARGET. * @type {number} */ get AT_TARGET() { return 2 }, /** * Constant of BUBBLING_PHASE. * @type {number} */ get BUBBLING_PHASE() { return 3 }, /** * The target of this event. * @type {number} */ get eventPhase() { return pd(this).eventPhase }, /** * Stop event bubbling. * @returns {void} */ stopPropagation() { const data = pd(this); data.stopped = true; if (typeof data.event.stopPropagation === "function") { data.event.stopPropagation(); } }, /** * Stop event bubbling. * @returns {void} */ stopImmediatePropagation() { const data = pd(this); data.stopped = true; data.immediateStopped = true; if (typeof data.event.stopImmediatePropagation === "function") { data.event.stopImmediatePropagation(); } }, /** * The flag to be bubbling. * @type {boolean} */ get bubbles() { return Boolean(pd(this).event.bubbles) }, /** * The flag to be cancelable. * @type {boolean} */ get cancelable() { return Boolean(pd(this).event.cancelable) }, /** * Cancel this event. * @returns {void} */ preventDefault() { setCancelFlag(pd(this)); }, /** * The flag to indicate cancellation state. * @type {boolean} */ get defaultPrevented() { return pd(this).canceled }, /** * The flag to be composed. * @type {boolean} */ get composed() { return Boolean(pd(this).event.composed) }, /** * The unix time of this event. * @type {number} */ get timeStamp() { return pd(this).timeStamp }, /** * The target of this event. * @type {EventTarget} * @deprecated */ get srcElement() { return pd(this).eventTarget }, /** * The flag to stop event bubbling. * @type {boolean} * @deprecated */ get cancelBubble() { return pd(this).stopped }, set cancelBubble(value) { if (!value) { return } const data = pd(this); data.stopped = true; if (typeof data.event.cancelBubble === "boolean") { data.event.cancelBubble = true; } }, /** * The flag to indicate cancellation state. * @type {boolean} * @deprecated */ get returnValue() { return !pd(this).canceled }, set returnValue(value) { if (!value) { setCancelFlag(pd(this)); } }, /** * Initialize this event object. But do nothing under event dispatching. * @param {string} type The event type. * @param {boolean} [bubbles=false] The flag to be possible to bubble up. * @param {boolean} [cancelable=false] The flag to be possible to cancel. * @deprecated */ initEvent() { // Do nothing. }, }; // `constructor` is not enumerable. Object.defineProperty(Event.prototype, "constructor", { value: Event, configurable: true, writable: true, }); // Ensure `event instanceof window.Event` is `true`. if (typeof window !== "undefined" && typeof window.Event !== "undefined") { Object.setPrototypeOf(Event.prototype, window.Event.prototype); // Make association for wrappers. wrappers.set(window.Event.prototype, Event); } /** * Get the property descriptor to redirect a given property. * @param {string} key Property name to define property descriptor. * @returns {PropertyDescriptor} The property descriptor to redirect the property. * @private */ function defineRedirectDescriptor(key) { return { get() { return pd(this).event[key] }, set(value) { pd(this).event[key] = value; }, configurable: true, enumerable: true, } } /** * Get the property descriptor to call a given method property. * @param {string} key Property name to define property descriptor. * @returns {PropertyDescriptor} The property descriptor to call the method property. * @private */ function defineCallDescriptor(key) { return { value() { const event = pd(this).event; return event[key].apply(event, arguments) }, configurable: true, enumerable: true, } } /** * Define new wrapper class. * @param {Function} BaseEvent The base wrapper class. * @param {Object} proto The prototype of the original event. * @returns {Function} The defined wrapper class. * @private */ function defineWrapper(BaseEvent, proto) { const keys = Object.keys(proto); if (keys.length === 0) { return BaseEvent } /** CustomEvent */ function CustomEvent(eventTarget, event) { BaseEvent.call(this, eventTarget, event); } CustomEvent.prototype = Object.create(BaseEvent.prototype, { constructor: { value: CustomEvent, configurable: true, writable: true }, }); // Define accessors. for (let i = 0; i < keys.length; ++i) { const key = keys[i]; if (!(key in BaseEvent.prototype)) { const descriptor = Object.getOwnPropertyDescriptor(proto, key); const isFunc = typeof descriptor.value === "function"; Object.defineProperty( CustomEvent.prototype, key, isFunc ? defineCallDescriptor(key) : defineRedirectDescriptor(key) ); } } return CustomEvent } /** * Get the wrapper class of a given prototype. * @param {Object} proto The prototype of the original event to get its wrapper. * @returns {Function} The wrapper class. * @private */ function getWrapper(proto) { if (proto == null || proto === Object.prototype) { return Event } let wrapper = wrappers.get(proto); if (wrapper == null) { wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto); wrappers.set(proto, wrapper); } return wrapper } /** * Wrap a given event to management a dispatching. * @param {EventTarget} eventTarget The event target of this dispatching. * @param {Object} event The event to wrap. * @returns {Event} The wrapper instance. * @private */ function wrapEvent(eventTarget, event) { const Wrapper = getWrapper(Object.getPrototypeOf(event)); return new Wrapper(eventTarget, event) } /** * Get the immediateStopped flag of a given event. * @param {Event} event The event to get. * @returns {boolean} The flag to stop propagation immediately. * @private */ function isStopped(event) { return pd(event).immediateStopped } /** * Set the current event phase of a given event. * @param {Event} event The event to set current target. * @param {number} eventPhase New event phase. * @returns {void} * @private */ function setEventPhase(event, eventPhase) { pd(event).eventPhase = eventPhase; } /** * Set the current target of a given event. * @param {Event} event The event to set current target. * @param {EventTarget|null} currentTarget New current target. * @returns {void} * @private */ function setCurrentTarget(event, currentTarget) { pd(event).currentTarget = currentTarget; } /** * Set a passive listener of a given event. * @param {Event} event The event to set current target. * @param {Function|null} passiveListener New passive listener. * @returns {void} * @private */ function setPassiveListener(event, passiveListener) { pd(event).passiveListener = passiveListener; } /** * @typedef {object} ListenerNode * @property {Function} listener * @property {1|2|3} listenerType * @property {boolean} passive * @property {boolean} once * @property {ListenerNode|null} next * @private */ /** * @type {WeakMap>} * @private */ const listenersMap = new WeakMap(); // Listener types const CAPTURE = 1; const BUBBLE = 2; const ATTRIBUTE = 3; /** * Check whether a given value is an object or not. * @param {any} x The value to check. * @returns {boolean} `true` if the value is an object. */ function isObject(x) { return x !== null && typeof x === "object" //eslint-disable-line no-restricted-syntax } /** * Get listeners. * @param {EventTarget} eventTarget The event target to get. * @returns {Map} The listeners. * @private */ function getListeners(eventTarget) { const listeners = listenersMap.get(eventTarget); if (listeners == null) { throw new TypeError( "'this' is expected an EventTarget object, but got another value." ) } return listeners } /** * Get the property descriptor for the event attribute of a given event. * @param {string} eventName The event name to get property descriptor. * @returns {PropertyDescriptor} The property descriptor. * @private */ function defineEventAttributeDescriptor(eventName) { return { get() { const listeners = getListeners(this); let node = listeners.get(eventName); while (node != null) { if (node.listenerType === ATTRIBUTE) { return node.listener } node = node.next; } return null }, set(listener) { if (typeof listener !== "function" && !isObject(listener)) { listener = null; // eslint-disable-line no-param-reassign } const listeners = getListeners(this); // Traverse to the tail while removing old value. let prev = null; let node = listeners.get(eventName); while (node != null) { if (node.listenerType === ATTRIBUTE) { // Remove old value. if (prev !== null) { prev.next = node.next; } else if (node.next !== null) { listeners.set(eventName, node.next); } else { listeners.delete(eventName); } } else { prev = node; } node = node.next; } // Add new value. if (listener !== null) { const newNode = { listener, listenerType: ATTRIBUTE, passive: false, once: false, next: null, }; if (prev === null) { listeners.set(eventName, newNode); } else { prev.next = newNode; } } }, configurable: true, enumerable: true, } } /** * Define an event attribute (e.g. `eventTarget.onclick`). * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite. * @param {string} eventName The event name to define. * @returns {void} */ function defineEventAttribute(eventTargetPrototype, eventName) { Object.defineProperty( eventTargetPrototype, `on${eventName}`, defineEventAttributeDescriptor(eventName) ); } /** * Define a custom EventTarget with event attributes. * @param {string[]} eventNames Event names for event attributes. * @returns {EventTarget} The custom EventTarget. * @private */ function defineCustomEventTarget(eventNames) { /** CustomEventTarget */ function CustomEventTarget() { EventTarget.call(this); } CustomEventTarget.prototype = Object.create(EventTarget.prototype, { constructor: { value: CustomEventTarget, configurable: true, writable: true, }, }); for (let i = 0; i < eventNames.length; ++i) { defineEventAttribute(CustomEventTarget.prototype, eventNames[i]); } return CustomEventTarget } /** * EventTarget. * * - This is constructor if no arguments. * - This is a function which returns a CustomEventTarget constructor if there are arguments. * * For example: * * class A extends EventTarget {} * class B extends EventTarget("message") {} * class C extends EventTarget("message", "error") {} * class D extends EventTarget(["message", "error"]) {} */ function EventTarget() { /*eslint-disable consistent-return */ if (this instanceof EventTarget) { listenersMap.set(this, new Map()); return } if (arguments.length === 1 && Array.isArray(arguments[0])) { return defineCustomEventTarget(arguments[0]) } if (arguments.length > 0) { const types = new Array(arguments.length); for (let i = 0; i < arguments.length; ++i) { types[i] = arguments[i]; } return defineCustomEventTarget(types) } throw new TypeError("Cannot call a class as a function") /*eslint-enable consistent-return */ } // Should be enumerable, but class methods are not enumerable. EventTarget.prototype = { /** * Add a given listener to this event target. * @param {string} eventName The event name to add. * @param {Function} listener The listener to add. * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. * @returns {void} */ addEventListener(eventName, listener, options) { if (listener == null) { return } if (typeof listener !== "function" && !isObject(listener)) { throw new TypeError("'listener' should be a function or an object.") } const listeners = getListeners(this); const optionsIsObj = isObject(options); const capture = optionsIsObj ? Boolean(options.capture) : Boolean(options); const listenerType = capture ? CAPTURE : BUBBLE; const newNode = { listener, listenerType, passive: optionsIsObj && Boolean(options.passive), once: optionsIsObj && Boolean(options.once), next: null, }; // Set it as the first node if the first node is null. let node = listeners.get(eventName); if (node === undefined) { listeners.set(eventName, newNode); return } // Traverse to the tail while checking duplication.. let prev = null; while (node != null) { if ( node.listener === listener && node.listenerType === listenerType ) { // Should ignore duplication. return } prev = node; node = node.next; } // Add it. prev.next = newNode; }, /** * Remove a given listener from this event target. * @param {string} eventName The event name to remove. * @param {Function} listener The listener to remove. * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. * @returns {void} */ removeEventListener(eventName, listener, options) { if (listener == null) { return } const listeners = getListeners(this); const capture = isObject(options) ? Boolean(options.capture) : Boolean(options); const listenerType = capture ? CAPTURE : BUBBLE; let prev = null; let node = listeners.get(eventName); while (node != null) { if ( node.listener === listener && node.listenerType === listenerType ) { if (prev !== null) { prev.next = node.next; } else if (node.next !== null) { listeners.set(eventName, node.next); } else { listeners.delete(eventName); } return } prev = node; node = node.next; } }, /** * Dispatch a given event. * @param {Event|{type:string}} event The event to dispatch. * @returns {boolean} `false` if canceled. */ dispatchEvent(event) { if (event == null || typeof event.type !== "string") { throw new TypeError('"event.type" should be a string.') } // If listeners aren't registered, terminate. const listeners = getListeners(this); const eventName = event.type; let node = listeners.get(eventName); if (node == null) { return true } // Since we cannot rewrite several properties, so wrap object. const wrappedEvent = wrapEvent(this, event); // This doesn't process capturing phase and bubbling phase. // This isn't participating in a tree. let prev = null; while (node != null) { // Remove this listener if it's once if (node.once) { if (prev !== null) { prev.next = node.next; } else if (node.next !== null) { listeners.set(eventName, node.next); } else { listeners.delete(eventName); } } else { prev = node; } // Call this listener setPassiveListener( wrappedEvent, node.passive ? node.listener : null ); if (typeof node.listener === "function") { try { node.listener.call(this, wrappedEvent); } catch (err) { if ( typeof console !== "undefined" && typeof console.error === "function" ) { console.error(err); } } } else if ( node.listenerType !== ATTRIBUTE && typeof node.listener.handleEvent === "function" ) { node.listener.handleEvent(wrappedEvent); } // Break if `event.stopImmediatePropagation` was called. if (isStopped(wrappedEvent)) { break } node = node.next; } setPassiveListener(wrappedEvent, null); setEventPhase(wrappedEvent, 0); setCurrentTarget(wrappedEvent, null); return !wrappedEvent.defaultPrevented }, }; // `constructor` is not enumerable. Object.defineProperty(EventTarget.prototype, "constructor", { value: EventTarget, configurable: true, writable: true, }); // Ensure `eventTarget instanceof window.EventTarget` is `true`. if ( typeof window !== "undefined" && typeof window.EventTarget !== "undefined" ) { Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype); } exports.defineEventAttribute = defineEventAttribute; exports.EventTarget = EventTarget; exports["default"] = EventTarget; module.exports = EventTarget module.exports.EventTarget = module.exports["default"] = EventTarget module.exports.defineEventAttribute = defineEventAttribute //# sourceMappingURL=event-target-shim.js.map /***/ }), /***/ 3860: /***/ ((module) => { "use strict"; var hasOwn = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var defineProperty = Object.defineProperty; var gOPD = Object.getOwnPropertyDescriptor; var isArray = function isArray(arr) { if (typeof Array.isArray === 'function') { return Array.isArray(arr); } return toStr.call(arr) === '[object Array]'; }; var isPlainObject = function isPlainObject(obj) { if (!obj || toStr.call(obj) !== '[object Object]') { return false; } var hasOwnConstructor = hasOwn.call(obj, 'constructor'); var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); // Not own constructor property must be Object if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for (key in obj) { /**/ } return typeof key === 'undefined' || hasOwn.call(obj, key); }; // If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target var setProperty = function setProperty(target, options) { if (defineProperty && options.name === '__proto__') { defineProperty(target, options.name, { enumerable: true, configurable: true, value: options.newValue, writable: true }); } else { target[options.name] = options.newValue; } }; // Return undefined instead of __proto__ if '__proto__' is not an own property var getProperty = function getProperty(obj, name) { if (name === '__proto__') { if (!hasOwn.call(obj, name)) { return void 0; } else if (gOPD) { // In early versions of node, obj['__proto__'] is buggy when obj has // __proto__ as an own property. Object.getOwnPropertyDescriptor() works. return gOPD(obj, name).value; } } return obj[name]; }; module.exports = function extend() { var options, name, src, copy, copyIsArray, clone; var target = arguments[0]; var i = 1; var length = arguments.length; var deep = false; // Handle a deep copy situation if (typeof target === 'boolean') { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } if (target == null || (typeof target !== 'object' && typeof target !== 'function')) { target = {}; } for (; i < length; ++i) { options = arguments[i]; // Only deal with non-null/undefined values if (options != null) { // Extend the base object for (name in options) { src = getProperty(target, name); copy = getProperty(options, name); // Prevent never-ending loop if (target !== copy) { // Recurse if we're merging plain objects or arrays if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { if (copyIsArray) { copyIsArray = false; clone = src && isArray(src) ? src : []; } else { clone = src && isPlainObject(src) ? src : {}; } // Never move original objects, clone them setProperty(target, { name: name, newValue: extend(deep, clone, copy) }); // Don't bring in undefined values } else if (typeof copy !== 'undefined') { setProperty(target, { name: name, newValue: copy }); } } } } } // Return the modified object return target; }; /***/ }), /***/ 9741: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const validator = __nccwpck_require__(9433); const XMLParser = __nccwpck_require__(9844); const XMLBuilder = __nccwpck_require__(659); module.exports = { XMLParser: XMLParser, XMLValidator: validator, XMLBuilder: XMLBuilder } /***/ }), /***/ 812: /***/ ((module) => { function getIgnoreAttributesFn(ignoreAttributes) { if (typeof ignoreAttributes === 'function') { return ignoreAttributes } if (Array.isArray(ignoreAttributes)) { return (attrName) => { for (const pattern of ignoreAttributes) { if (typeof pattern === 'string' && attrName === pattern) { return true } if (pattern instanceof RegExp && pattern.test(attrName)) { return true } } } } return () => false } module.exports = getIgnoreAttributesFn /***/ }), /***/ 7019: /***/ ((__unused_webpack_module, exports) => { "use strict"; const nameStartChar = ':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'; const nameChar = nameStartChar + '\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040'; const nameRegexp = '[' + nameStartChar + '][' + nameChar + ']*' const regexName = new RegExp('^' + nameRegexp + '$'); const getAllMatches = function(string, regex) { const matches = []; let match = regex.exec(string); while (match) { const allmatches = []; allmatches.startIndex = regex.lastIndex - match[0].length; const len = match.length; for (let index = 0; index < len; index++) { allmatches.push(match[index]); } matches.push(allmatches); match = regex.exec(string); } return matches; }; const isName = function(string) { const match = regexName.exec(string); return !(match === null || typeof match === 'undefined'); }; exports.isExist = function(v) { return typeof v !== 'undefined'; }; exports.isEmptyObject = function(obj) { return Object.keys(obj).length === 0; }; /** * Copy all the properties of a into b. * @param {*} target * @param {*} a */ exports.merge = function(target, a, arrayMode) { if (a) { const keys = Object.keys(a); // will return an array of own properties const len = keys.length; //don't make it inline for (let i = 0; i < len; i++) { if (arrayMode === 'strict') { target[keys[i]] = [ a[keys[i]] ]; } else { target[keys[i]] = a[keys[i]]; } } } }; /* exports.merge =function (b,a){ return Object.assign(b,a); } */ exports.getValue = function(v) { if (exports.isExist(v)) { return v; } else { return ''; } }; // const fakeCall = function(a) {return a;}; // const fakeCallNoReturn = function() {}; exports.isName = isName; exports.getAllMatches = getAllMatches; exports.nameRegexp = nameRegexp; /***/ }), /***/ 9433: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; const util = __nccwpck_require__(7019); const defaultOptions = { allowBooleanAttributes: false, //A tag can have attributes without any value unpairedTags: [] }; //const tagsPattern = new RegExp("<\\/?([\\w:\\-_\.]+)\\s*\/?>","g"); exports.validate = function (xmlData, options) { options = Object.assign({}, defaultOptions, options); //xmlData = xmlData.replace(/(\r\n|\n|\r)/gm,"");//make it single line //xmlData = xmlData.replace(/(^\s*<\?xml.*?\?>)/g,"");//Remove XML starting tag //xmlData = xmlData.replace(/()/g,"");//Remove DOCTYPE const tags = []; let tagFound = false; //indicates that the root tag has been closed (aka. depth 0 has been reached) let reachedRoot = false; if (xmlData[0] === '\ufeff') { // check for byte order mark (BOM) xmlData = xmlData.substr(1); } for (let i = 0; i < xmlData.length; i++) { if (xmlData[i] === '<' && xmlData[i+1] === '?') { i+=2; i = readPI(xmlData,i); if (i.err) return i; }else if (xmlData[i] === '<') { //starting of tag //read until you reach to '>' avoiding any '>' in attribute value let tagStartPos = i; i++; if (xmlData[i] === '!') { i = readCommentAndCDATA(xmlData, i); continue; } else { let closingTag = false; if (xmlData[i] === '/') { //closing tag closingTag = true; i++; } //read tagname let tagName = ''; for (; i < xmlData.length && xmlData[i] !== '>' && xmlData[i] !== ' ' && xmlData[i] !== '\t' && xmlData[i] !== '\n' && xmlData[i] !== '\r'; i++ ) { tagName += xmlData[i]; } tagName = tagName.trim(); //console.log(tagName); if (tagName[tagName.length - 1] === '/') { //self closing tag without attributes tagName = tagName.substring(0, tagName.length - 1); //continue; i--; } if (!validateTagName(tagName)) { let msg; if (tagName.trim().length === 0) { msg = "Invalid space after '<'."; } else { msg = "Tag '"+tagName+"' is an invalid name."; } return getErrorObject('InvalidTag', msg, getLineNumberForPosition(xmlData, i)); } const result = readAttributeStr(xmlData, i); if (result === false) { return getErrorObject('InvalidAttr', "Attributes for '"+tagName+"' have open quote.", getLineNumberForPosition(xmlData, i)); } let attrStr = result.value; i = result.index; if (attrStr[attrStr.length - 1] === '/') { //self closing tag const attrStrStart = i - attrStr.length; attrStr = attrStr.substring(0, attrStr.length - 1); const isValid = validateAttributeString(attrStr, options); if (isValid === true) { tagFound = true; //continue; //text may presents after self closing tag } else { //the result from the nested function returns the position of the error within the attribute //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute //this gives us the absolute index in the entire xml, which we can use to find the line at last return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line)); } } else if (closingTag) { if (!result.tagClosed) { return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' doesn't have proper closing.", getLineNumberForPosition(xmlData, i)); } else if (attrStr.trim().length > 0) { return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos)); } else if (tags.length === 0) { return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos)); } else { const otg = tags.pop(); if (tagName !== otg.tagName) { let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos); return getErrorObject('InvalidTag', "Expected closing tag '"+otg.tagName+"' (opened in line "+openPos.line+", col "+openPos.col+") instead of closing tag '"+tagName+"'.", getLineNumberForPosition(xmlData, tagStartPos)); } //when there are no more tags, we reached the root level. if (tags.length == 0) { reachedRoot = true; } } } else { const isValid = validateAttributeString(attrStr, options); if (isValid !== true) { //the result from the nested function returns the position of the error within the attribute //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute //this gives us the absolute index in the entire xml, which we can use to find the line at last return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line)); } //if the root level has been reached before ... if (reachedRoot === true) { return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i)); } else if(options.unpairedTags.indexOf(tagName) !== -1){ //don't push into stack } else { tags.push({tagName, tagStartPos}); } tagFound = true; } //skip tag text value //It may include comments and CDATA value for (i++; i < xmlData.length; i++) { if (xmlData[i] === '<') { if (xmlData[i + 1] === '!') { //comment or CADATA i++; i = readCommentAndCDATA(xmlData, i); continue; } else if (xmlData[i+1] === '?') { i = readPI(xmlData, ++i); if (i.err) return i; } else{ break; } } else if (xmlData[i] === '&') { const afterAmp = validateAmpersand(xmlData, i); if (afterAmp == -1) return getErrorObject('InvalidChar', "char '&' is not expected.", getLineNumberForPosition(xmlData, i)); i = afterAmp; }else{ if (reachedRoot === true && !isWhiteSpace(xmlData[i])) { return getErrorObject('InvalidXml', "Extra text at the end", getLineNumberForPosition(xmlData, i)); } } } //end of reading tag text value if (xmlData[i] === '<') { i--; } } } else { if ( isWhiteSpace(xmlData[i])) { continue; } return getErrorObject('InvalidChar', "char '"+xmlData[i]+"' is not expected.", getLineNumberForPosition(xmlData, i)); } } if (!tagFound) { return getErrorObject('InvalidXml', 'Start tag expected.', 1); }else if (tags.length == 1) { return getErrorObject('InvalidTag', "Unclosed tag '"+tags[0].tagName+"'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos)); }else if (tags.length > 0) { return getErrorObject('InvalidXml', "Invalid '"+ JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\r?\n/g, '')+ "' found.", {line: 1, col: 1}); } return true; }; function isWhiteSpace(char){ return char === ' ' || char === '\t' || char === '\n' || char === '\r'; } /** * Read Processing insstructions and skip * @param {*} xmlData * @param {*} i */ function readPI(xmlData, i) { const start = i; for (; i < xmlData.length; i++) { if (xmlData[i] == '?' || xmlData[i] == ' ') { //tagname const tagname = xmlData.substr(start, i - start); if (i > 5 && tagname === 'xml') { return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i)); } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') { //check if valid attribut string i++; break; } else { continue; } } } return i; } function readCommentAndCDATA(xmlData, i) { if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') { //comment for (i += 3; i < xmlData.length; i++) { if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') { i += 2; break; } } } else if ( xmlData.length > i + 8 && xmlData[i + 1] === 'D' && xmlData[i + 2] === 'O' && xmlData[i + 3] === 'C' && xmlData[i + 4] === 'T' && xmlData[i + 5] === 'Y' && xmlData[i + 6] === 'P' && xmlData[i + 7] === 'E' ) { let angleBracketsCount = 1; for (i += 8; i < xmlData.length; i++) { if (xmlData[i] === '<') { angleBracketsCount++; } else if (xmlData[i] === '>') { angleBracketsCount--; if (angleBracketsCount === 0) { break; } } } } else if ( xmlData.length > i + 9 && xmlData[i + 1] === '[' && xmlData[i + 2] === 'C' && xmlData[i + 3] === 'D' && xmlData[i + 4] === 'A' && xmlData[i + 5] === 'T' && xmlData[i + 6] === 'A' && xmlData[i + 7] === '[' ) { for (i += 8; i < xmlData.length; i++) { if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') { i += 2; break; } } } return i; } const doubleQuote = '"'; const singleQuote = "'"; /** * Keep reading xmlData until '<' is found outside the attribute value. * @param {string} xmlData * @param {number} i */ function readAttributeStr(xmlData, i) { let attrStr = ''; let startChar = ''; let tagClosed = false; for (; i < xmlData.length; i++) { if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) { if (startChar === '') { startChar = xmlData[i]; } else if (startChar !== xmlData[i]) { //if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa } else { startChar = ''; } } else if (xmlData[i] === '>') { if (startChar === '') { tagClosed = true; break; } } attrStr += xmlData[i]; } if (startChar !== '') { return false; } return { value: attrStr, index: i, tagClosed: tagClosed }; } /** * Select all the attributes whether valid or invalid. */ const validAttrStrRegxp = new RegExp('(\\s*)([^\\s=]+)(\\s*=)?(\\s*([\'"])(([\\s\\S])*?)\\5)?', 'g'); //attr, ="sd", a="amit's", a="sd"b="saf", ab cd="" function validateAttributeString(attrStr, options) { //console.log("start:"+attrStr+":end"); //if(attrStr.trim().length === 0) return true; //empty string const matches = util.getAllMatches(attrStr, validAttrStrRegxp); const attrNames = {}; for (let i = 0; i < matches.length; i++) { if (matches[i][1].length === 0) { //nospace before attribute name: a="sd"b="saf" return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' has no space in starting.", getPositionFromMatch(matches[i])) } else if (matches[i][3] !== undefined && matches[i][4] === undefined) { return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' is without value.", getPositionFromMatch(matches[i])); } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) { //independent attribute: ab return getErrorObject('InvalidAttr', "boolean attribute '"+matches[i][2]+"' is not allowed.", getPositionFromMatch(matches[i])); } /* else if(matches[i][6] === undefined){//attribute without value: ab= return { err: { code:"InvalidAttr",msg:"attribute " + matches[i][2] + " has no value assigned."}}; } */ const attrName = matches[i][2]; if (!validateAttrName(attrName)) { return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is an invalid name.", getPositionFromMatch(matches[i])); } if (!attrNames.hasOwnProperty(attrName)) { //check for duplicate attribute. attrNames[attrName] = 1; } else { return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is repeated.", getPositionFromMatch(matches[i])); } } return true; } function validateNumberAmpersand(xmlData, i) { let re = /\d/; if (xmlData[i] === 'x') { i++; re = /[\da-fA-F]/; } for (; i < xmlData.length; i++) { if (xmlData[i] === ';') return i; if (!xmlData[i].match(re)) break; } return -1; } function validateAmpersand(xmlData, i) { // https://www.w3.org/TR/xml/#dt-charref i++; if (xmlData[i] === ';') return -1; if (xmlData[i] === '#') { i++; return validateNumberAmpersand(xmlData, i); } let count = 0; for (; i < xmlData.length; i++, count++) { if (xmlData[i].match(/\w/) && count < 20) continue; if (xmlData[i] === ';') break; return -1; } return i; } function getErrorObject(code, message, lineNumber) { return { err: { code: code, msg: message, line: lineNumber.line || lineNumber, col: lineNumber.col, }, }; } function validateAttrName(attrName) { return util.isName(attrName); } // const startsWithXML = /^xml/i; function validateTagName(tagname) { return util.isName(tagname) /* && !tagname.match(startsWithXML) */; } //this function returns the line number for the character at the given index function getLineNumberForPosition(xmlData, index) { const lines = xmlData.substring(0, index).split(/\r?\n/); return { line: lines.length, // column number is last line's length + 1, because column numbering starts at 1: col: lines[lines.length - 1].length + 1 }; } //this function returns the position of the first character of match within attrStr function getPositionFromMatch(match) { return match.startIndex + match[1].length; } /***/ }), /***/ 659: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; //parse Empty Node as self closing node const buildFromOrderedJs = __nccwpck_require__(6378); const getIgnoreAttributesFn = __nccwpck_require__(812) const defaultOptions = { attributeNamePrefix: '@_', attributesGroupName: false, textNodeName: '#text', ignoreAttributes: true, cdataPropName: false, format: false, indentBy: ' ', suppressEmptyNode: false, suppressUnpairedNode: true, suppressBooleanAttributes: true, tagValueProcessor: function(key, a) { return a; }, attributeValueProcessor: function(attrName, a) { return a; }, preserveOrder: false, commentPropName: false, unpairedTags: [], entities: [ { regex: new RegExp("&", "g"), val: "&" },//it must be on top { regex: new RegExp(">", "g"), val: ">" }, { regex: new RegExp("<", "g"), val: "<" }, { regex: new RegExp("\'", "g"), val: "'" }, { regex: new RegExp("\"", "g"), val: """ } ], processEntities: true, stopNodes: [], // transformTagName: false, // transformAttributeName: false, oneListGroup: false }; function Builder(options) { this.options = Object.assign({}, defaultOptions, options); if (this.options.ignoreAttributes === true || this.options.attributesGroupName) { this.isAttribute = function(/*a*/) { return false; }; } else { this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes) this.attrPrefixLen = this.options.attributeNamePrefix.length; this.isAttribute = isAttribute; } this.processTextOrObjNode = processTextOrObjNode if (this.options.format) { this.indentate = indentate; this.tagEndChar = '>\n'; this.newLine = '\n'; } else { this.indentate = function() { return ''; }; this.tagEndChar = '>'; this.newLine = ''; } } Builder.prototype.build = function(jObj) { if(this.options.preserveOrder){ return buildFromOrderedJs(jObj, this.options); }else { if(Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1){ jObj = { [this.options.arrayNodeName] : jObj } } return this.j2x(jObj, 0, []).val; } }; Builder.prototype.j2x = function(jObj, level, ajPath) { let attrStr = ''; let val = ''; const jPath = ajPath.join('.') for (let key in jObj) { if(!Object.prototype.hasOwnProperty.call(jObj, key)) continue; if (typeof jObj[key] === 'undefined') { // supress undefined node only if it is not an attribute if (this.isAttribute(key)) { val += ''; } } else if (jObj[key] === null) { // null attribute should be ignored by the attribute list, but should not cause the tag closing if (this.isAttribute(key)) { val += ''; } else if (key === this.options.cdataPropName) { val += ''; } else if (key[0] === '?') { val += this.indentate(level) + '<' + key + '?' + this.tagEndChar; } else { val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; } // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; } else if (jObj[key] instanceof Date) { val += this.buildTextValNode(jObj[key], key, '', level); } else if (typeof jObj[key] !== 'object') { //premitive type const attr = this.isAttribute(key); if (attr && !this.ignoreAttributesFn(attr, jPath)) { attrStr += this.buildAttrPairStr(attr, '' + jObj[key]); } else if (!attr) { //tag value if (key === this.options.textNodeName) { let newval = this.options.tagValueProcessor(key, '' + jObj[key]); val += this.replaceEntitiesValue(newval); } else { val += this.buildTextValNode(jObj[key], key, '', level); } } } else if (Array.isArray(jObj[key])) { //repeated nodes const arrLen = jObj[key].length; let listTagVal = ""; let listTagAttr = ""; for (let j = 0; j < arrLen; j++) { const item = jObj[key][j]; if (typeof item === 'undefined') { // supress undefined node } else if (item === null) { if(key[0] === "?") val += this.indentate(level) + '<' + key + '?' + this.tagEndChar; else val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; } else if (typeof item === 'object') { if(this.options.oneListGroup){ const result = this.j2x(item, level + 1, ajPath.concat(key)); listTagVal += result.val; if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) { listTagAttr += result.attrStr } }else{ listTagVal += this.processTextOrObjNode(item, key, level, ajPath) } } else { if (this.options.oneListGroup) { let textValue = this.options.tagValueProcessor(key, item); textValue = this.replaceEntitiesValue(textValue); listTagVal += textValue; } else { listTagVal += this.buildTextValNode(item, key, '', level); } } } if(this.options.oneListGroup){ listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level); } val += listTagVal; } else { //nested node if (this.options.attributesGroupName && key === this.options.attributesGroupName) { const Ks = Object.keys(jObj[key]); const L = Ks.length; for (let j = 0; j < L; j++) { attrStr += this.buildAttrPairStr(Ks[j], '' + jObj[key][Ks[j]]); } } else { val += this.processTextOrObjNode(jObj[key], key, level, ajPath) } } } return {attrStr: attrStr, val: val}; }; Builder.prototype.buildAttrPairStr = function(attrName, val){ val = this.options.attributeValueProcessor(attrName, '' + val); val = this.replaceEntitiesValue(val); if (this.options.suppressBooleanAttributes && val === "true") { return ' ' + attrName; } else return ' ' + attrName + '="' + val + '"'; } function processTextOrObjNode (object, key, level, ajPath) { const result = this.j2x(object, level + 1, ajPath.concat(key)); if (object[this.options.textNodeName] !== undefined && Object.keys(object).length === 1) { return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level); } else { return this.buildObjectNode(result.val, key, result.attrStr, level); } } Builder.prototype.buildObjectNode = function(val, key, attrStr, level) { if(val === ""){ if(key[0] === "?") return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar; else { return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar; } }else{ let tagEndExp = '' + val + tagEndExp ); } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) { return this.indentate(level) + `` + this.newLine; }else { return ( this.indentate(level) + '<' + key + attrStr + piClosingChar + this.tagEndChar + val + this.indentate(level) + tagEndExp ); } } } Builder.prototype.closeTag = function(key){ let closeTag = ""; if(this.options.unpairedTags.indexOf(key) !== -1){ //unpaired if(!this.options.suppressUnpairedNode) closeTag = "/" }else if(this.options.suppressEmptyNode){ //empty closeTag = "/"; }else{ closeTag = `>` + this.newLine; }else if (this.options.commentPropName !== false && key === this.options.commentPropName) { return this.indentate(level) + `` + this.newLine; }else if(key[0] === "?") {//PI tag return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar; }else{ let textValue = this.options.tagValueProcessor(key, val); textValue = this.replaceEntitiesValue(textValue); if( textValue === ''){ return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar; }else{ return this.indentate(level) + '<' + key + attrStr + '>' + textValue + ' 0 && this.options.processEntities){ for (let i=0; i { const EOL = "\n"; /** * * @param {array} jArray * @param {any} options * @returns */ function toXml(jArray, options) { let indentation = ""; if (options.format && options.indentBy.length > 0) { indentation = EOL; } return arrToStr(jArray, options, "", indentation); } function arrToStr(arr, options, jPath, indentation) { let xmlStr = ""; let isPreviousElementTag = false; for (let i = 0; i < arr.length; i++) { const tagObj = arr[i]; const tagName = propName(tagObj); if(tagName === undefined) continue; let newJPath = ""; if (jPath.length === 0) newJPath = tagName else newJPath = `${jPath}.${tagName}`; if (tagName === options.textNodeName) { let tagText = tagObj[tagName]; if (!isStopNode(newJPath, options)) { tagText = options.tagValueProcessor(tagName, tagText); tagText = replaceEntitiesValue(tagText, options); } if (isPreviousElementTag) { xmlStr += indentation; } xmlStr += tagText; isPreviousElementTag = false; continue; } else if (tagName === options.cdataPropName) { if (isPreviousElementTag) { xmlStr += indentation; } xmlStr += ``; isPreviousElementTag = false; continue; } else if (tagName === options.commentPropName) { xmlStr += indentation + ``; isPreviousElementTag = true; continue; } else if (tagName[0] === "?") { const attStr = attr_to_str(tagObj[":@"], options); const tempInd = tagName === "?xml" ? "" : indentation; let piTextNodeName = tagObj[tagName][0][options.textNodeName]; piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : ""; //remove extra spacing xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr}?>`; isPreviousElementTag = true; continue; } let newIdentation = indentation; if (newIdentation !== "") { newIdentation += options.indentBy; } const attStr = attr_to_str(tagObj[":@"], options); const tagStart = indentation + `<${tagName}${attStr}`; const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation); if (options.unpairedTags.indexOf(tagName) !== -1) { if (options.suppressUnpairedNode) xmlStr += tagStart + ">"; else xmlStr += tagStart + "/>"; } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) { xmlStr += tagStart + "/>"; } else if (tagValue && tagValue.endsWith(">")) { xmlStr += tagStart + `>${tagValue}${indentation}`; } else { xmlStr += tagStart + ">"; if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes("`; } isPreviousElementTag = true; } return xmlStr; } function propName(obj) { const keys = Object.keys(obj); for (let i = 0; i < keys.length; i++) { const key = keys[i]; if(!obj.hasOwnProperty(key)) continue; if (key !== ":@") return key; } } function attr_to_str(attrMap, options) { let attrStr = ""; if (attrMap && !options.ignoreAttributes) { for (let attr in attrMap) { if(!attrMap.hasOwnProperty(attr)) continue; let attrVal = options.attributeValueProcessor(attr, attrMap[attr]); attrVal = replaceEntitiesValue(attrVal, options); if (attrVal === true && options.suppressBooleanAttributes) { attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`; } else { attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`; } } } return attrStr; } function isStopNode(jPath, options) { jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1); let tagName = jPath.substr(jPath.lastIndexOf(".") + 1); for (let index in options.stopNodes) { if (options.stopNodes[index] === jPath || options.stopNodes[index] === "*." + tagName) return true; } return false; } function replaceEntitiesValue(textValue, options) { if (textValue && textValue.length > 0 && options.processEntities) { for (let i = 0; i < options.entities.length; i++) { const entity = options.entities[i]; textValue = textValue.replace(entity.regex, entity.val); } } return textValue; } module.exports = toXml; /***/ }), /***/ 151: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const util = __nccwpck_require__(7019); //TODO: handle comments function readDocType(xmlData, i){ const entities = {}; if( xmlData[i + 3] === 'O' && xmlData[i + 4] === 'C' && xmlData[i + 5] === 'T' && xmlData[i + 6] === 'Y' && xmlData[i + 7] === 'P' && xmlData[i + 8] === 'E') { i = i+9; let angleBracketsCount = 1; let hasBody = false, comment = false; let exp = ""; for(;i') { //Read tag content if(comment){ if( xmlData[i - 1] === "-" && xmlData[i - 2] === "-"){ comment = false; angleBracketsCount--; } }else{ angleBracketsCount--; } if (angleBracketsCount === 0) { break; } }else if( xmlData[i] === '['){ hasBody = true; }else{ exp += xmlData[i]; } } if(angleBracketsCount !== 0){ throw new Error(`Unclosed DOCTYPE`); } }else{ throw new Error(`Invalid Tag instead of DOCTYPE`); } return {entities, i}; } function readEntityExp(xmlData,i){ //External entities are not supported // //Parameter entities are not supported // //Internal entities are supported // //read EntityName let entityName = ""; for (; i < xmlData.length && (xmlData[i] !== "'" && xmlData[i] !== '"' ); i++) { // if(xmlData[i] === " ") continue; // else entityName += xmlData[i]; } entityName = entityName.trim(); if(entityName.indexOf(" ") !== -1) throw new Error("External entites are not supported"); //read Entity Value const startChar = xmlData[i++]; let val = "" for (; i < xmlData.length && xmlData[i] !== startChar ; i++) { val += xmlData[i]; } return [entityName, val, i]; } function isComment(xmlData, i){ if(xmlData[i+1] === '!' && xmlData[i+2] === '-' && xmlData[i+3] === '-') return true return false } function isEntity(xmlData, i){ if(xmlData[i+1] === '!' && xmlData[i+2] === 'E' && xmlData[i+3] === 'N' && xmlData[i+4] === 'T' && xmlData[i+5] === 'I' && xmlData[i+6] === 'T' && xmlData[i+7] === 'Y') return true return false } function isElement(xmlData, i){ if(xmlData[i+1] === '!' && xmlData[i+2] === 'E' && xmlData[i+3] === 'L' && xmlData[i+4] === 'E' && xmlData[i+5] === 'M' && xmlData[i+6] === 'E' && xmlData[i+7] === 'N' && xmlData[i+8] === 'T') return true return false } function isAttlist(xmlData, i){ if(xmlData[i+1] === '!' && xmlData[i+2] === 'A' && xmlData[i+3] === 'T' && xmlData[i+4] === 'T' && xmlData[i+5] === 'L' && xmlData[i+6] === 'I' && xmlData[i+7] === 'S' && xmlData[i+8] === 'T') return true return false } function isNotation(xmlData, i){ if(xmlData[i+1] === '!' && xmlData[i+2] === 'N' && xmlData[i+3] === 'O' && xmlData[i+4] === 'T' && xmlData[i+5] === 'A' && xmlData[i+6] === 'T' && xmlData[i+7] === 'I' && xmlData[i+8] === 'O' && xmlData[i+9] === 'N') return true return false } function validateEntityName(name){ if (util.isName(name)) return name; else throw new Error(`Invalid entity name ${name}`); } module.exports = readDocType; /***/ }), /***/ 4769: /***/ ((__unused_webpack_module, exports) => { const defaultOptions = { preserveOrder: false, attributeNamePrefix: '@_', attributesGroupName: false, textNodeName: '#text', ignoreAttributes: true, removeNSPrefix: false, // remove NS from tag name or attribute name if true allowBooleanAttributes: false, //a tag can have attributes without any value //ignoreRootElement : false, parseTagValue: true, parseAttributeValue: false, trimValues: true, //Trim string values of tag and attributes cdataPropName: false, numberParseOptions: { hex: true, leadingZeros: true, eNotation: true }, tagValueProcessor: function(tagName, val) { return val; }, attributeValueProcessor: function(attrName, val) { return val; }, stopNodes: [], //nested tags will not be parsed even for errors alwaysCreateTextNode: false, isArray: () => false, commentPropName: false, unpairedTags: [], processEntities: true, htmlEntities: false, ignoreDeclaration: false, ignorePiTags: false, transformTagName: false, transformAttributeName: false, updateTag: function(tagName, jPath, attrs){ return tagName }, // skipEmptyListItem: false }; const buildOptions = function(options) { return Object.assign({}, defaultOptions, options); }; exports.buildOptions = buildOptions; exports.defaultOptions = defaultOptions; /***/ }), /***/ 3017: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; ///@ts-check const util = __nccwpck_require__(7019); const xmlNode = __nccwpck_require__(9307); const readDocType = __nccwpck_require__(151); const toNumber = __nccwpck_require__(6496); const getIgnoreAttributesFn = __nccwpck_require__(812) // const regx = // '<((!\\[CDATA\\[([\\s\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\/)(NAME)\\s*>))([^<]*)' // .replace(/NAME/g, util.nameRegexp); //const tagsRegx = new RegExp("<(\\/?[\\w:\\-\._]+)([^>]*)>(\\s*"+cdataRegx+")*([^<]+)?","g"); //const tagsRegx = new RegExp("<(\\/?)((\\w*:)?([\\w:\\-\._]+))([^>]*)>([^<]*)("+cdataRegx+"([^<]*))*([^<]+)?","g"); class OrderedObjParser{ constructor(options){ this.options = options; this.currentNode = null; this.tagsNodeStack = []; this.docTypeEntities = {}; this.lastEntities = { "apos" : { regex: /&(apos|#39|#x27);/g, val : "'"}, "gt" : { regex: /&(gt|#62|#x3E);/g, val : ">"}, "lt" : { regex: /&(lt|#60|#x3C);/g, val : "<"}, "quot" : { regex: /&(quot|#34|#x22);/g, val : "\""}, }; this.ampEntity = { regex: /&(amp|#38|#x26);/g, val : "&"}; this.htmlEntities = { "space": { regex: /&(nbsp|#160);/g, val: " " }, // "lt" : { regex: /&(lt|#60);/g, val: "<" }, // "gt" : { regex: /&(gt|#62);/g, val: ">" }, // "amp" : { regex: /&(amp|#38);/g, val: "&" }, // "quot" : { regex: /&(quot|#34);/g, val: "\"" }, // "apos" : { regex: /&(apos|#39);/g, val: "'" }, "cent" : { regex: /&(cent|#162);/g, val: "¢" }, "pound" : { regex: /&(pound|#163);/g, val: "£" }, "yen" : { regex: /&(yen|#165);/g, val: "¥" }, "euro" : { regex: /&(euro|#8364);/g, val: "€" }, "copyright" : { regex: /&(copy|#169);/g, val: "©" }, "reg" : { regex: /&(reg|#174);/g, val: "®" }, "inr" : { regex: /&(inr|#8377);/g, val: "₹" }, "num_dec": { regex: /&#([0-9]{1,7});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 10)) }, "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 16)) }, }; this.addExternalEntities = addExternalEntities; this.parseXml = parseXml; this.parseTextData = parseTextData; this.resolveNameSpace = resolveNameSpace; this.buildAttributesMap = buildAttributesMap; this.isItStopNode = isItStopNode; this.replaceEntitiesValue = replaceEntitiesValue; this.readStopNodeData = readStopNodeData; this.saveTextToParentTag = saveTextToParentTag; this.addChild = addChild; this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes) } } function addExternalEntities(externalEntities){ const entKeys = Object.keys(externalEntities); for (let i = 0; i < entKeys.length; i++) { const ent = entKeys[i]; this.lastEntities[ent] = { regex: new RegExp("&"+ent+";","g"), val : externalEntities[ent] } } } /** * @param {string} val * @param {string} tagName * @param {string} jPath * @param {boolean} dontTrim * @param {boolean} hasAttributes * @param {boolean} isLeafNode * @param {boolean} escapeEntities */ function parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) { if (val !== undefined) { if (this.options.trimValues && !dontTrim) { val = val.trim(); } if(val.length > 0){ if(!escapeEntities) val = this.replaceEntitiesValue(val); const newval = this.options.tagValueProcessor(tagName, val, jPath, hasAttributes, isLeafNode); if(newval === null || newval === undefined){ //don't parse return val; }else if(typeof newval !== typeof val || newval !== val){ //overwrite return newval; }else if(this.options.trimValues){ return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions); }else{ const trimmedVal = val.trim(); if(trimmedVal === val){ return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions); }else{ return val; } } } } } function resolveNameSpace(tagname) { if (this.options.removeNSPrefix) { const tags = tagname.split(':'); const prefix = tagname.charAt(0) === '/' ? '/' : ''; if (tags[0] === 'xmlns') { return ''; } if (tags.length === 2) { tagname = prefix + tags[1]; } } return tagname; } //TODO: change regex to capture NS //const attrsRegx = new RegExp("([\\w\\-\\.\\:]+)\\s*=\\s*(['\"])((.|\n)*?)\\2","gm"); const attrsRegx = new RegExp('([^\\s=]+)\\s*(=\\s*([\'"])([\\s\\S]*?)\\3)?', 'gm'); function buildAttributesMap(attrStr, jPath, tagName) { if (this.options.ignoreAttributes !== true && typeof attrStr === 'string') { // attrStr = attrStr.replace(/\r?\n/g, ' '); //attrStr = attrStr || attrStr.trim(); const matches = util.getAllMatches(attrStr, attrsRegx); const len = matches.length; //don't make it inline const attrs = {}; for (let i = 0; i < len; i++) { const attrName = this.resolveNameSpace(matches[i][1]); if (this.ignoreAttributesFn(attrName, jPath)) { continue } let oldVal = matches[i][4]; let aName = this.options.attributeNamePrefix + attrName; if (attrName.length) { if (this.options.transformAttributeName) { aName = this.options.transformAttributeName(aName); } if(aName === "__proto__") aName = "#__proto__"; if (oldVal !== undefined) { if (this.options.trimValues) { oldVal = oldVal.trim(); } oldVal = this.replaceEntitiesValue(oldVal); const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath); if(newVal === null || newVal === undefined){ //don't parse attrs[aName] = oldVal; }else if(typeof newVal !== typeof oldVal || newVal !== oldVal){ //overwrite attrs[aName] = newVal; }else{ //parse attrs[aName] = parseValue( oldVal, this.options.parseAttributeValue, this.options.numberParseOptions ); } } else if (this.options.allowBooleanAttributes) { attrs[aName] = true; } } } if (!Object.keys(attrs).length) { return; } if (this.options.attributesGroupName) { const attrCollection = {}; attrCollection[this.options.attributesGroupName] = attrs; return attrCollection; } return attrs } } const parseXml = function(xmlData) { xmlData = xmlData.replace(/\r\n?/g, "\n"); //TODO: remove this line const xmlObj = new xmlNode('!xml'); let currentNode = xmlObj; let textData = ""; let jPath = ""; for(let i=0; i< xmlData.length; i++){//for each char in XML data const ch = xmlData[i]; if(ch === '<'){ // const nextIndex = i+1; // const _2ndChar = xmlData[nextIndex]; if( xmlData[i+1] === '/') {//Closing Tag const closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed.") let tagName = xmlData.substring(i+2,closeIndex).trim(); if(this.options.removeNSPrefix){ const colonIndex = tagName.indexOf(":"); if(colonIndex !== -1){ tagName = tagName.substr(colonIndex+1); } } if(this.options.transformTagName) { tagName = this.options.transformTagName(tagName); } if(currentNode){ textData = this.saveTextToParentTag(textData, currentNode, jPath); } //check if last tag of nested tag was unpaired tag const lastTagName = jPath.substring(jPath.lastIndexOf(".")+1); if(tagName && this.options.unpairedTags.indexOf(tagName) !== -1 ){ throw new Error(`Unpaired tag can not be used as closing tag: `); } let propIndex = 0 if(lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1 ){ propIndex = jPath.lastIndexOf('.', jPath.lastIndexOf('.')-1) this.tagsNodeStack.pop(); }else{ propIndex = jPath.lastIndexOf("."); } jPath = jPath.substring(0, propIndex); currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope textData = ""; i = closeIndex; } else if( xmlData[i+1] === '?') { let tagData = readTagExp(xmlData,i, false, "?>"); if(!tagData) throw new Error("Pi Tag is not closed."); textData = this.saveTextToParentTag(textData, currentNode, jPath); if( (this.options.ignoreDeclaration && tagData.tagName === "?xml") || this.options.ignorePiTags){ }else{ const childNode = new xmlNode(tagData.tagName); childNode.add(this.options.textNodeName, ""); if(tagData.tagName !== tagData.tagExp && tagData.attrExpPresent){ childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName); } this.addChild(currentNode, childNode, jPath) } i = tagData.closeIndex + 1; } else if(xmlData.substr(i + 1, 3) === '!--') { const endIndex = findClosingIndex(xmlData, "-->", i+4, "Comment is not closed.") if(this.options.commentPropName){ const comment = xmlData.substring(i + 4, endIndex - 2); textData = this.saveTextToParentTag(textData, currentNode, jPath); currentNode.add(this.options.commentPropName, [ { [this.options.textNodeName] : comment } ]); } i = endIndex; } else if( xmlData.substr(i + 1, 2) === '!D') { const result = readDocType(xmlData, i); this.docTypeEntities = result.entities; i = result.i; }else if(xmlData.substr(i + 1, 2) === '![') { const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2; const tagExp = xmlData.substring(i + 9,closeIndex); textData = this.saveTextToParentTag(textData, currentNode, jPath); let val = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true); if(val == undefined) val = ""; //cdata should be set even if it is 0 length string if(this.options.cdataPropName){ currentNode.add(this.options.cdataPropName, [ { [this.options.textNodeName] : tagExp } ]); }else{ currentNode.add(this.options.textNodeName, val); } i = closeIndex + 2; }else {//Opening tag let result = readTagExp(xmlData,i, this.options.removeNSPrefix); let tagName= result.tagName; const rawTagName = result.rawTagName; let tagExp = result.tagExp; let attrExpPresent = result.attrExpPresent; let closeIndex = result.closeIndex; if (this.options.transformTagName) { tagName = this.options.transformTagName(tagName); } //save text as child node if (currentNode && textData) { if(currentNode.tagname !== '!xml'){ //when nested tag is found textData = this.saveTextToParentTag(textData, currentNode, jPath, false); } } //check if last tag was unpaired tag const lastTag = currentNode; if(lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1 ){ currentNode = this.tagsNodeStack.pop(); jPath = jPath.substring(0, jPath.lastIndexOf(".")); } if(tagName !== xmlObj.tagname){ jPath += jPath ? "." + tagName : tagName; } if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) { let tagContent = ""; //self-closing tag if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){ if(tagName[tagName.length - 1] === "/"){ //remove trailing '/' tagName = tagName.substr(0, tagName.length - 1); jPath = jPath.substr(0, jPath.length - 1); tagExp = tagName; }else{ tagExp = tagExp.substr(0, tagExp.length - 1); } i = result.closeIndex; } //unpaired tag else if(this.options.unpairedTags.indexOf(tagName) !== -1){ i = result.closeIndex; } //normal tag else{ //read until closing tag is found const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1); if(!result) throw new Error(`Unexpected end of ${rawTagName}`); i = result.i; tagContent = result.tagContent; } const childNode = new xmlNode(tagName); if(tagName !== tagExp && attrExpPresent){ childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); } if(tagContent) { tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true); } jPath = jPath.substr(0, jPath.lastIndexOf(".")); childNode.add(this.options.textNodeName, tagContent); this.addChild(currentNode, childNode, jPath) }else{ //selfClosing tag if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){ if(tagName[tagName.length - 1] === "/"){ //remove trailing '/' tagName = tagName.substr(0, tagName.length - 1); jPath = jPath.substr(0, jPath.length - 1); tagExp = tagName; }else{ tagExp = tagExp.substr(0, tagExp.length - 1); } if(this.options.transformTagName) { tagName = this.options.transformTagName(tagName); } const childNode = new xmlNode(tagName); if(tagName !== tagExp && attrExpPresent){ childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); } this.addChild(currentNode, childNode, jPath) jPath = jPath.substr(0, jPath.lastIndexOf(".")); } //opening tag else{ const childNode = new xmlNode( tagName); this.tagsNodeStack.push(currentNode); if(tagName !== tagExp && attrExpPresent){ childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); } this.addChild(currentNode, childNode, jPath) currentNode = childNode; } textData = ""; i = closeIndex; } } }else{ textData += xmlData[i]; } } return xmlObj.child; } function addChild(currentNode, childNode, jPath){ const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"]) if(result === false){ }else if(typeof result === "string"){ childNode.tagname = result currentNode.addChild(childNode); }else{ currentNode.addChild(childNode); } } const replaceEntitiesValue = function(val){ if(this.options.processEntities){ for(let entityName in this.docTypeEntities){ const entity = this.docTypeEntities[entityName]; val = val.replace( entity.regx, entity.val); } for(let entityName in this.lastEntities){ const entity = this.lastEntities[entityName]; val = val.replace( entity.regex, entity.val); } if(this.options.htmlEntities){ for(let entityName in this.htmlEntities){ const entity = this.htmlEntities[entityName]; val = val.replace( entity.regex, entity.val); } } val = val.replace( this.ampEntity.regex, this.ampEntity.val); } return val; } function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) { if (textData) { //store previously collected data as textNode if(isLeafNode === undefined) isLeafNode = currentNode.child.length === 0 textData = this.parseTextData(textData, currentNode.tagname, jPath, false, currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : false, isLeafNode); if (textData !== undefined && textData !== "") currentNode.add(this.options.textNodeName, textData); textData = ""; } return textData; } //TODO: use jPath to simplify the logic /** * * @param {string[]} stopNodes * @param {string} jPath * @param {string} currentTagName */ function isItStopNode(stopNodes, jPath, currentTagName){ const allNodesExp = "*." + currentTagName; for (const stopNodePath in stopNodes) { const stopNodeExp = stopNodes[stopNodePath]; if( allNodesExp === stopNodeExp || jPath === stopNodeExp ) return true; } return false; } /** * Returns the tag Expression and where it is ending handling single-double quotes situation * @param {string} xmlData * @param {number} i starting index * @returns */ function tagExpWithClosingIndex(xmlData, i, closingChar = ">"){ let attrBoundary; let tagExp = ""; for (let index = i; index < xmlData.length; index++) { let ch = xmlData[index]; if (attrBoundary) { if (ch === attrBoundary) attrBoundary = "";//reset } else if (ch === '"' || ch === "'") { attrBoundary = ch; } else if (ch === closingChar[0]) { if(closingChar[1]){ if(xmlData[index + 1] === closingChar[1]){ return { data: tagExp, index: index } } }else{ return { data: tagExp, index: index } } } else if (ch === '\t') { ch = " " } tagExp += ch; } } function findClosingIndex(xmlData, str, i, errMsg){ const closingIndex = xmlData.indexOf(str, i); if(closingIndex === -1){ throw new Error(errMsg) }else{ return closingIndex + str.length - 1; } } function readTagExp(xmlData,i, removeNSPrefix, closingChar = ">"){ const result = tagExpWithClosingIndex(xmlData, i+1, closingChar); if(!result) return; let tagExp = result.data; const closeIndex = result.index; const separatorIndex = tagExp.search(/\s/); let tagName = tagExp; let attrExpPresent = true; if(separatorIndex !== -1){//separate tag name and attributes expression tagName = tagExp.substring(0, separatorIndex); tagExp = tagExp.substring(separatorIndex + 1).trimStart(); } const rawTagName = tagName; if(removeNSPrefix){ const colonIndex = tagName.indexOf(":"); if(colonIndex !== -1){ tagName = tagName.substr(colonIndex+1); attrExpPresent = tagName !== result.data.substr(colonIndex + 1); } } return { tagName: tagName, tagExp: tagExp, closeIndex: closeIndex, attrExpPresent: attrExpPresent, rawTagName: rawTagName, } } /** * find paired tag for a stop node * @param {string} xmlData * @param {string} tagName * @param {number} i */ function readStopNodeData(xmlData, tagName, i){ const startIndex = i; // Starting at 1 since we already have an open tag let openTagCount = 1; for (; i < xmlData.length; i++) { if( xmlData[i] === "<"){ if (xmlData[i+1] === "/") {//close tag const closeIndex = findClosingIndex(xmlData, ">", i, `${tagName} is not closed`); let closeTagName = xmlData.substring(i+2,closeIndex).trim(); if(closeTagName === tagName){ openTagCount--; if (openTagCount === 0) { return { tagContent: xmlData.substring(startIndex, i), i : closeIndex } } } i=closeIndex; } else if(xmlData[i+1] === '?') { const closeIndex = findClosingIndex(xmlData, "?>", i+1, "StopNode is not closed.") i=closeIndex; } else if(xmlData.substr(i + 1, 3) === '!--') { const closeIndex = findClosingIndex(xmlData, "-->", i+3, "StopNode is not closed.") i=closeIndex; } else if(xmlData.substr(i + 1, 2) === '![') { const closeIndex = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2; i=closeIndex; } else { const tagData = readTagExp(xmlData, i, '>') if (tagData) { const openTagName = tagData && tagData.tagName; if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length-1] !== "/") { openTagCount++; } i=tagData.closeIndex; } } } }//end for loop } function parseValue(val, shouldParse, options) { if (shouldParse && typeof val === 'string') { //console.log(options) const newval = val.trim(); if(newval === 'true' ) return true; else if(newval === 'false' ) return false; else return toNumber(val, options); } else { if (util.isExist(val)) { return val; } else { return ''; } } } module.exports = OrderedObjParser; /***/ }), /***/ 9844: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { buildOptions} = __nccwpck_require__(4769); const OrderedObjParser = __nccwpck_require__(3017); const { prettify} = __nccwpck_require__(7594); const validator = __nccwpck_require__(9433); class XMLParser{ constructor(options){ this.externalEntities = {}; this.options = buildOptions(options); } /** * Parse XML dats to JS object * @param {string|Buffer} xmlData * @param {boolean|Object} validationOption */ parse(xmlData,validationOption){ if(typeof xmlData === "string"){ }else if( xmlData.toString){ xmlData = xmlData.toString(); }else{ throw new Error("XML data is accepted in String or Bytes[] form.") } if( validationOption){ if(validationOption === true) validationOption = {}; //validate with default options const result = validator.validate(xmlData, validationOption); if (result !== true) { throw Error( `${result.err.msg}:${result.err.line}:${result.err.col}` ) } } const orderedObjParser = new OrderedObjParser(this.options); orderedObjParser.addExternalEntities(this.externalEntities); const orderedResult = orderedObjParser.parseXml(xmlData); if(this.options.preserveOrder || orderedResult === undefined) return orderedResult; else return prettify(orderedResult, this.options); } /** * Add Entity which is not by default supported by this library * @param {string} key * @param {string} value */ addEntity(key, value){ if(value.indexOf("&") !== -1){ throw new Error("Entity value can't have '&'") }else if(key.indexOf("&") !== -1 || key.indexOf(";") !== -1){ throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for ' '") }else if(value === "&"){ throw new Error("An entity with value '&' is not permitted"); }else{ this.externalEntities[key] = value; } } } module.exports = XMLParser; /***/ }), /***/ 7594: /***/ ((__unused_webpack_module, exports) => { "use strict"; /** * * @param {array} node * @param {any} options * @returns */ function prettify(node, options){ return compress( node, options); } /** * * @param {array} arr * @param {object} options * @param {string} jPath * @returns object */ function compress(arr, options, jPath){ let text; const compressedObj = {}; for (let i = 0; i < arr.length; i++) { const tagObj = arr[i]; const property = propName(tagObj); let newJpath = ""; if(jPath === undefined) newJpath = property; else newJpath = jPath + "." + property; if(property === options.textNodeName){ if(text === undefined) text = tagObj[property]; else text += "" + tagObj[property]; }else if(property === undefined){ continue; }else if(tagObj[property]){ let val = compress(tagObj[property], options, newJpath); const isLeaf = isLeafTag(val, options); if(tagObj[":@"]){ assignAttributes( val, tagObj[":@"], newJpath, options); }else if(Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode){ val = val[options.textNodeName]; }else if(Object.keys(val).length === 0){ if(options.alwaysCreateTextNode) val[options.textNodeName] = ""; else val = ""; } if(compressedObj[property] !== undefined && compressedObj.hasOwnProperty(property)) { if(!Array.isArray(compressedObj[property])) { compressedObj[property] = [ compressedObj[property] ]; } compressedObj[property].push(val); }else{ //TODO: if a node is not an array, then check if it should be an array //also determine if it is a leaf node if (options.isArray(property, newJpath, isLeaf )) { compressedObj[property] = [val]; }else{ compressedObj[property] = val; } } } } // if(text && text.length > 0) compressedObj[options.textNodeName] = text; if(typeof text === "string"){ if(text.length > 0) compressedObj[options.textNodeName] = text; }else if(text !== undefined) compressedObj[options.textNodeName] = text; return compressedObj; } function propName(obj){ const keys = Object.keys(obj); for (let i = 0; i < keys.length; i++) { const key = keys[i]; if(key !== ":@") return key; } } function assignAttributes(obj, attrMap, jpath, options){ if (attrMap) { const keys = Object.keys(attrMap); const len = keys.length; //don't make it inline for (let i = 0; i < len; i++) { const atrrName = keys[i]; if (options.isArray(atrrName, jpath + "." + atrrName, true, true)) { obj[atrrName] = [ attrMap[atrrName] ]; } else { obj[atrrName] = attrMap[atrrName]; } } } } function isLeafTag(obj, options){ const { textNodeName } = options; const propCount = Object.keys(obj).length; if (propCount === 0) { return true; } if ( propCount === 1 && (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0) ) { return true; } return false; } exports.prettify = prettify; /***/ }), /***/ 9307: /***/ ((module) => { "use strict"; class XmlNode{ constructor(tagname) { this.tagname = tagname; this.child = []; //nested tags, text, cdata, comments in order this[":@"] = {}; //attributes map } add(key,val){ // this.child.push( {name : key, val: val, isCdata: isCdata }); if(key === "__proto__") key = "#__proto__"; this.child.push( {[key]: val }); } addChild(node) { if(node.tagname === "__proto__") node.tagname = "#__proto__"; if(node[":@"] && Object.keys(node[":@"]).length > 0){ this.child.push( { [node.tagname]: node.child, [":@"]: node[":@"] }); }else{ this.child.push( { [node.tagname]: node.child }); } }; }; module.exports = XmlNode; /***/ }), /***/ 7506: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright 2018 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; var _a; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GaxiosError = exports.GAXIOS_ERROR_SYMBOL = void 0; exports.defaultErrorRedactor = defaultErrorRedactor; const url_1 = __nccwpck_require__(7016); const util_1 = __nccwpck_require__(3155); const extend_1 = __importDefault(__nccwpck_require__(3860)); /** * Support `instanceof` operator for `GaxiosError`s in different versions of this library. * * @see {@link GaxiosError[Symbol.hasInstance]} */ exports.GAXIOS_ERROR_SYMBOL = Symbol.for(`${util_1.pkg.name}-gaxios-error`); /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ class GaxiosError extends Error { /** * Support `instanceof` operator for `GaxiosError` across builds/duplicated files. * * @see {@link GAXIOS_ERROR_SYMBOL} * @see {@link GaxiosError[GAXIOS_ERROR_SYMBOL]} */ static [(_a = exports.GAXIOS_ERROR_SYMBOL, Symbol.hasInstance)](instance) { if (instance && typeof instance === 'object' && exports.GAXIOS_ERROR_SYMBOL in instance && instance[exports.GAXIOS_ERROR_SYMBOL] === util_1.pkg.version) { return true; } // fallback to native return Function.prototype[Symbol.hasInstance].call(GaxiosError, instance); } constructor(message, config, response, error) { var _b; super(message); this.config = config; this.response = response; this.error = error; /** * Support `instanceof` operator for `GaxiosError` across builds/duplicated files. * * @see {@link GAXIOS_ERROR_SYMBOL} * @see {@link GaxiosError[Symbol.hasInstance]} * @see {@link https://github.com/microsoft/TypeScript/issues/13965#issuecomment-278570200} * @see {@link https://stackoverflow.com/questions/46618852/require-and-instanceof} * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/@@hasInstance#reverting_to_default_instanceof_behavior} */ this[_a] = util_1.pkg.version; // deep-copy config as we do not want to mutate // the existing config for future retries/use this.config = (0, extend_1.default)(true, {}, config); if (this.response) { this.response.config = (0, extend_1.default)(true, {}, this.response.config); } if (this.response) { try { this.response.data = translateData(this.config.responseType, (_b = this.response) === null || _b === void 0 ? void 0 : _b.data); } catch (_c) { // best effort - don't throw an error within an error // we could set `this.response.config.responseType = 'unknown'`, but // that would mutate future calls with this config object. } this.status = this.response.status; } if (error && 'code' in error && error.code) { this.code = error.code; } if (config.errorRedactor) { config.errorRedactor({ config: this.config, response: this.response, }); } } } exports.GaxiosError = GaxiosError; function translateData(responseType, data) { switch (responseType) { case 'stream': return data; case 'json': return JSON.parse(JSON.stringify(data)); case 'arraybuffer': return JSON.parse(Buffer.from(data).toString('utf8')); case 'blob': return JSON.parse(data.text()); default: return data; } } /** * An experimental error redactor. * * @param config Config to potentially redact properties of * @param response Config to potentially redact properties of * * @experimental */ function defaultErrorRedactor(data) { const REDACT = '< - See `errorRedactor` option in `gaxios` for configuration>.'; function redactHeaders(headers) { if (!headers) return; for (const key of Object.keys(headers)) { // any casing of `Authentication` if (/^authentication$/i.test(key)) { headers[key] = REDACT; } // any casing of `Authorization` if (/^authorization$/i.test(key)) { headers[key] = REDACT; } // anything containing secret, such as 'client secret' if (/secret/i.test(key)) { headers[key] = REDACT; } } } function redactString(obj, key) { if (typeof obj === 'object' && obj !== null && typeof obj[key] === 'string') { const text = obj[key]; if (/grant_type=/i.test(text) || /assertion=/i.test(text) || /secret/i.test(text)) { obj[key] = REDACT; } } } function redactObject(obj) { if (typeof obj === 'object' && obj !== null) { if ('grant_type' in obj) { obj['grant_type'] = REDACT; } if ('assertion' in obj) { obj['assertion'] = REDACT; } if ('client_secret' in obj) { obj['client_secret'] = REDACT; } } } if (data.config) { redactHeaders(data.config.headers); redactString(data.config, 'data'); redactObject(data.config.data); redactString(data.config, 'body'); redactObject(data.config.body); try { const url = new url_1.URL('', data.config.url); if (url.searchParams.has('token')) { url.searchParams.set('token', REDACT); } if (url.searchParams.has('client_secret')) { url.searchParams.set('client_secret', REDACT); } data.config.url = url.toString(); } catch (_b) { // ignore error - no need to parse an invalid URL } } if (data.response) { defaultErrorRedactor({ config: data.response.config }); redactHeaders(data.response.headers); redactString(data.response, 'data'); redactObject(data.response.data); } return data; } //# sourceMappingURL=common.js.map /***/ }), /***/ 6010: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright 2018 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 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 __classPrivateFieldGet = (this && this.__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); }; var __classPrivateFieldSet = (this && this.__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; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; var _Gaxios_instances, _a, _Gaxios_urlMayUseProxy, _Gaxios_applyRequestInterceptors, _Gaxios_applyResponseInterceptors, _Gaxios_prepareRequest, _Gaxios_proxyAgent, _Gaxios_getProxyAgent; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Gaxios = void 0; const extend_1 = __importDefault(__nccwpck_require__(3860)); const https_1 = __nccwpck_require__(5692); const node_fetch_1 = __importDefault(__nccwpck_require__(6705)); const querystring_1 = __importDefault(__nccwpck_require__(3480)); const is_stream_1 = __importDefault(__nccwpck_require__(6543)); const url_1 = __nccwpck_require__(7016); const common_1 = __nccwpck_require__(7506); const retry_1 = __nccwpck_require__(2789); const stream_1 = __nccwpck_require__(2203); const uuid_1 = __nccwpck_require__(3187); const interceptor_1 = __nccwpck_require__(5608); /* eslint-disable @typescript-eslint/no-explicit-any */ const fetch = hasFetch() ? window.fetch : node_fetch_1.default; function hasWindow() { return typeof window !== 'undefined' && !!window; } function hasFetch() { return hasWindow() && !!window.fetch; } function hasBuffer() { return typeof Buffer !== 'undefined'; } function hasHeader(options, header) { return !!getHeader(options, header); } function getHeader(options, header) { header = header.toLowerCase(); for (const key of Object.keys((options === null || options === void 0 ? void 0 : options.headers) || {})) { if (header === key.toLowerCase()) { return options.headers[key]; } } return undefined; } class Gaxios { /** * The Gaxios class is responsible for making HTTP requests. * @param defaults The default set of options to be used for this instance. */ constructor(defaults) { _Gaxios_instances.add(this); this.agentCache = new Map(); this.defaults = defaults || {}; this.interceptors = { request: new interceptor_1.GaxiosInterceptorManager(), response: new interceptor_1.GaxiosInterceptorManager(), }; } /** * Perform an HTTP request with the given options. * @param opts Set of HTTP options that will be used for this HTTP request. */ async request(opts = {}) { opts = await __classPrivateFieldGet(this, _Gaxios_instances, "m", _Gaxios_prepareRequest).call(this, opts); opts = await __classPrivateFieldGet(this, _Gaxios_instances, "m", _Gaxios_applyRequestInterceptors).call(this, opts); return __classPrivateFieldGet(this, _Gaxios_instances, "m", _Gaxios_applyResponseInterceptors).call(this, this._request(opts)); } async _defaultAdapter(opts) { const fetchImpl = opts.fetchImplementation || fetch; const res = (await fetchImpl(opts.url, opts)); const data = await this.getResponseData(opts, res); return this.translateResponse(opts, res, data); } /** * Internal, retryable version of the `request` method. * @param opts Set of HTTP options that will be used for this HTTP request. */ async _request(opts = {}) { var _b; try { let translatedResponse; if (opts.adapter) { translatedResponse = await opts.adapter(opts, this._defaultAdapter.bind(this)); } else { translatedResponse = await this._defaultAdapter(opts); } if (!opts.validateStatus(translatedResponse.status)) { if (opts.responseType === 'stream') { let response = ''; await new Promise(resolve => { (translatedResponse === null || translatedResponse === void 0 ? void 0 : translatedResponse.data).on('data', chunk => { response += chunk; }); (translatedResponse === null || translatedResponse === void 0 ? void 0 : translatedResponse.data).on('end', resolve); }); translatedResponse.data = response; } throw new common_1.GaxiosError(`Request failed with status code ${translatedResponse.status}`, opts, translatedResponse); } return translatedResponse; } catch (e) { const err = e instanceof common_1.GaxiosError ? e : new common_1.GaxiosError(e.message, opts, undefined, e); const { shouldRetry, config } = await (0, retry_1.getRetryConfig)(err); if (shouldRetry && config) { err.config.retryConfig.currentRetryAttempt = config.retryConfig.currentRetryAttempt; // The error's config could be redacted - therefore we only want to // copy the retry state over to the existing config opts.retryConfig = (_b = err.config) === null || _b === void 0 ? void 0 : _b.retryConfig; return this._request(opts); } throw err; } } async getResponseData(opts, res) { switch (opts.responseType) { case 'stream': return res.body; case 'json': { let data = await res.text(); try { data = JSON.parse(data); } catch (_b) { // continue } return data; } case 'arraybuffer': return res.arrayBuffer(); case 'blob': return res.blob(); case 'text': return res.text(); default: return this.getResponseDataFromContentType(res); } } /** * By default, throw for any non-2xx status code * @param status status code from the HTTP response */ validateStatus(status) { return status >= 200 && status < 300; } /** * Encode a set of key/value pars into a querystring format (?foo=bar&baz=boo) * @param params key value pars to encode */ paramsSerializer(params) { return querystring_1.default.stringify(params); } translateResponse(opts, res, data) { // headers need to be converted from a map to an obj const headers = {}; res.headers.forEach((value, key) => { headers[key] = value; }); return { config: opts, data: data, headers, status: res.status, statusText: res.statusText, // XMLHttpRequestLike request: { responseURL: res.url, }, }; } /** * Attempts to parse a response by looking at the Content-Type header. * @param {FetchResponse} response the HTTP response. * @returns {Promise} a promise that resolves to the response data. */ async getResponseDataFromContentType(response) { let contentType = response.headers.get('Content-Type'); if (contentType === null) { // Maintain existing functionality by calling text() return response.text(); } contentType = contentType.toLowerCase(); if (contentType.includes('application/json')) { let data = await response.text(); try { data = JSON.parse(data); } catch (_b) { // continue } return data; } else if (contentType.match(/^text\//)) { return response.text(); } else { // If the content type is something not easily handled, just return the raw data (blob) return response.blob(); } } /** * Creates an async generator that yields the pieces of a multipart/related request body. * This implementation follows the spec: https://www.ietf.org/rfc/rfc2387.txt. However, recursive * multipart/related requests are not currently supported. * * @param {GaxioMultipartOptions[]} multipartOptions the pieces to turn into a multipart/related body. * @param {string} boundary the boundary string to be placed between each part. */ async *getMultipartRequest(multipartOptions, boundary) { const finale = `--${boundary}--`; for (const currentPart of multipartOptions) { const partContentType = currentPart.headers['Content-Type'] || 'application/octet-stream'; const preamble = `--${boundary}\r\nContent-Type: ${partContentType}\r\n\r\n`; yield preamble; if (typeof currentPart.content === 'string') { yield currentPart.content; } else { yield* currentPart.content; } yield '\r\n'; } yield finale; } } exports.Gaxios = Gaxios; _a = Gaxios, _Gaxios_instances = new WeakSet(), _Gaxios_urlMayUseProxy = function _Gaxios_urlMayUseProxy(url, noProxy = []) { var _b, _c; const candidate = new url_1.URL(url); const noProxyList = [...noProxy]; const noProxyEnvList = ((_c = ((_b = process.env.NO_PROXY) !== null && _b !== void 0 ? _b : process.env.no_proxy)) === null || _c === void 0 ? void 0 : _c.split(',')) || []; for (const rule of noProxyEnvList) { noProxyList.push(rule.trim()); } for (const rule of noProxyList) { // Match regex if (rule instanceof RegExp) { if (rule.test(candidate.toString())) { return false; } } // Match URL else if (rule instanceof url_1.URL) { if (rule.origin === candidate.origin) { return false; } } // Match string regex else if (rule.startsWith('*.') || rule.startsWith('.')) { const cleanedRule = rule.replace(/^\*\./, '.'); if (candidate.hostname.endsWith(cleanedRule)) { return false; } } // Basic string match else if (rule === candidate.origin || rule === candidate.hostname || rule === candidate.href) { return false; } } return true; }, _Gaxios_applyRequestInterceptors = /** * Applies the request interceptors. The request interceptors are applied after the * call to prepareRequest is completed. * * @param {GaxiosOptions} options The current set of options. * * @returns {Promise} Promise that resolves to the set of options or response after interceptors are applied. */ async function _Gaxios_applyRequestInterceptors(options) { let promiseChain = Promise.resolve(options); for (const interceptor of this.interceptors.request.values()) { if (interceptor) { promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected); } } return promiseChain; }, _Gaxios_applyResponseInterceptors = /** * Applies the response interceptors. The response interceptors are applied after the * call to request is made. * * @param {GaxiosOptions} options The current set of options. * * @returns {Promise} Promise that resolves to the set of options or response after interceptors are applied. */ async function _Gaxios_applyResponseInterceptors(response) { let promiseChain = Promise.resolve(response); for (const interceptor of this.interceptors.response.values()) { if (interceptor) { promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected); } } return promiseChain; }, _Gaxios_prepareRequest = /** * Validates the options, merges them with defaults, and prepare request. * * @param options The original options passed from the client. * @returns Prepared options, ready to make a request */ async function _Gaxios_prepareRequest(options) { var _b, _c, _d, _e; const opts = (0, extend_1.default)(true, {}, this.defaults, options); if (!opts.url) { throw new Error('URL is required.'); } // baseUrl has been deprecated, remove in 2.0 const baseUrl = opts.baseUrl || opts.baseURL; if (baseUrl) { opts.url = baseUrl.toString() + opts.url; } opts.paramsSerializer = opts.paramsSerializer || this.paramsSerializer; if (opts.params && Object.keys(opts.params).length > 0) { let additionalQueryParams = opts.paramsSerializer(opts.params); if (additionalQueryParams.startsWith('?')) { additionalQueryParams = additionalQueryParams.slice(1); } const prefix = opts.url.toString().includes('?') ? '&' : '?'; opts.url = opts.url + prefix + additionalQueryParams; } if (typeof options.maxContentLength === 'number') { opts.size = options.maxContentLength; } if (typeof options.maxRedirects === 'number') { opts.follow = options.maxRedirects; } opts.headers = opts.headers || {}; if (opts.multipart === undefined && opts.data) { const isFormData = typeof FormData === 'undefined' ? false : (opts === null || opts === void 0 ? void 0 : opts.data) instanceof FormData; if (is_stream_1.default.readable(opts.data)) { opts.body = opts.data; } else if (hasBuffer() && Buffer.isBuffer(opts.data)) { // Do not attempt to JSON.stringify() a Buffer: opts.body = opts.data; if (!hasHeader(opts, 'Content-Type')) { opts.headers['Content-Type'] = 'application/json'; } } else if (typeof opts.data === 'object') { // If www-form-urlencoded content type has been set, but data is // provided as an object, serialize the content using querystring: if (!isFormData) { if (getHeader(opts, 'content-type') === 'application/x-www-form-urlencoded') { opts.body = opts.paramsSerializer(opts.data); } else { // } else if (!(opts.data instanceof FormData)) { if (!hasHeader(opts, 'Content-Type')) { opts.headers['Content-Type'] = 'application/json'; } opts.body = JSON.stringify(opts.data); } } } else { opts.body = opts.data; } } else if (opts.multipart && opts.multipart.length > 0) { // note: once the minimum version reaches Node 16, // this can be replaced with randomUUID() function from crypto // and the dependency on UUID removed const boundary = (0, uuid_1.v4)(); opts.headers['Content-Type'] = `multipart/related; boundary=${boundary}`; const bodyStream = new stream_1.PassThrough(); opts.body = bodyStream; (0, stream_1.pipeline)(this.getMultipartRequest(opts.multipart, boundary), bodyStream, () => { }); } opts.validateStatus = opts.validateStatus || this.validateStatus; opts.responseType = opts.responseType || 'unknown'; if (!opts.headers['Accept'] && opts.responseType === 'json') { opts.headers['Accept'] = 'application/json'; } opts.method = opts.method || 'GET'; const proxy = opts.proxy || ((_b = process === null || process === void 0 ? void 0 : process.env) === null || _b === void 0 ? void 0 : _b.HTTPS_PROXY) || ((_c = process === null || process === void 0 ? void 0 : process.env) === null || _c === void 0 ? void 0 : _c.https_proxy) || ((_d = process === null || process === void 0 ? void 0 : process.env) === null || _d === void 0 ? void 0 : _d.HTTP_PROXY) || ((_e = process === null || process === void 0 ? void 0 : process.env) === null || _e === void 0 ? void 0 : _e.http_proxy); const urlMayUseProxy = __classPrivateFieldGet(this, _Gaxios_instances, "m", _Gaxios_urlMayUseProxy).call(this, opts.url, opts.noProxy); if (opts.agent) { // don't do any of the following options - use the user-provided agent. } else if (proxy && urlMayUseProxy) { const HttpsProxyAgent = await __classPrivateFieldGet(_a, _a, "m", _Gaxios_getProxyAgent).call(_a); if (this.agentCache.has(proxy)) { opts.agent = this.agentCache.get(proxy); } else { opts.agent = new HttpsProxyAgent(proxy, { cert: opts.cert, key: opts.key, }); this.agentCache.set(proxy, opts.agent); } } else if (opts.cert && opts.key) { // Configure client for mTLS if (this.agentCache.has(opts.key)) { opts.agent = this.agentCache.get(opts.key); } else { opts.agent = new https_1.Agent({ cert: opts.cert, key: opts.key, }); this.agentCache.set(opts.key, opts.agent); } } if (typeof opts.errorRedactor !== 'function' && opts.errorRedactor !== false) { opts.errorRedactor = common_1.defaultErrorRedactor; } return opts; }, _Gaxios_getProxyAgent = async function _Gaxios_getProxyAgent() { __classPrivateFieldSet(this, _a, __classPrivateFieldGet(this, _a, "f", _Gaxios_proxyAgent) || (await Promise.resolve().then(() => __importStar(__nccwpck_require__(3669)))).HttpsProxyAgent, "f", _Gaxios_proxyAgent); return __classPrivateFieldGet(this, _a, "f", _Gaxios_proxyAgent); }; /** * A cache for the lazily-loaded proxy agent. * * Should use {@link Gaxios[#getProxyAgent]} to retrieve. */ // using `import` to dynamically import the types here _Gaxios_proxyAgent = { value: void 0 }; //# sourceMappingURL=gaxios.js.map /***/ }), /***/ 7003: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright 2018 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.instance = exports.Gaxios = exports.GaxiosError = void 0; exports.request = request; const gaxios_1 = __nccwpck_require__(6010); Object.defineProperty(exports, "Gaxios", ({ enumerable: true, get: function () { return gaxios_1.Gaxios; } })); var common_1 = __nccwpck_require__(7506); Object.defineProperty(exports, "GaxiosError", ({ enumerable: true, get: function () { return common_1.GaxiosError; } })); __exportStar(__nccwpck_require__(5608), exports); /** * The default instance used when the `request` method is directly * invoked. */ exports.instance = new gaxios_1.Gaxios(); /** * Make an HTTP request using the given options. * @param opts Options for the request */ async function request(opts) { return exports.instance.request(opts); } //# sourceMappingURL=index.js.map /***/ }), /***/ 5608: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright 2024 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GaxiosInterceptorManager = void 0; /** * Class to manage collections of GaxiosInterceptors for both requests and responses. */ class GaxiosInterceptorManager extends Set { } exports.GaxiosInterceptorManager = GaxiosInterceptorManager; //# sourceMappingURL=interceptor.js.map /***/ }), /***/ 2789: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright 2018 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getRetryConfig = getRetryConfig; async function getRetryConfig(err) { let config = getConfig(err); if (!err || !err.config || (!config && !err.config.retry)) { return { shouldRetry: false }; } config = config || {}; config.currentRetryAttempt = config.currentRetryAttempt || 0; config.retry = config.retry === undefined || config.retry === null ? 3 : config.retry; config.httpMethodsToRetry = config.httpMethodsToRetry || [ 'GET', 'HEAD', 'PUT', 'OPTIONS', 'DELETE', ]; config.noResponseRetries = config.noResponseRetries === undefined || config.noResponseRetries === null ? 2 : config.noResponseRetries; config.retryDelayMultiplier = config.retryDelayMultiplier ? config.retryDelayMultiplier : 2; config.timeOfFirstRequest = config.timeOfFirstRequest ? config.timeOfFirstRequest : Date.now(); config.totalTimeout = config.totalTimeout ? config.totalTimeout : Number.MAX_SAFE_INTEGER; config.maxRetryDelay = config.maxRetryDelay ? config.maxRetryDelay : Number.MAX_SAFE_INTEGER; // If this wasn't in the list of status codes where we want // to automatically retry, return. const retryRanges = [ // https://en.wikipedia.org/wiki/List_of_HTTP_status_codes // 1xx - Retry (Informational, request still processing) // 2xx - Do not retry (Success) // 3xx - Do not retry (Redirect) // 4xx - Do not retry (Client errors) // 408 - Retry ("Request Timeout") // 429 - Retry ("Too Many Requests") // 5xx - Retry (Server errors) [100, 199], [408, 408], [429, 429], [500, 599], ]; config.statusCodesToRetry = config.statusCodesToRetry || retryRanges; // Put the config back into the err err.config.retryConfig = config; // Determine if we should retry the request const shouldRetryFn = config.shouldRetry || shouldRetryRequest; if (!(await shouldRetryFn(err))) { return { shouldRetry: false, config: err.config }; } const delay = getNextRetryDelay(config); // We're going to retry! Incremenent the counter. err.config.retryConfig.currentRetryAttempt += 1; // Create a promise that invokes the retry after the backOffDelay const backoff = config.retryBackoff ? config.retryBackoff(err, delay) : new Promise(resolve => { setTimeout(resolve, delay); }); // Notify the user if they added an `onRetryAttempt` handler if (config.onRetryAttempt) { config.onRetryAttempt(err); } // Return the promise in which recalls Gaxios to retry the request await backoff; return { shouldRetry: true, config: err.config }; } /** * Determine based on config if we should retry the request. * @param err The GaxiosError passed to the interceptor. */ function shouldRetryRequest(err) { var _a; const config = getConfig(err); // node-fetch raises an AbortError if signaled: // https://github.com/bitinn/node-fetch#request-cancellation-with-abortsignal if (err.name === 'AbortError' || ((_a = err.error) === null || _a === void 0 ? void 0 : _a.name) === 'AbortError') { return false; } // If there's no config, or retries are disabled, return. if (!config || config.retry === 0) { return false; } // Check if this error has no response (ETIMEDOUT, ENOTFOUND, etc) if (!err.response && (config.currentRetryAttempt || 0) >= config.noResponseRetries) { return false; } // Only retry with configured HttpMethods. if (!err.config.method || config.httpMethodsToRetry.indexOf(err.config.method.toUpperCase()) < 0) { return false; } // If this wasn't in the list of status codes where we want // to automatically retry, return. if (err.response && err.response.status) { let isInRange = false; for (const [min, max] of config.statusCodesToRetry) { const status = err.response.status; if (status >= min && status <= max) { isInRange = true; break; } } if (!isInRange) { return false; } } // If we are out of retry attempts, return config.currentRetryAttempt = config.currentRetryAttempt || 0; if (config.currentRetryAttempt >= config.retry) { return false; } return true; } /** * Acquire the raxConfig object from an GaxiosError if available. * @param err The Gaxios error with a config object. */ function getConfig(err) { if (err && err.config && err.config.retryConfig) { return err.config.retryConfig; } return; } /** * Gets the delay to wait before the next retry. * * @param {RetryConfig} config The current set of retry options * @returns {number} the amount of ms to wait before the next retry attempt. */ function getNextRetryDelay(config) { var _a; // Calculate time to wait with exponential backoff. // If this is the first retry, look for a configured retryDelay. const retryDelay = config.currentRetryAttempt ? 0 : (_a = config.retryDelay) !== null && _a !== void 0 ? _a : 100; // Formula: retryDelay + ((retryDelayMultiplier^currentRetryAttempt - 1 / 2) * 1000) const calculatedDelay = retryDelay + ((Math.pow(config.retryDelayMultiplier, config.currentRetryAttempt) - 1) / 2) * 1000; const maxAllowableDelay = config.totalTimeout - (Date.now() - config.timeOfFirstRequest); return Math.min(calculatedDelay, maxAllowableDelay, config.maxRetryDelay); } //# sourceMappingURL=retry.js.map /***/ }), /***/ 3155: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright 2023 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.pkg = void 0; exports.pkg = __nccwpck_require__(6495); //# sourceMappingURL=util.js.map /***/ }), /***/ 3187: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "NIL", ({ enumerable: true, get: function () { return _nil.default; } })); Object.defineProperty(exports, "parse", ({ enumerable: true, get: function () { return _parse.default; } })); Object.defineProperty(exports, "stringify", ({ enumerable: true, get: function () { return _stringify.default; } })); 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, "validate", ({ enumerable: true, get: function () { return _validate.default; } })); Object.defineProperty(exports, "version", ({ enumerable: true, get: function () { return _version.default; } })); var _v = _interopRequireDefault(__nccwpck_require__(6698)); var _v2 = _interopRequireDefault(__nccwpck_require__(6272)); var _v3 = _interopRequireDefault(__nccwpck_require__(8485)); var _v4 = _interopRequireDefault(__nccwpck_require__(742)); var _nil = _interopRequireDefault(__nccwpck_require__(8212)); var _version = _interopRequireDefault(__nccwpck_require__(6651)); var _validate = _interopRequireDefault(__nccwpck_require__(5913)); var _stringify = _interopRequireDefault(__nccwpck_require__(4386)); var _parse = _interopRequireDefault(__nccwpck_require__(9884)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /***/ }), /***/ 1979: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _crypto = _interopRequireDefault(__nccwpck_require__(6982)); 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(); } var _default = md5; exports["default"] = _default; /***/ }), /***/ 3968: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _crypto = _interopRequireDefault(__nccwpck_require__(6982)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _default = { randomUUID: _crypto.default.randomUUID }; exports["default"] = _default; /***/ }), /***/ 8212: /***/ ((__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; /***/ }), /***/ 9884: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _validate = _interopRequireDefault(__nccwpck_require__(5913)); 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; } var _default = parse; exports["default"] = _default; /***/ }), /***/ 956: /***/ ((__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; /***/ }), /***/ 4566: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = rng; var _crypto = _interopRequireDefault(__nccwpck_require__(6982)); 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); } /***/ }), /***/ 5398: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _crypto = _interopRequireDefault(__nccwpck_require__(6982)); 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; /***/ }), /***/ 4386: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; exports.unsafeStringify = unsafeStringify; var _validate = _interopRequireDefault(__nccwpck_require__(5913)); 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).slice(1)); } function unsafeStringify(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 return 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]]; } function stringify(arr, offset = 0) { const uuid = unsafeStringify(arr, offset); // 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; /***/ }), /***/ 6698: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _rng = _interopRequireDefault(__nccwpck_require__(4566)); var _stringify = __nccwpck_require__(4386); 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.unsafeStringify)(b); } var _default = v1; exports["default"] = _default; /***/ }), /***/ 6272: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _v = _interopRequireDefault(__nccwpck_require__(2781)); var _md = _interopRequireDefault(__nccwpck_require__(1979)); 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; /***/ }), /***/ 2781: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.URL = exports.DNS = void 0; exports["default"] = v35; var _stringify = __nccwpck_require__(4386); var _parse = _interopRequireDefault(__nccwpck_require__(9884)); 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 v35(name, version, hashfunc) { function generateUUID(value, namespace, buf, offset) { var _namespace; if (typeof value === 'string') { value = stringToBytes(value); } if (typeof namespace === 'string') { namespace = (0, _parse.default)(namespace); } if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _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); bytes.set(namespace); bytes.set(value, namespace.length); bytes = hashfunc(bytes); bytes[6] = bytes[6] & 0x0f | version; bytes[8] = bytes[8] & 0x3f | 0x80; if (buf) { offset = offset || 0; for (let i = 0; i < 16; ++i) { buf[offset + i] = bytes[i]; } return buf; } return (0, _stringify.unsafeStringify)(bytes); } // Function#name is not settable on some platforms (#270) try { generateUUID.name = name; // eslint-disable-next-line no-empty } catch (err) {} // For CommonJS default export support generateUUID.DNS = DNS; generateUUID.URL = URL; return generateUUID; } /***/ }), /***/ 8485: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _native = _interopRequireDefault(__nccwpck_require__(3968)); var _rng = _interopRequireDefault(__nccwpck_require__(4566)); var _stringify = __nccwpck_require__(4386); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function v4(options, buf, offset) { if (_native.default.randomUUID && !buf && !options) { return _native.default.randomUUID(); } options = options || {}; const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` rnds[6] = rnds[6] & 0x0f | 0x40; rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided if (buf) { offset = offset || 0; for (let i = 0; i < 16; ++i) { buf[offset + i] = rnds[i]; } return buf; } return (0, _stringify.unsafeStringify)(rnds); } var _default = v4; exports["default"] = _default; /***/ }), /***/ 742: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _v = _interopRequireDefault(__nccwpck_require__(2781)); var _sha = _interopRequireDefault(__nccwpck_require__(5398)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const v5 = (0, _v.default)('v5', 0x50, _sha.default); var _default = v5; exports["default"] = _default; /***/ }), /***/ 5913: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _regex = _interopRequireDefault(__nccwpck_require__(956)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function validate(uuid) { return typeof uuid === 'string' && _regex.default.test(uuid); } var _default = validate; exports["default"] = _default; /***/ }), /***/ 6651: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _validate = _interopRequireDefault(__nccwpck_require__(5913)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function version(uuid) { if (!(0, _validate.default)(uuid)) { throw TypeError('Invalid UUID'); } return parseInt(uuid.slice(14, 15), 16); } var _default = version; exports["default"] = _default; /***/ }), /***/ 381: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /** * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GCE_LINUX_BIOS_PATHS = void 0; exports.isGoogleCloudServerless = isGoogleCloudServerless; exports.isGoogleComputeEngineLinux = isGoogleComputeEngineLinux; exports.isGoogleComputeEngineMACAddress = isGoogleComputeEngineMACAddress; exports.isGoogleComputeEngine = isGoogleComputeEngine; exports.detectGCPResidency = detectGCPResidency; const fs_1 = __nccwpck_require__(9896); const os_1 = __nccwpck_require__(857); /** * Known paths unique to Google Compute Engine Linux instances */ exports.GCE_LINUX_BIOS_PATHS = { BIOS_DATE: '/sys/class/dmi/id/bios_date', BIOS_VENDOR: '/sys/class/dmi/id/bios_vendor', }; const GCE_MAC_ADDRESS_REGEX = /^42:01/; /** * Determines if the process is running on a Google Cloud Serverless environment (Cloud Run or Cloud Functions instance). * * Uses the: * - {@link https://cloud.google.com/run/docs/container-contract#env-vars Cloud Run environment variables}. * - {@link https://cloud.google.com/functions/docs/env-var Cloud Functions environment variables}. * * @returns {boolean} `true` if the process is running on GCP serverless, `false` otherwise. */ function isGoogleCloudServerless() { /** * `CLOUD_RUN_JOB` is used for Cloud Run Jobs * - See {@link https://cloud.google.com/run/docs/container-contract#env-vars Cloud Run environment variables}. * * `FUNCTION_NAME` is used in older Cloud Functions environments: * - See {@link https://cloud.google.com/functions/docs/env-var Python 3.7 and Go 1.11}. * * `K_SERVICE` is used in Cloud Run and newer Cloud Functions environments: * - See {@link https://cloud.google.com/run/docs/container-contract#env-vars Cloud Run environment variables}. * - See {@link https://cloud.google.com/functions/docs/env-var Cloud Functions newer runtimes}. */ const isGFEnvironment = process.env.CLOUD_RUN_JOB || process.env.FUNCTION_NAME || process.env.K_SERVICE; return !!isGFEnvironment; } /** * Determines if the process is running on a Linux Google Compute Engine instance. * * @returns {boolean} `true` if the process is running on Linux GCE, `false` otherwise. */ function isGoogleComputeEngineLinux() { if ((0, os_1.platform)() !== 'linux') return false; try { // ensure this file exist (0, fs_1.statSync)(exports.GCE_LINUX_BIOS_PATHS.BIOS_DATE); // ensure this file exist and matches const biosVendor = (0, fs_1.readFileSync)(exports.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR, 'utf8'); return /Google/.test(biosVendor); } catch (_a) { return false; } } /** * Determines if the process is running on a Google Compute Engine instance with a known * MAC address. * * @returns {boolean} `true` if the process is running on GCE (as determined by MAC address), `false` otherwise. */ function isGoogleComputeEngineMACAddress() { const interfaces = (0, os_1.networkInterfaces)(); for (const item of Object.values(interfaces)) { if (!item) continue; for (const { mac } of item) { if (GCE_MAC_ADDRESS_REGEX.test(mac)) { return true; } } } return false; } /** * Determines if the process is running on a Google Compute Engine instance. * * @returns {boolean} `true` if the process is running on GCE, `false` otherwise. */ function isGoogleComputeEngine() { return isGoogleComputeEngineLinux() || isGoogleComputeEngineMACAddress(); } /** * Determines if the process is running on Google Cloud Platform. * * @returns {boolean} `true` if the process is running on GCP, `false` otherwise. */ function detectGCPResidency() { return isGoogleCloudServerless() || isGoogleComputeEngine(); } //# sourceMappingURL=gcp-residency.js.map /***/ }), /***/ 3046: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; /** * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.gcpResidencyCache = exports.METADATA_SERVER_DETECTION = exports.HEADERS = exports.HEADER_VALUE = exports.HEADER_NAME = exports.SECONDARY_HOST_ADDRESS = exports.HOST_ADDRESS = exports.BASE_PATH = void 0; exports.instance = instance; exports.project = project; exports.universe = universe; exports.bulk = bulk; exports.isAvailable = isAvailable; exports.resetIsAvailableCache = resetIsAvailableCache; exports.getGCPResidency = getGCPResidency; exports.setGCPResidency = setGCPResidency; exports.requestTimeout = requestTimeout; const gaxios_1 = __nccwpck_require__(7003); const jsonBigint = __nccwpck_require__(4826); const gcp_residency_1 = __nccwpck_require__(381); const logger = __nccwpck_require__(1577); exports.BASE_PATH = '/computeMetadata/v1'; exports.HOST_ADDRESS = 'http://169.254.169.254'; exports.SECONDARY_HOST_ADDRESS = 'http://metadata.google.internal.'; exports.HEADER_NAME = 'Metadata-Flavor'; exports.HEADER_VALUE = 'Google'; exports.HEADERS = Object.freeze({ [exports.HEADER_NAME]: exports.HEADER_VALUE }); const log = logger.log('gcp metadata'); /** * Metadata server detection override options. * * Available via `process.env.METADATA_SERVER_DETECTION`. */ exports.METADATA_SERVER_DETECTION = Object.freeze({ 'assume-present': "don't try to ping the metadata server, but assume it's present", none: "don't try to ping the metadata server, but don't try to use it either", 'bios-only': "treat the result of a BIOS probe as canonical (don't fall back to pinging)", 'ping-only': 'skip the BIOS probe, and go straight to pinging', }); /** * Returns the base URL while taking into account the GCE_METADATA_HOST * environment variable if it exists. * * @returns The base URL, e.g., http://169.254.169.254/computeMetadata/v1. */ function getBaseUrl(baseUrl) { if (!baseUrl) { baseUrl = process.env.GCE_METADATA_IP || process.env.GCE_METADATA_HOST || exports.HOST_ADDRESS; } // If no scheme is provided default to HTTP: if (!/^https?:\/\//.test(baseUrl)) { baseUrl = `http://${baseUrl}`; } return new URL(exports.BASE_PATH, baseUrl).href; } // Accepts an options object passed from the user to the API. In previous // versions of the API, it referred to a `Request` or an `Axios` request // options object. Now it refers to an object with very limited property // names. This is here to help ensure users don't pass invalid options when // they upgrade from 0.4 to 0.5 to 0.8. function validate(options) { Object.keys(options).forEach(key => { switch (key) { case 'params': case 'property': case 'headers': break; case 'qs': throw new Error("'qs' is not a valid configuration option. Please use 'params' instead."); default: throw new Error(`'${key}' is not a valid configuration option.`); } }); } async function metadataAccessor(type, options = {}, noResponseRetries = 3, fastFail = false) { let metadataKey = ''; let params = {}; let headers = {}; if (typeof type === 'object') { const metadataAccessor = type; metadataKey = metadataAccessor.metadataKey; params = metadataAccessor.params || params; headers = metadataAccessor.headers || headers; noResponseRetries = metadataAccessor.noResponseRetries || noResponseRetries; fastFail = metadataAccessor.fastFail || fastFail; } else { metadataKey = type; } if (typeof options === 'string') { metadataKey += `/${options}`; } else { validate(options); if (options.property) { metadataKey += `/${options.property}`; } headers = options.headers || headers; params = options.params || params; } const requestMethod = fastFail ? fastFailMetadataRequest : gaxios_1.request; const req = { url: `${getBaseUrl()}/${metadataKey}`, headers: { ...exports.HEADERS, ...headers }, retryConfig: { noResponseRetries }, params, responseType: 'text', timeout: requestTimeout(), }; log.info('instance request %j', req); const res = await requestMethod(req); log.info('instance metadata is %s', res.data); // NOTE: node.js converts all incoming headers to lower case. if (res.headers[exports.HEADER_NAME.toLowerCase()] !== exports.HEADER_VALUE) { throw new Error(`Invalid response from metadata service: incorrect ${exports.HEADER_NAME} header. Expected '${exports.HEADER_VALUE}', got ${res.headers[exports.HEADER_NAME.toLowerCase()] ? `'${res.headers[exports.HEADER_NAME.toLowerCase()]}'` : 'no header'}`); } if (typeof res.data === 'string') { try { return jsonBigint.parse(res.data); } catch (_a) { /* ignore */ } } return res.data; } async function fastFailMetadataRequest(options) { var _a; const secondaryOptions = { ...options, url: (_a = options.url) === null || _a === void 0 ? void 0 : _a.toString().replace(getBaseUrl(), getBaseUrl(exports.SECONDARY_HOST_ADDRESS)), }; // We race a connection between DNS/IP to metadata server. There are a couple // reasons for this: // // 1. the DNS is slow in some GCP environments; by checking both, we might // detect the runtime environment signficantly faster. // 2. we can't just check the IP, which is tarpitted and slow to respond // on a user's local machine. // // Additional logic has been added to make sure that we don't create an // unhandled rejection in scenarios where a failure happens sometime // after a success. // // Note, however, if a failure happens prior to a success, a rejection should // occur, this is for folks running locally. // let responded = false; const r1 = (0, gaxios_1.request)(options) .then(res => { responded = true; return res; }) .catch(err => { if (responded) { return r2; } else { responded = true; throw err; } }); const r2 = (0, gaxios_1.request)(secondaryOptions) .then(res => { responded = true; return res; }) .catch(err => { if (responded) { return r1; } else { responded = true; throw err; } }); return Promise.race([r1, r2]); } /** * Obtain metadata for the current GCE instance. * * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} * * @example * ``` * const serviceAccount: {} = await instance('service-accounts/'); * const serviceAccountEmail: string = await instance('service-accounts/default/email'); * ``` */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function instance(options) { return metadataAccessor('instance', options); } /** * Obtain metadata for the current GCP project. * * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} * * @example * ``` * const projectId: string = await project('project-id'); * const numericProjectId: number = await project('numeric-project-id'); * ``` */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function project(options) { return metadataAccessor('project', options); } /** * Obtain metadata for the current universe. * * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} * * @example * ``` * const universeDomain: string = await universe('universe-domain'); * ``` */ function universe(options) { return metadataAccessor('universe', options); } /** * Retrieve metadata items in parallel. * * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} * * @example * ``` * const data = await bulk([ * { * metadataKey: 'instance', * }, * { * metadataKey: 'project/project-id', * }, * ] as const); * * // data.instance; * // data['project/project-id']; * ``` * * @param properties The metadata properties to retrieve * @returns The metadata in `metadatakey:value` format */ async function bulk(properties) { const r = {}; await Promise.all(properties.map(item => { return (async () => { const res = await metadataAccessor(item); const key = item.metadataKey; r[key] = res; })(); })); return r; } /* * How many times should we retry detecting GCP environment. */ function detectGCPAvailableRetries() { return process.env.DETECT_GCP_RETRIES ? Number(process.env.DETECT_GCP_RETRIES) : 0; } let cachedIsAvailableResponse; /** * Determine if the metadata server is currently available. */ async function isAvailable() { if (process.env.METADATA_SERVER_DETECTION) { const value = process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase(); if (!(value in exports.METADATA_SERVER_DETECTION)) { throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${value}\`, but it should be \`${Object.keys(exports.METADATA_SERVER_DETECTION).join('`, `')}\`, or unset`); } switch (value) { case 'assume-present': return true; case 'none': return false; case 'bios-only': return getGCPResidency(); case 'ping-only': // continue, we want to ping the server } } try { // If a user is instantiating several GCP libraries at the same time, // this may result in multiple calls to isAvailable(), to detect the // runtime environment. We use the same promise for each of these calls // to reduce the network load. if (cachedIsAvailableResponse === undefined) { cachedIsAvailableResponse = metadataAccessor('instance', undefined, detectGCPAvailableRetries(), // If the default HOST_ADDRESS has been overridden, we should not // make an effort to try SECONDARY_HOST_ADDRESS (as we are likely in // a non-GCP environment): !(process.env.GCE_METADATA_IP || process.env.GCE_METADATA_HOST)); } await cachedIsAvailableResponse; return true; } catch (e) { const err = e; if (process.env.DEBUG_AUTH) { console.info(err); } if (err.type === 'request-timeout') { // If running in a GCP environment, metadata endpoint should return // within ms. return false; } if (err.response && err.response.status === 404) { return false; } else { if (!(err.response && err.response.status === 404) && // A warning is emitted if we see an unexpected err.code, or err.code // is not populated: (!err.code || ![ 'EHOSTDOWN', 'EHOSTUNREACH', 'ENETUNREACH', 'ENOENT', 'ENOTFOUND', 'ECONNREFUSED', ].includes(err.code))) { let code = 'UNKNOWN'; if (err.code) code = err.code; process.emitWarning(`received unexpected error = ${err.message} code = ${code}`, 'MetadataLookupWarning'); } // Failure to resolve the metadata service means that it is not available. return false; } } } /** * reset the memoized isAvailable() lookup. */ function resetIsAvailableCache() { cachedIsAvailableResponse = undefined; } /** * A cache for the detected GCP Residency. */ exports.gcpResidencyCache = null; /** * Detects GCP Residency. * Caches results to reduce costs for subsequent calls. * * @see setGCPResidency for setting */ function getGCPResidency() { if (exports.gcpResidencyCache === null) { setGCPResidency(); } return exports.gcpResidencyCache; } /** * Sets the detected GCP Residency. * Useful for forcing metadata server detection behavior. * * Set `null` to autodetect the environment (default behavior). * @see getGCPResidency for getting */ function setGCPResidency(value = null) { exports.gcpResidencyCache = value !== null ? value : (0, gcp_residency_1.detectGCPResidency)(); } /** * Obtain the timeout for requests to the metadata server. * * In certain environments and conditions requests can take longer than * the default timeout to complete. This function will determine the * appropriate timeout based on the environment. * * @returns {number} a request timeout duration in milliseconds. */ function requestTimeout() { return getGCPResidency() ? 0 : 3000; } __exportStar(__nccwpck_require__(381), exports); //# sourceMappingURL=index.js.map /***/ }), /***/ 4810: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright 2012 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AuthClient = exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = exports.DEFAULT_UNIVERSE = void 0; const events_1 = __nccwpck_require__(4434); const gaxios_1 = __nccwpck_require__(7003); const transporters_1 = __nccwpck_require__(7633); const util_1 = __nccwpck_require__(7870); /** * The default cloud universe * * @see {@link AuthJSONOptions.universe_domain} */ exports.DEFAULT_UNIVERSE = 'googleapis.com'; /** * The default {@link AuthClientOptions.eagerRefreshThresholdMillis} */ exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = 5 * 60 * 1000; class AuthClient extends events_1.EventEmitter { constructor(opts = {}) { var _a, _b, _c, _d, _e; super(); this.credentials = {}; this.eagerRefreshThresholdMillis = exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS; this.forceRefreshOnFailure = false; this.universeDomain = exports.DEFAULT_UNIVERSE; const options = (0, util_1.originalOrCamelOptions)(opts); // Shared auth options this.apiKey = opts.apiKey; this.projectId = (_a = options.get('project_id')) !== null && _a !== void 0 ? _a : null; this.quotaProjectId = options.get('quota_project_id'); this.credentials = (_b = options.get('credentials')) !== null && _b !== void 0 ? _b : {}; this.universeDomain = (_c = options.get('universe_domain')) !== null && _c !== void 0 ? _c : exports.DEFAULT_UNIVERSE; // Shared client options this.transporter = (_d = opts.transporter) !== null && _d !== void 0 ? _d : new transporters_1.DefaultTransporter(); if (opts.transporterOptions) { this.transporter.defaults = opts.transporterOptions; } if (opts.eagerRefreshThresholdMillis) { this.eagerRefreshThresholdMillis = opts.eagerRefreshThresholdMillis; } this.forceRefreshOnFailure = (_e = opts.forceRefreshOnFailure) !== null && _e !== void 0 ? _e : false; } /** * Return the {@link Gaxios `Gaxios`} instance from the {@link AuthClient.transporter}. * * @expiremental */ get gaxios() { if (this.transporter instanceof gaxios_1.Gaxios) { return this.transporter; } else if (this.transporter instanceof transporters_1.DefaultTransporter) { return this.transporter.instance; } else if ('instance' in this.transporter && this.transporter.instance instanceof gaxios_1.Gaxios) { return this.transporter.instance; } return null; } /** * Sets the auth credentials. */ setCredentials(credentials) { this.credentials = credentials; } /** * Append additional headers, e.g., x-goog-user-project, shared across the * classes inheriting AuthClient. This method should be used by any method * that overrides getRequestMetadataAsync(), which is a shared helper for * setting request information in both gRPC and HTTP API calls. * * @param headers object to append additional headers to. */ addSharedMetadataHeaders(headers) { // quota_project_id, stored in application_default_credentials.json, is set in // the x-goog-user-project header, to indicate an alternate account for // billing and quota: if (!headers['x-goog-user-project'] && // don't override a value the user sets. this.quotaProjectId) { headers['x-goog-user-project'] = this.quotaProjectId; } return headers; } /** * Retry config for Auth-related requests. * * @remarks * * This is not a part of the default {@link AuthClient.transporter transporter/gaxios} * config as some downstream APIs would prefer if customers explicitly enable retries, * such as GCS. */ static get RETRY_CONFIG() { return { retry: true, retryConfig: { httpMethodsToRetry: ['GET', 'PUT', 'POST', 'HEAD', 'OPTIONS', 'DELETE'], }, }; } } exports.AuthClient = AuthClient; /***/ }), /***/ 1261: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. var __classPrivateFieldGet = (this && this.__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); }; var _a, _AwsClient_DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AwsClient = void 0; const awsrequestsigner_1 = __nccwpck_require__(7647); const baseexternalclient_1 = __nccwpck_require__(142); const defaultawssecuritycredentialssupplier_1 = __nccwpck_require__(9157); const util_1 = __nccwpck_require__(7870); /** * AWS external account client. This is used for AWS workloads, where * AWS STS GetCallerIdentity serialized signed requests are exchanged for * GCP access token. */ class AwsClient extends baseexternalclient_1.BaseExternalAccountClient { /** * Instantiates an AwsClient instance using the provided JSON * object loaded from an external account credentials file. * An error is thrown if the credential is not a valid AWS credential. * @param options The external account options object typically loaded * from the external account JSON credential file. * @param additionalOptions **DEPRECATED, all options are available in the * `options` parameter.** Optional additional behavior customization options. * These currently customize expiration threshold time and whether to retry * on 401/403 API request errors. */ constructor(options, additionalOptions) { super(options, additionalOptions); const opts = (0, util_1.originalOrCamelOptions)(options); const credentialSource = opts.get('credential_source'); const awsSecurityCredentialsSupplier = opts.get('aws_security_credentials_supplier'); // Validate credential sourcing configuration. if (!credentialSource && !awsSecurityCredentialsSupplier) { throw new Error('A credential source or AWS security credentials supplier must be specified.'); } if (credentialSource && awsSecurityCredentialsSupplier) { throw new Error('Only one of credential source or AWS security credentials supplier can be specified.'); } if (awsSecurityCredentialsSupplier) { this.awsSecurityCredentialsSupplier = awsSecurityCredentialsSupplier; this.regionalCredVerificationUrl = __classPrivateFieldGet(_a, _a, "f", _AwsClient_DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL); this.credentialSourceType = 'programmatic'; } else { const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource); this.environmentId = credentialSourceOpts.get('environment_id'); // This is only required if the AWS region is not available in the // AWS_REGION or AWS_DEFAULT_REGION environment variables. const regionUrl = credentialSourceOpts.get('region_url'); // This is only required if AWS security credentials are not available in // environment variables. const securityCredentialsUrl = credentialSourceOpts.get('url'); const imdsV2SessionTokenUrl = credentialSourceOpts.get('imdsv2_session_token_url'); this.awsSecurityCredentialsSupplier = new defaultawssecuritycredentialssupplier_1.DefaultAwsSecurityCredentialsSupplier({ regionUrl: regionUrl, securityCredentialsUrl: securityCredentialsUrl, imdsV2SessionTokenUrl: imdsV2SessionTokenUrl, }); this.regionalCredVerificationUrl = credentialSourceOpts.get('regional_cred_verification_url'); this.credentialSourceType = 'aws'; // Data validators. this.validateEnvironmentId(); } this.awsRequestSigner = null; this.region = ''; } validateEnvironmentId() { var _b; const match = (_b = this.environmentId) === null || _b === void 0 ? void 0 : _b.match(/^(aws)(\d+)$/); if (!match || !this.regionalCredVerificationUrl) { throw new Error('No valid AWS "credential_source" provided'); } else if (parseInt(match[2], 10) !== 1) { throw new Error(`aws version "${match[2]}" is not supported in the current build.`); } } /** * Triggered when an external subject token is needed to be exchanged for a * GCP access token via GCP STS endpoint. This will call the * {@link AwsSecurityCredentialsSupplier} to retrieve an AWS region and AWS * Security Credentials, then use them to create a signed AWS STS request that * can be exchanged for a GCP access token. * @return A promise that resolves with the external subject token. */ async retrieveSubjectToken() { // Initialize AWS request signer if not already initialized. if (!this.awsRequestSigner) { this.region = await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext); this.awsRequestSigner = new awsrequestsigner_1.AwsRequestSigner(async () => { return this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext); }, this.region); } // Generate signed request to AWS STS GetCallerIdentity API. // Use the required regional endpoint. Otherwise, the request will fail. const options = await this.awsRequestSigner.getRequestOptions({ ..._a.RETRY_CONFIG, url: this.regionalCredVerificationUrl.replace('{region}', this.region), method: 'POST', }); // The GCP STS endpoint expects the headers to be formatted as: // [ // {key: 'x-amz-date', value: '...'}, // {key: 'Authorization', value: '...'}, // ... // ] // And then serialized as: // encodeURIComponent(JSON.stringify({ // url: '...', // method: 'POST', // headers: [{key: 'x-amz-date', value: '...'}, ...] // })) const reformattedHeader = []; const extendedHeaders = Object.assign({ // The full, canonical resource name of the workload identity pool // provider, with or without the HTTPS prefix. // Including this header as part of the signature is recommended to // ensure data integrity. 'x-goog-cloud-target-resource': this.audience, }, options.headers); // Reformat header to GCP STS expected format. for (const key in extendedHeaders) { reformattedHeader.push({ key, value: extendedHeaders[key], }); } // Serialize the reformatted signed request. return encodeURIComponent(JSON.stringify({ url: options.url, method: options.method, headers: reformattedHeader, })); } } exports.AwsClient = AwsClient; _a = AwsClient; _AwsClient_DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL = { value: 'https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15' }; /** * @deprecated AWS client no validates the EC2 metadata address. **/ AwsClient.AWS_EC2_METADATA_IPV4_ADDRESS = '169.254.169.254'; /** * @deprecated AWS client no validates the EC2 metadata address. **/ AwsClient.AWS_EC2_METADATA_IPV6_ADDRESS = 'fd00:ec2::254'; /***/ }), /***/ 7647: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AwsRequestSigner = void 0; const crypto_1 = __nccwpck_require__(8851); /** AWS Signature Version 4 signing algorithm identifier. */ const AWS_ALGORITHM = 'AWS4-HMAC-SHA256'; /** * The termination string for the AWS credential scope value as defined in * https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html */ const AWS_REQUEST_TYPE = 'aws4_request'; /** * Implements an AWS API request signer based on the AWS Signature Version 4 * signing process. * https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html */ class AwsRequestSigner { /** * Instantiates an AWS API request signer used to send authenticated signed * requests to AWS APIs based on the AWS Signature Version 4 signing process. * This also provides a mechanism to generate the signed request without * sending it. * @param getCredentials A mechanism to retrieve AWS security credentials * when needed. * @param region The AWS region to use. */ constructor(getCredentials, region) { this.getCredentials = getCredentials; this.region = region; this.crypto = (0, crypto_1.createCrypto)(); } /** * Generates the signed request for the provided HTTP request for calling * an AWS API. This follows the steps described at: * https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html * @param amzOptions The AWS request options that need to be signed. * @return A promise that resolves with the GaxiosOptions containing the * signed HTTP request parameters. */ async getRequestOptions(amzOptions) { if (!amzOptions.url) { throw new Error('"url" is required in "amzOptions"'); } // Stringify JSON requests. This will be set in the request body of the // generated signed request. const requestPayloadData = typeof amzOptions.data === 'object' ? JSON.stringify(amzOptions.data) : amzOptions.data; const url = amzOptions.url; const method = amzOptions.method || 'GET'; const requestPayload = amzOptions.body || requestPayloadData; const additionalAmzHeaders = amzOptions.headers; const awsSecurityCredentials = await this.getCredentials(); const uri = new URL(url); const headerMap = await generateAuthenticationHeaderMap({ crypto: this.crypto, host: uri.host, canonicalUri: uri.pathname, canonicalQuerystring: uri.search.substr(1), method, region: this.region, securityCredentials: awsSecurityCredentials, requestPayload, additionalAmzHeaders, }); // Append additional optional headers, eg. X-Amz-Target, Content-Type, etc. const headers = Object.assign( // Add x-amz-date if available. headerMap.amzDate ? { 'x-amz-date': headerMap.amzDate } : {}, { Authorization: headerMap.authorizationHeader, host: uri.host, }, additionalAmzHeaders || {}); if (awsSecurityCredentials.token) { Object.assign(headers, { 'x-amz-security-token': awsSecurityCredentials.token, }); } const awsSignedReq = { url, method: method, headers, }; if (typeof requestPayload !== 'undefined') { awsSignedReq.body = requestPayload; } return awsSignedReq; } } exports.AwsRequestSigner = AwsRequestSigner; /** * Creates the HMAC-SHA256 hash of the provided message using the * provided key. * * @param crypto The crypto instance used to facilitate cryptographic * operations. * @param key The HMAC-SHA256 key to use. * @param msg The message to hash. * @return The computed hash bytes. */ async function sign(crypto, key, msg) { return await crypto.signWithHmacSha256(key, msg); } /** * Calculates the signing key used to calculate the signature for * AWS Signature Version 4 based on: * https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html * * @param crypto The crypto instance used to facilitate cryptographic * operations. * @param key The AWS secret access key. * @param dateStamp The '%Y%m%d' date format. * @param region The AWS region. * @param serviceName The AWS service name, eg. sts. * @return The signing key bytes. */ async function getSigningKey(crypto, key, dateStamp, region, serviceName) { const kDate = await sign(crypto, `AWS4${key}`, dateStamp); const kRegion = await sign(crypto, kDate, region); const kService = await sign(crypto, kRegion, serviceName); const kSigning = await sign(crypto, kService, 'aws4_request'); return kSigning; } /** * Generates the authentication header map needed for generating the AWS * Signature Version 4 signed request. * * @param option The options needed to compute the authentication header map. * @return The AWS authentication header map which constitutes of the following * components: amz-date, authorization header and canonical query string. */ async function generateAuthenticationHeaderMap(options) { const additionalAmzHeaders = options.additionalAmzHeaders || {}; const requestPayload = options.requestPayload || ''; // iam.amazonaws.com host => iam service. // sts.us-east-2.amazonaws.com => sts service. const serviceName = options.host.split('.')[0]; const now = new Date(); // Format: '%Y%m%dT%H%M%SZ'. const amzDate = now .toISOString() .replace(/[-:]/g, '') .replace(/\.[0-9]+/, ''); // Format: '%Y%m%d'. const dateStamp = now.toISOString().replace(/[-]/g, '').replace(/T.*/, ''); // Change all additional headers to be lower case. const reformattedAdditionalAmzHeaders = {}; Object.keys(additionalAmzHeaders).forEach(key => { reformattedAdditionalAmzHeaders[key.toLowerCase()] = additionalAmzHeaders[key]; }); // Add AWS token if available. if (options.securityCredentials.token) { reformattedAdditionalAmzHeaders['x-amz-security-token'] = options.securityCredentials.token; } // Header keys need to be sorted alphabetically. const amzHeaders = Object.assign({ host: options.host, }, // Previously the date was not fixed with x-amz- and could be provided manually. // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-header-value-trim.req reformattedAdditionalAmzHeaders.date ? {} : { 'x-amz-date': amzDate }, reformattedAdditionalAmzHeaders); let canonicalHeaders = ''; const signedHeadersList = Object.keys(amzHeaders).sort(); signedHeadersList.forEach(key => { canonicalHeaders += `${key}:${amzHeaders[key]}\n`; }); const signedHeaders = signedHeadersList.join(';'); const payloadHash = await options.crypto.sha256DigestHex(requestPayload); // https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html const canonicalRequest = `${options.method}\n` + `${options.canonicalUri}\n` + `${options.canonicalQuerystring}\n` + `${canonicalHeaders}\n` + `${signedHeaders}\n` + `${payloadHash}`; const credentialScope = `${dateStamp}/${options.region}/${serviceName}/${AWS_REQUEST_TYPE}`; // https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html const stringToSign = `${AWS_ALGORITHM}\n` + `${amzDate}\n` + `${credentialScope}\n` + (await options.crypto.sha256DigestHex(canonicalRequest)); // https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html const signingKey = await getSigningKey(options.crypto, options.securityCredentials.secretAccessKey, dateStamp, options.region, serviceName); const signature = await sign(options.crypto, signingKey, stringToSign); // https://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html const authorizationHeader = `${AWS_ALGORITHM} Credential=${options.securityCredentials.accessKeyId}/` + `${credentialScope}, SignedHeaders=${signedHeaders}, ` + `Signature=${(0, crypto_1.fromArrayBufferToHex)(signature)}`; return { // Do not return x-amz-date if date is available. amzDate: reformattedAdditionalAmzHeaders.date ? undefined : amzDate, authorizationHeader, canonicalQuerystring: options.canonicalQuerystring, }; } /***/ }), /***/ 142: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. var __classPrivateFieldGet = (this && this.__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); }; var __classPrivateFieldSet = (this && this.__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; }; var _BaseExternalAccountClient_instances, _BaseExternalAccountClient_pendingAccessToken, _BaseExternalAccountClient_internalRefreshAccessTokenAsync; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BaseExternalAccountClient = exports.DEFAULT_UNIVERSE = exports.CLOUD_RESOURCE_MANAGER = exports.EXTERNAL_ACCOUNT_TYPE = exports.EXPIRATION_TIME_OFFSET = void 0; const stream = __nccwpck_require__(2203); const authclient_1 = __nccwpck_require__(4810); const sts = __nccwpck_require__(121); const util_1 = __nccwpck_require__(7870); /** * The required token exchange grant_type: rfc8693#section-2.1 */ const STS_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange'; /** * The requested token exchange requested_token_type: rfc8693#section-2.1 */ const STS_REQUEST_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token'; /** The default OAuth scope to request when none is provided. */ const DEFAULT_OAUTH_SCOPE = 'https://www.googleapis.com/auth/cloud-platform'; /** Default impersonated token lifespan in seconds.*/ const DEFAULT_TOKEN_LIFESPAN = 3600; /** * Offset to take into account network delays and server clock skews. */ exports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000; /** * The credentials JSON file type for external account clients. * There are 3 types of JSON configs: * 1. authorized_user => Google end user credential * 2. service_account => Google service account credential * 3. external_Account => non-GCP service (eg. AWS, Azure, K8s) */ exports.EXTERNAL_ACCOUNT_TYPE = 'external_account'; /** * Cloud resource manager URL used to retrieve project information. * * @deprecated use {@link BaseExternalAccountClient.cloudResourceManagerURL} instead **/ exports.CLOUD_RESOURCE_MANAGER = 'https://cloudresourcemanager.googleapis.com/v1/projects/'; /** The workforce audience pattern. */ const WORKFORCE_AUDIENCE_PATTERN = '//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+'; const DEFAULT_TOKEN_URL = 'https://sts.{universeDomain}/v1/token'; // eslint-disable-next-line @typescript-eslint/no-var-requires const pkg = __nccwpck_require__(6066); /** * For backwards compatibility. */ var authclient_2 = __nccwpck_require__(4810); Object.defineProperty(exports, "DEFAULT_UNIVERSE", ({ enumerable: true, get: function () { return authclient_2.DEFAULT_UNIVERSE; } })); /** * Base external account client. This is used to instantiate AuthClients for * exchanging external account credentials for GCP access token and authorizing * requests to GCP APIs. * The base class implements common logic for exchanging various type of * external credentials for GCP access token. The logic of determining and * retrieving the external credential based on the environment and * credential_source will be left for the subclasses. */ class BaseExternalAccountClient extends authclient_1.AuthClient { /** * Instantiate a BaseExternalAccountClient instance using the provided JSON * object loaded from an external account credentials file. * @param options The external account options object typically loaded * from the external account JSON credential file. The camelCased options * are aliases for the snake_cased options. * @param additionalOptions **DEPRECATED, all options are available in the * `options` parameter.** Optional additional behavior customization options. * These currently customize expiration threshold time and whether to retry * on 401/403 API request errors. */ constructor(options, additionalOptions) { var _a; super({ ...options, ...additionalOptions }); _BaseExternalAccountClient_instances.add(this); /** * A pending access token request. Used for concurrent calls. */ _BaseExternalAccountClient_pendingAccessToken.set(this, null); const opts = (0, util_1.originalOrCamelOptions)(options); const type = opts.get('type'); if (type && type !== exports.EXTERNAL_ACCOUNT_TYPE) { throw new Error(`Expected "${exports.EXTERNAL_ACCOUNT_TYPE}" type but ` + `received "${options.type}"`); } const clientId = opts.get('client_id'); const clientSecret = opts.get('client_secret'); const tokenUrl = (_a = opts.get('token_url')) !== null && _a !== void 0 ? _a : DEFAULT_TOKEN_URL.replace('{universeDomain}', this.universeDomain); const subjectTokenType = opts.get('subject_token_type'); const workforcePoolUserProject = opts.get('workforce_pool_user_project'); const serviceAccountImpersonationUrl = opts.get('service_account_impersonation_url'); const serviceAccountImpersonation = opts.get('service_account_impersonation'); const serviceAccountImpersonationLifetime = (0, util_1.originalOrCamelOptions)(serviceAccountImpersonation).get('token_lifetime_seconds'); this.cloudResourceManagerURL = new URL(opts.get('cloud_resource_manager_url') || `https://cloudresourcemanager.${this.universeDomain}/v1/projects/`); if (clientId) { this.clientAuth = { confidentialClientType: 'basic', clientId, clientSecret, }; } this.stsCredential = new sts.StsCredentials(tokenUrl, this.clientAuth); this.scopes = opts.get('scopes') || [DEFAULT_OAUTH_SCOPE]; this.cachedAccessToken = null; this.audience = opts.get('audience'); this.subjectTokenType = subjectTokenType; this.workforcePoolUserProject = workforcePoolUserProject; const workforceAudiencePattern = new RegExp(WORKFORCE_AUDIENCE_PATTERN); if (this.workforcePoolUserProject && !this.audience.match(workforceAudiencePattern)) { throw new Error('workforcePoolUserProject should not be set for non-workforce pool ' + 'credentials.'); } this.serviceAccountImpersonationUrl = serviceAccountImpersonationUrl; this.serviceAccountImpersonationLifetime = serviceAccountImpersonationLifetime; if (this.serviceAccountImpersonationLifetime) { this.configLifetimeRequested = true; } else { this.configLifetimeRequested = false; this.serviceAccountImpersonationLifetime = DEFAULT_TOKEN_LIFESPAN; } this.projectNumber = this.getProjectNumber(this.audience); this.supplierContext = { audience: this.audience, subjectTokenType: this.subjectTokenType, transporter: this.transporter, }; } /** The service account email to be impersonated, if available. */ getServiceAccountEmail() { var _a; if (this.serviceAccountImpersonationUrl) { if (this.serviceAccountImpersonationUrl.length > 256) { /** * Prevents DOS attacks. * @see {@link https://github.com/googleapis/google-auth-library-nodejs/security/code-scanning/84} **/ throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`); } // Parse email from URL. The formal looks as follows: // https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/name@project-id.iam.gserviceaccount.com:generateAccessToken const re = /serviceAccounts\/(?[^:]+):generateAccessToken$/; const result = re.exec(this.serviceAccountImpersonationUrl); return ((_a = result === null || result === void 0 ? void 0 : result.groups) === null || _a === void 0 ? void 0 : _a.email) || null; } return null; } /** * Provides a mechanism to inject GCP access tokens directly. * When the provided credential expires, a new credential, using the * external account options, is retrieved. * @param credentials The Credentials object to set on the current client. */ setCredentials(credentials) { super.setCredentials(credentials); this.cachedAccessToken = credentials; } /** * @return A promise that resolves with the current GCP access token * response. If the current credential is expired, a new one is retrieved. */ async getAccessToken() { // If cached access token is unavailable or expired, force refresh. if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) { await this.refreshAccessTokenAsync(); } // Return GCP access token in GetAccessTokenResponse format. return { token: this.cachedAccessToken.access_token, res: this.cachedAccessToken.res, }; } /** * The main authentication interface. It takes an optional url which when * present is the endpoint being accessed, and returns a Promise which * resolves with authorization header fields. * * The result has the form: * { Authorization: 'Bearer ' } */ async getRequestHeaders() { const accessTokenResponse = await this.getAccessToken(); const headers = { Authorization: `Bearer ${accessTokenResponse.token}`, }; return this.addSharedMetadataHeaders(headers); } request(opts, callback) { if (callback) { this.requestAsync(opts).then(r => callback(null, r), e => { return callback(e, e.response); }); } else { return this.requestAsync(opts); } } /** * @return A promise that resolves with the project ID corresponding to the * current workload identity pool or current workforce pool if * determinable. For workforce pool credential, it returns the project ID * corresponding to the workforcePoolUserProject. * This is introduced to match the current pattern of using the Auth * library: * const projectId = await auth.getProjectId(); * const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`; * const res = await client.request({ url }); * The resource may not have permission * (resourcemanager.projects.get) to call this API or the required * scopes may not be selected: * https://cloud.google.com/resource-manager/reference/rest/v1/projects/get#authorization-scopes */ async getProjectId() { const projectNumber = this.projectNumber || this.workforcePoolUserProject; if (this.projectId) { // Return previously determined project ID. return this.projectId; } else if (projectNumber) { // Preferable not to use request() to avoid retrial policies. const headers = await this.getRequestHeaders(); const response = await this.transporter.request({ ...BaseExternalAccountClient.RETRY_CONFIG, headers, url: `${this.cloudResourceManagerURL.toString()}${projectNumber}`, responseType: 'json', }); this.projectId = response.data.projectId; return this.projectId; } return null; } /** * Authenticates the provided HTTP request, processes it and resolves with the * returned response. * @param opts The HTTP request options. * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure. * @return A promise that resolves with the successful response. */ async requestAsync(opts, reAuthRetried = false) { let response; try { const requestHeaders = await this.getRequestHeaders(); opts.headers = opts.headers || {}; if (requestHeaders && requestHeaders['x-goog-user-project']) { opts.headers['x-goog-user-project'] = requestHeaders['x-goog-user-project']; } if (requestHeaders && requestHeaders.Authorization) { opts.headers.Authorization = requestHeaders.Authorization; } response = await this.transporter.request(opts); } catch (e) { const res = e.response; if (res) { const statusCode = res.status; // Retry the request for metadata if the following criteria are true: // - We haven't already retried. It only makes sense to retry once. // - The response was a 401 or a 403 // - The request didn't send a readableStream // - forceRefreshOnFailure is true const isReadableStream = res.config.data instanceof stream.Readable; const isAuthErr = statusCode === 401 || statusCode === 403; if (!reAuthRetried && isAuthErr && !isReadableStream && this.forceRefreshOnFailure) { await this.refreshAccessTokenAsync(); return await this.requestAsync(opts, true); } } throw e; } return response; } /** * Forces token refresh, even if unexpired tokens are currently cached. * External credentials are exchanged for GCP access tokens via the token * exchange endpoint and other settings provided in the client options * object. * If the service_account_impersonation_url is provided, an additional * step to exchange the external account GCP access token for a service * account impersonated token is performed. * @return A promise that resolves with the fresh GCP access tokens. */ async refreshAccessTokenAsync() { // Use an existing access token request, or cache a new one __classPrivateFieldSet(this, _BaseExternalAccountClient_pendingAccessToken, __classPrivateFieldGet(this, _BaseExternalAccountClient_pendingAccessToken, "f") || __classPrivateFieldGet(this, _BaseExternalAccountClient_instances, "m", _BaseExternalAccountClient_internalRefreshAccessTokenAsync).call(this), "f"); try { return await __classPrivateFieldGet(this, _BaseExternalAccountClient_pendingAccessToken, "f"); } finally { // clear pending access token for future requests __classPrivateFieldSet(this, _BaseExternalAccountClient_pendingAccessToken, null, "f"); } } /** * Returns the workload identity pool project number if it is determinable * from the audience resource name. * @param audience The STS audience used to determine the project number. * @return The project number associated with the workload identity pool, if * this can be determined from the STS audience field. Otherwise, null is * returned. */ getProjectNumber(audience) { // STS audience pattern: // //iam.googleapis.com/projects/$PROJECT_NUMBER/locations/... const match = audience.match(/\/projects\/([^/]+)/); if (!match) { return null; } return match[1]; } /** * Exchanges an external account GCP access token for a service * account impersonated access token using iamcredentials * GenerateAccessToken API. * @param token The access token to exchange for a service account access * token. * @return A promise that resolves with the service account impersonated * credentials response. */ async getImpersonatedAccessToken(token) { const opts = { ...BaseExternalAccountClient.RETRY_CONFIG, url: this.serviceAccountImpersonationUrl, method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}`, }, data: { scope: this.getScopesArray(), lifetime: this.serviceAccountImpersonationLifetime + 's', }, responseType: 'json', }; const response = await this.transporter.request(opts); const successResponse = response.data; return { access_token: successResponse.accessToken, // Convert from ISO format to timestamp. expiry_date: new Date(successResponse.expireTime).getTime(), res: response, }; } /** * Returns whether the provided credentials are expired or not. * If there is no expiry time, assumes the token is not expired or expiring. * @param accessToken The credentials to check for expiration. * @return Whether the credentials are expired or not. */ isExpired(accessToken) { const now = new Date().getTime(); return accessToken.expiry_date ? now >= accessToken.expiry_date - this.eagerRefreshThresholdMillis : false; } /** * @return The list of scopes for the requested GCP access token. */ getScopesArray() { // Since scopes can be provided as string or array, the type should // be normalized. if (typeof this.scopes === 'string') { return [this.scopes]; } return this.scopes || [DEFAULT_OAUTH_SCOPE]; } getMetricsHeaderValue() { const nodeVersion = process.version.replace(/^v/, ''); const saImpersonation = this.serviceAccountImpersonationUrl !== undefined; const credentialSourceType = this.credentialSourceType ? this.credentialSourceType : 'unknown'; return `gl-node/${nodeVersion} auth/${pkg.version} google-byoid-sdk source/${credentialSourceType} sa-impersonation/${saImpersonation} config-lifetime/${this.configLifetimeRequested}`; } } exports.BaseExternalAccountClient = BaseExternalAccountClient; _BaseExternalAccountClient_pendingAccessToken = new WeakMap(), _BaseExternalAccountClient_instances = new WeakSet(), _BaseExternalAccountClient_internalRefreshAccessTokenAsync = async function _BaseExternalAccountClient_internalRefreshAccessTokenAsync() { // Retrieve the external credential. const subjectToken = await this.retrieveSubjectToken(); // Construct the STS credentials options. const stsCredentialsOptions = { grantType: STS_GRANT_TYPE, audience: this.audience, requestedTokenType: STS_REQUEST_TOKEN_TYPE, subjectToken, subjectTokenType: this.subjectTokenType, // generateAccessToken requires the provided access token to have // scopes: // https://www.googleapis.com/auth/iam or // https://www.googleapis.com/auth/cloud-platform // The new service account access token scopes will match the user // provided ones. scope: this.serviceAccountImpersonationUrl ? [DEFAULT_OAUTH_SCOPE] : this.getScopesArray(), }; // Exchange the external credentials for a GCP access token. // Client auth is prioritized over passing the workforcePoolUserProject // parameter for STS token exchange. const additionalOptions = !this.clientAuth && this.workforcePoolUserProject ? { userProject: this.workforcePoolUserProject } : undefined; const additionalHeaders = { 'x-goog-api-client': this.getMetricsHeaderValue(), }; const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, additionalHeaders, additionalOptions); if (this.serviceAccountImpersonationUrl) { this.cachedAccessToken = await this.getImpersonatedAccessToken(stsResponse.access_token); } else if (stsResponse.expires_in) { // Save response in cached access token. this.cachedAccessToken = { access_token: stsResponse.access_token, expiry_date: new Date().getTime() + stsResponse.expires_in * 1000, res: stsResponse.res, }; } else { // Save response in cached access token. this.cachedAccessToken = { access_token: stsResponse.access_token, res: stsResponse.res, }; } // Save credentials. this.credentials = {}; Object.assign(this.credentials, this.cachedAccessToken); delete this.credentials.res; // Trigger tokens event to notify external listeners. this.emit('tokens', { refresh_token: null, expiry_date: this.cachedAccessToken.expiry_date, access_token: this.cachedAccessToken.access_token, token_type: 'Bearer', id_token: null, }); // Return the cached access token. return this.cachedAccessToken; }; /***/ }), /***/ 977: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright 2013 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Compute = void 0; const gaxios_1 = __nccwpck_require__(7003); const gcpMetadata = __nccwpck_require__(3046); const oauth2client_1 = __nccwpck_require__(91); class Compute extends oauth2client_1.OAuth2Client { /** * Google Compute Engine service account credentials. * * Retrieve access token from the metadata server. * See: https://cloud.google.com/compute/docs/access/authenticate-workloads#applications */ constructor(options = {}) { super(options); // Start with an expired refresh token, which will automatically be // refreshed before the first API call is made. this.credentials = { expiry_date: 1, refresh_token: 'compute-placeholder' }; this.serviceAccountEmail = options.serviceAccountEmail || 'default'; this.scopes = Array.isArray(options.scopes) ? options.scopes : options.scopes ? [options.scopes] : []; } /** * Refreshes the access token. * @param refreshToken Unused parameter */ async refreshTokenNoCache( // eslint-disable-next-line @typescript-eslint/no-unused-vars refreshToken) { const tokenPath = `service-accounts/${this.serviceAccountEmail}/token`; let data; try { const instanceOptions = { property: tokenPath, }; if (this.scopes.length > 0) { instanceOptions.params = { scopes: this.scopes.join(','), }; } data = await gcpMetadata.instance(instanceOptions); } catch (e) { if (e instanceof gaxios_1.GaxiosError) { e.message = `Could not refresh access token: ${e.message}`; this.wrapError(e); } throw e; } const tokens = data; if (data && data.expires_in) { tokens.expiry_date = new Date().getTime() + data.expires_in * 1000; delete tokens.expires_in; } this.emit('tokens', tokens); return { tokens, res: null }; } /** * Fetches an ID token. * @param targetAudience the audience for the fetched ID token. */ async fetchIdToken(targetAudience) { const idTokenPath = `service-accounts/${this.serviceAccountEmail}/identity` + `?format=full&audience=${targetAudience}`; let idToken; try { const instanceOptions = { property: idTokenPath, }; idToken = await gcpMetadata.instance(instanceOptions); } catch (e) { if (e instanceof Error) { e.message = `Could not fetch ID token: ${e.message}`; } throw e; } return idToken; } wrapError(e) { const res = e.response; if (res && res.status) { e.status = res.status; if (res.status === 403) { e.message = 'A Forbidden error was returned while attempting to retrieve an access ' + 'token for the Compute Engine built-in service account. This may be because the Compute ' + 'Engine instance does not have the correct permission scopes specified: ' + e.message; } else if (res.status === 404) { e.message = 'A Not Found error was returned while attempting to retrieve an access' + 'token for the Compute Engine built-in service account. This may be because the Compute ' + 'Engine instance does not have any permission scopes specified: ' + e.message; } } } } exports.Compute = Compute; /***/ }), /***/ 9157: /***/ (function(__unused_webpack_module, exports) { "use strict"; // Copyright 2024 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. var __classPrivateFieldGet = (this && this.__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); }; var _DefaultAwsSecurityCredentialsSupplier_instances, _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken, _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName, _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials, _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get, _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DefaultAwsSecurityCredentialsSupplier = void 0; /** * Internal AWS security credentials supplier implementation used by {@link AwsClient} * when a credential source is provided instead of a user defined supplier. * The logic is summarized as: * 1. If imdsv2_session_token_url is provided in the credential source, then * fetch the aws session token and include it in the headers of the * metadata requests. This is a requirement for IDMSv2 but optional * for IDMSv1. * 2. Retrieve AWS region from availability-zone. * 3a. Check AWS credentials in environment variables. If not found, get * from security-credentials endpoint. * 3b. Get AWS credentials from security-credentials endpoint. In order * to retrieve this, the AWS role needs to be determined by calling * security-credentials endpoint without any argument. Then the * credentials can be retrieved via: security-credentials/role_name * 4. Generate the signed request to AWS STS GetCallerIdentity action. * 5. Inject x-goog-cloud-target-resource into header and serialize the * signed request. This will be the subject-token to pass to GCP STS. */ class DefaultAwsSecurityCredentialsSupplier { /** * Instantiates a new DefaultAwsSecurityCredentialsSupplier using information * from the credential_source stored in the ADC file. * @param opts The default aws security credentials supplier options object to * build the supplier with. */ constructor(opts) { _DefaultAwsSecurityCredentialsSupplier_instances.add(this); this.regionUrl = opts.regionUrl; this.securityCredentialsUrl = opts.securityCredentialsUrl; this.imdsV2SessionTokenUrl = opts.imdsV2SessionTokenUrl; this.additionalGaxiosOptions = opts.additionalGaxiosOptions; } /** * Returns the active AWS region. This first checks to see if the region * is available as an environment variable. If it is not, then the supplier * will call the region URL. * @param context {@link ExternalAccountSupplierContext} from the calling * {@link AwsClient}, contains the requested audience and subject token type * for the external account identity. * @return A promise that resolves with the AWS region string. */ async getAwsRegion(context) { // Priority order for region determination: // AWS_REGION > AWS_DEFAULT_REGION > metadata server. if (__classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get)) { return __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get); } const metadataHeaders = {}; if (!__classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get) && this.imdsV2SessionTokenUrl) { metadataHeaders['x-aws-ec2-metadata-token'] = await __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken).call(this, context.transporter); } if (!this.regionUrl) { throw new Error('Unable to determine AWS region due to missing ' + '"options.credential_source.region_url"'); } const opts = { ...this.additionalGaxiosOptions, url: this.regionUrl, method: 'GET', responseType: 'text', headers: metadataHeaders, }; const response = await context.transporter.request(opts); // Remove last character. For example, if us-east-2b is returned, // the region would be us-east-2. return response.data.substr(0, response.data.length - 1); } /** * Returns AWS security credentials. This first checks to see if the credentials * is available as environment variables. If it is not, then the supplier * will call the security credentials URL. * @param context {@link ExternalAccountSupplierContext} from the calling * {@link AwsClient}, contains the requested audience and subject token type * for the external account identity. * @return A promise that resolves with the AWS security credentials. */ async getAwsSecurityCredentials(context) { // Check environment variables for permanent credentials first. // https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html if (__classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get)) { return __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get); } const metadataHeaders = {}; if (this.imdsV2SessionTokenUrl) { metadataHeaders['x-aws-ec2-metadata-token'] = await __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken).call(this, context.transporter); } // Since the role on a VM can change, we don't need to cache it. const roleName = await __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName).call(this, metadataHeaders, context.transporter); // Temporary credentials typically last for several hours. // Expiration is returned in response. // Consider future optimization of this logic to cache AWS tokens // until their natural expiration. const awsCreds = await __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials).call(this, roleName, metadataHeaders, context.transporter); return { accessKeyId: awsCreds.AccessKeyId, secretAccessKey: awsCreds.SecretAccessKey, token: awsCreds.Token, }; } } exports.DefaultAwsSecurityCredentialsSupplier = DefaultAwsSecurityCredentialsSupplier; _DefaultAwsSecurityCredentialsSupplier_instances = new WeakSet(), _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken = /** * @param transporter The transporter to use for requests. * @return A promise that resolves with the IMDSv2 Session Token. */ async function _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken(transporter) { const opts = { ...this.additionalGaxiosOptions, url: this.imdsV2SessionTokenUrl, method: 'PUT', responseType: 'text', headers: { 'x-aws-ec2-metadata-token-ttl-seconds': '300' }, }; const response = await transporter.request(opts); return response.data; }, _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName = /** * @param headers The headers to be used in the metadata request. * @param transporter The transporter to use for requests. * @return A promise that resolves with the assigned role to the current * AWS VM. This is needed for calling the security-credentials endpoint. */ async function _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName(headers, transporter) { if (!this.securityCredentialsUrl) { throw new Error('Unable to determine AWS role name due to missing ' + '"options.credential_source.url"'); } const opts = { ...this.additionalGaxiosOptions, url: this.securityCredentialsUrl, method: 'GET', responseType: 'text', headers: headers, }; const response = await transporter.request(opts); return response.data; }, _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials = /** * Retrieves the temporary AWS credentials by calling the security-credentials * endpoint as specified in the `credential_source` object. * @param roleName The role attached to the current VM. * @param headers The headers to be used in the metadata request. * @param transporter The transporter to use for requests. * @return A promise that resolves with the temporary AWS credentials * needed for creating the GetCallerIdentity signed request. */ async function _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials(roleName, headers, transporter) { const response = await transporter.request({ ...this.additionalGaxiosOptions, url: `${this.securityCredentialsUrl}/${roleName}`, responseType: 'json', headers: headers, }); return response.data; }, _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get = function _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get() { // The AWS region can be provided through AWS_REGION or AWS_DEFAULT_REGION. // Only one is required. return (process.env['AWS_REGION'] || process.env['AWS_DEFAULT_REGION'] || null); }, _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get = function _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get() { // Both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are required. if (process.env['AWS_ACCESS_KEY_ID'] && process.env['AWS_SECRET_ACCESS_KEY']) { return { accessKeyId: process.env['AWS_ACCESS_KEY_ID'], secretAccessKey: process.env['AWS_SECRET_ACCESS_KEY'], token: process.env['AWS_SESSION_TOKEN'], }; } return null; }; /***/ }), /***/ 7556: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DownscopedClient = exports.EXPIRATION_TIME_OFFSET = exports.MAX_ACCESS_BOUNDARY_RULES_COUNT = void 0; const stream = __nccwpck_require__(2203); const authclient_1 = __nccwpck_require__(4810); const sts = __nccwpck_require__(121); /** * The required token exchange grant_type: rfc8693#section-2.1 */ const STS_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange'; /** * The requested token exchange requested_token_type: rfc8693#section-2.1 */ const STS_REQUEST_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token'; /** * The requested token exchange subject_token_type: rfc8693#section-2.1 */ const STS_SUBJECT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token'; /** * The maximum number of access boundary rules a Credential Access Boundary * can contain. */ exports.MAX_ACCESS_BOUNDARY_RULES_COUNT = 10; /** * Offset to take into account network delays and server clock skews. */ exports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000; /** * Defines a set of Google credentials that are downscoped from an existing set * of Google OAuth2 credentials. This is useful to restrict the Identity and * Access Management (IAM) permissions that a short-lived credential can use. * The common pattern of usage is to have a token broker with elevated access * generate these downscoped credentials from higher access source credentials * and pass the downscoped short-lived access tokens to a token consumer via * some secure authenticated channel for limited access to Google Cloud Storage * resources. */ class DownscopedClient extends authclient_1.AuthClient { /** * Instantiates a downscoped client object using the provided source * AuthClient and credential access boundary rules. * To downscope permissions of a source AuthClient, a Credential Access * Boundary that specifies which resources the new credential can access, as * well as an upper bound on the permissions that are available on each * resource, has to be defined. A downscoped client can then be instantiated * using the source AuthClient and the Credential Access Boundary. * @param authClient The source AuthClient to be downscoped based on the * provided Credential Access Boundary rules. * @param credentialAccessBoundary The Credential Access Boundary which * contains a list of access boundary rules. Each rule contains information * on the resource that the rule applies to, the upper bound of the * permissions that are available on that resource and an optional * condition to further restrict permissions. * @param additionalOptions **DEPRECATED, set this in the provided `authClient`.** * Optional additional behavior customization options. * @param quotaProjectId **DEPRECATED, set this in the provided `authClient`.** * Optional quota project id for setting up in the x-goog-user-project header. */ constructor(authClient, credentialAccessBoundary, additionalOptions, quotaProjectId) { super({ ...additionalOptions, quotaProjectId }); this.authClient = authClient; this.credentialAccessBoundary = credentialAccessBoundary; // Check 1-10 Access Boundary Rules are defined within Credential Access // Boundary. if (credentialAccessBoundary.accessBoundary.accessBoundaryRules.length === 0) { throw new Error('At least one access boundary rule needs to be defined.'); } else if (credentialAccessBoundary.accessBoundary.accessBoundaryRules.length > exports.MAX_ACCESS_BOUNDARY_RULES_COUNT) { throw new Error('The provided access boundary has more than ' + `${exports.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`); } // Check at least one permission should be defined in each Access Boundary // Rule. for (const rule of credentialAccessBoundary.accessBoundary .accessBoundaryRules) { if (rule.availablePermissions.length === 0) { throw new Error('At least one permission should be defined in access boundary rules.'); } } this.stsCredential = new sts.StsCredentials(`https://sts.${this.universeDomain}/v1/token`); this.cachedDownscopedAccessToken = null; } /** * Provides a mechanism to inject Downscoped access tokens directly. * The expiry_date field is required to facilitate determination of the token * expiration which would make it easier for the token consumer to handle. * @param credentials The Credentials object to set on the current client. */ setCredentials(credentials) { if (!credentials.expiry_date) { throw new Error('The access token expiry_date field is missing in the provided ' + 'credentials.'); } super.setCredentials(credentials); this.cachedDownscopedAccessToken = credentials; } async getAccessToken() { // If the cached access token is unavailable or expired, force refresh. // The Downscoped access token will be returned in // DownscopedAccessTokenResponse format. if (!this.cachedDownscopedAccessToken || this.isExpired(this.cachedDownscopedAccessToken)) { await this.refreshAccessTokenAsync(); } // Return Downscoped access token in DownscopedAccessTokenResponse format. return { token: this.cachedDownscopedAccessToken.access_token, expirationTime: this.cachedDownscopedAccessToken.expiry_date, res: this.cachedDownscopedAccessToken.res, }; } /** * The main authentication interface. It takes an optional url which when * present is the endpoint being accessed, and returns a Promise which * resolves with authorization header fields. * * The result has the form: * { Authorization: 'Bearer ' } */ async getRequestHeaders() { const accessTokenResponse = await this.getAccessToken(); const headers = { Authorization: `Bearer ${accessTokenResponse.token}`, }; return this.addSharedMetadataHeaders(headers); } request(opts, callback) { if (callback) { this.requestAsync(opts).then(r => callback(null, r), e => { return callback(e, e.response); }); } else { return this.requestAsync(opts); } } /** * Authenticates the provided HTTP request, processes it and resolves with the * returned response. * @param opts The HTTP request options. * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure * @return A promise that resolves with the successful response. */ async requestAsync(opts, reAuthRetried = false) { let response; try { const requestHeaders = await this.getRequestHeaders(); opts.headers = opts.headers || {}; if (requestHeaders && requestHeaders['x-goog-user-project']) { opts.headers['x-goog-user-project'] = requestHeaders['x-goog-user-project']; } if (requestHeaders && requestHeaders.Authorization) { opts.headers.Authorization = requestHeaders.Authorization; } response = await this.transporter.request(opts); } catch (e) { const res = e.response; if (res) { const statusCode = res.status; // Retry the request for metadata if the following criteria are true: // - We haven't already retried. It only makes sense to retry once. // - The response was a 401 or a 403 // - The request didn't send a readableStream // - forceRefreshOnFailure is true const isReadableStream = res.config.data instanceof stream.Readable; const isAuthErr = statusCode === 401 || statusCode === 403; if (!reAuthRetried && isAuthErr && !isReadableStream && this.forceRefreshOnFailure) { await this.refreshAccessTokenAsync(); return await this.requestAsync(opts, true); } } throw e; } return response; } /** * Forces token refresh, even if unexpired tokens are currently cached. * GCP access tokens are retrieved from authclient object/source credential. * Then GCP access tokens are exchanged for downscoped access tokens via the * token exchange endpoint. * @return A promise that resolves with the fresh downscoped access token. */ async refreshAccessTokenAsync() { var _a; // Retrieve GCP access token from source credential. const subjectToken = (await this.authClient.getAccessToken()).token; // Construct the STS credentials options. const stsCredentialsOptions = { grantType: STS_GRANT_TYPE, requestedTokenType: STS_REQUEST_TOKEN_TYPE, subjectToken: subjectToken, subjectTokenType: STS_SUBJECT_TOKEN_TYPE, }; // Exchange the source AuthClient access token for a Downscoped access // token. const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, undefined, this.credentialAccessBoundary); /** * The STS endpoint will only return the expiration time for the downscoped * access token if the original access token represents a service account. * The downscoped token's expiration time will always match the source * credential expiration. When no expires_in is returned, we can copy the * source credential's expiration time. */ const sourceCredExpireDate = ((_a = this.authClient.credentials) === null || _a === void 0 ? void 0 : _a.expiry_date) || null; const expiryDate = stsResponse.expires_in ? new Date().getTime() + stsResponse.expires_in * 1000 : sourceCredExpireDate; // Save response in cached access token. this.cachedDownscopedAccessToken = { access_token: stsResponse.access_token, expiry_date: expiryDate, res: stsResponse.res, }; // Save credentials. this.credentials = {}; Object.assign(this.credentials, this.cachedDownscopedAccessToken); delete this.credentials.res; // Trigger tokens event to notify external listeners. this.emit('tokens', { refresh_token: null, expiry_date: this.cachedDownscopedAccessToken.expiry_date, access_token: this.cachedDownscopedAccessToken.access_token, token_type: 'Bearer', id_token: null, }); // Return the cached access token. return this.cachedDownscopedAccessToken; } /** * Returns whether the provided credentials are expired or not. * If there is no expiry time, assumes the token is not expired or expiring. * @param downscopedAccessToken The credentials to check for expiration. * @return Whether the credentials are expired or not. */ isExpired(downscopedAccessToken) { const now = new Date().getTime(); return downscopedAccessToken.expiry_date ? now >= downscopedAccessToken.expiry_date - this.eagerRefreshThresholdMillis : false; } } exports.DownscopedClient = DownscopedClient; /***/ }), /***/ 963: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GCPEnv = void 0; exports.clear = clear; exports.getEnv = getEnv; const gcpMetadata = __nccwpck_require__(3046); var GCPEnv; (function (GCPEnv) { GCPEnv["APP_ENGINE"] = "APP_ENGINE"; GCPEnv["KUBERNETES_ENGINE"] = "KUBERNETES_ENGINE"; GCPEnv["CLOUD_FUNCTIONS"] = "CLOUD_FUNCTIONS"; GCPEnv["COMPUTE_ENGINE"] = "COMPUTE_ENGINE"; GCPEnv["CLOUD_RUN"] = "CLOUD_RUN"; GCPEnv["NONE"] = "NONE"; })(GCPEnv || (exports.GCPEnv = GCPEnv = {})); let envPromise; function clear() { envPromise = undefined; } async function getEnv() { if (envPromise) { return envPromise; } envPromise = getEnvMemoized(); return envPromise; } async function getEnvMemoized() { let env = GCPEnv.NONE; if (isAppEngine()) { env = GCPEnv.APP_ENGINE; } else if (isCloudFunction()) { env = GCPEnv.CLOUD_FUNCTIONS; } else if (await isComputeEngine()) { if (await isKubernetesEngine()) { env = GCPEnv.KUBERNETES_ENGINE; } else if (isCloudRun()) { env = GCPEnv.CLOUD_RUN; } else { env = GCPEnv.COMPUTE_ENGINE; } } else { env = GCPEnv.NONE; } return env; } function isAppEngine() { return !!(process.env.GAE_SERVICE || process.env.GAE_MODULE_NAME); } function isCloudFunction() { return !!(process.env.FUNCTION_NAME || process.env.FUNCTION_TARGET); } /** * This check only verifies that the environment is running knative. * This must be run *after* checking for Kubernetes, otherwise it will * return a false positive. */ function isCloudRun() { return !!process.env.K_CONFIGURATION; } async function isKubernetesEngine() { try { await gcpMetadata.instance('attributes/cluster-name'); return true; } catch (e) { return false; } } async function isComputeEngine() { return gcpMetadata.isAvailable(); } /***/ }), /***/ 3247: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.InvalidSubjectTokenError = exports.InvalidMessageFieldError = exports.InvalidCodeFieldError = exports.InvalidTokenTypeFieldError = exports.InvalidExpirationTimeFieldError = exports.InvalidSuccessFieldError = exports.InvalidVersionFieldError = exports.ExecutableResponseError = exports.ExecutableResponse = void 0; const SAML_SUBJECT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:saml2'; const OIDC_SUBJECT_TOKEN_TYPE1 = 'urn:ietf:params:oauth:token-type:id_token'; const OIDC_SUBJECT_TOKEN_TYPE2 = 'urn:ietf:params:oauth:token-type:jwt'; /** * Defines the response of a 3rd party executable run by the pluggable auth client. */ class ExecutableResponse { /** * Instantiates an ExecutableResponse instance using the provided JSON object * from the output of the executable. * @param responseJson Response from a 3rd party executable, loaded from a * run of the executable or a cached output file. */ constructor(responseJson) { // Check that the required fields exist in the json response. if (!responseJson.version) { throw new InvalidVersionFieldError("Executable response must contain a 'version' field."); } if (responseJson.success === undefined) { throw new InvalidSuccessFieldError("Executable response must contain a 'success' field."); } this.version = responseJson.version; this.success = responseJson.success; // Validate required fields for a successful response. if (this.success) { this.expirationTime = responseJson.expiration_time; this.tokenType = responseJson.token_type; // Validate token type field. if (this.tokenType !== SAML_SUBJECT_TOKEN_TYPE && this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE1 && this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE2) { throw new InvalidTokenTypeFieldError("Executable response must contain a 'token_type' field when successful " + `and it must be one of ${OIDC_SUBJECT_TOKEN_TYPE1}, ${OIDC_SUBJECT_TOKEN_TYPE2}, or ${SAML_SUBJECT_TOKEN_TYPE}.`); } // Validate subject token. if (this.tokenType === SAML_SUBJECT_TOKEN_TYPE) { if (!responseJson.saml_response) { throw new InvalidSubjectTokenError(`Executable response must contain a 'saml_response' field when token_type=${SAML_SUBJECT_TOKEN_TYPE}.`); } this.subjectToken = responseJson.saml_response; } else { if (!responseJson.id_token) { throw new InvalidSubjectTokenError("Executable response must contain a 'id_token' field when " + `token_type=${OIDC_SUBJECT_TOKEN_TYPE1} or ${OIDC_SUBJECT_TOKEN_TYPE2}.`); } this.subjectToken = responseJson.id_token; } } else { // Both code and message must be provided for unsuccessful responses. if (!responseJson.code) { throw new InvalidCodeFieldError("Executable response must contain a 'code' field when unsuccessful."); } if (!responseJson.message) { throw new InvalidMessageFieldError("Executable response must contain a 'message' field when unsuccessful."); } this.errorCode = responseJson.code; this.errorMessage = responseJson.message; } } /** * @return A boolean representing if the response has a valid token. Returns * true when the response was successful and the token is not expired. */ isValid() { return !this.isExpired() && this.success; } /** * @return A boolean representing if the response is expired. Returns true if the * provided timeout has passed. */ isExpired() { return (this.expirationTime !== undefined && this.expirationTime < Math.round(Date.now() / 1000)); } } exports.ExecutableResponse = ExecutableResponse; /** * An error thrown by the ExecutableResponse class. */ class ExecutableResponseError extends Error { constructor(message) { super(message); Object.setPrototypeOf(this, new.target.prototype); } } exports.ExecutableResponseError = ExecutableResponseError; /** * An error thrown when the 'version' field in an executable response is missing or invalid. */ class InvalidVersionFieldError extends ExecutableResponseError { } exports.InvalidVersionFieldError = InvalidVersionFieldError; /** * An error thrown when the 'success' field in an executable response is missing or invalid. */ class InvalidSuccessFieldError extends ExecutableResponseError { } exports.InvalidSuccessFieldError = InvalidSuccessFieldError; /** * An error thrown when the 'expiration_time' field in an executable response is missing or invalid. */ class InvalidExpirationTimeFieldError extends ExecutableResponseError { } exports.InvalidExpirationTimeFieldError = InvalidExpirationTimeFieldError; /** * An error thrown when the 'token_type' field in an executable response is missing or invalid. */ class InvalidTokenTypeFieldError extends ExecutableResponseError { } exports.InvalidTokenTypeFieldError = InvalidTokenTypeFieldError; /** * An error thrown when the 'code' field in an executable response is missing or invalid. */ class InvalidCodeFieldError extends ExecutableResponseError { } exports.InvalidCodeFieldError = InvalidCodeFieldError; /** * An error thrown when the 'message' field in an executable response is missing or invalid. */ class InvalidMessageFieldError extends ExecutableResponseError { } exports.InvalidMessageFieldError = InvalidMessageFieldError; /** * An error thrown when the subject token in an executable response is missing or invalid. */ class InvalidSubjectTokenError extends ExecutableResponseError { } exports.InvalidSubjectTokenError = InvalidSubjectTokenError; /***/ }), /***/ 4240: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright 2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ExternalAccountAuthorizedUserClient = exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = void 0; const authclient_1 = __nccwpck_require__(4810); const oauth2common_1 = __nccwpck_require__(6653); const gaxios_1 = __nccwpck_require__(7003); const stream = __nccwpck_require__(2203); const baseexternalclient_1 = __nccwpck_require__(142); /** * The credentials JSON file type for external account authorized user clients. */ exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = 'external_account_authorized_user'; const DEFAULT_TOKEN_URL = 'https://sts.{universeDomain}/v1/oauthtoken'; /** * Handler for token refresh requests sent to the token_url endpoint for external * authorized user credentials. */ class ExternalAccountAuthorizedUserHandler extends oauth2common_1.OAuthClientAuthHandler { /** * Initializes an ExternalAccountAuthorizedUserHandler instance. * @param url The URL of the token refresh endpoint. * @param transporter The transporter to use for the refresh request. * @param clientAuthentication The client authentication credentials to use * for the refresh request. */ constructor(url, transporter, clientAuthentication) { super(clientAuthentication); this.url = url; this.transporter = transporter; } /** * Requests a new access token from the token_url endpoint using the provided * refresh token. * @param refreshToken The refresh token to use to generate a new access token. * @param additionalHeaders Optional additional headers to pass along the * request. * @return A promise that resolves with the token refresh response containing * the requested access token and its expiration time. */ async refreshToken(refreshToken, additionalHeaders) { const values = new URLSearchParams({ grant_type: 'refresh_token', refresh_token: refreshToken, }); const headers = { 'Content-Type': 'application/x-www-form-urlencoded', ...additionalHeaders, }; const opts = { ...ExternalAccountAuthorizedUserHandler.RETRY_CONFIG, url: this.url, method: 'POST', headers, data: values.toString(), responseType: 'json', }; // Apply OAuth client authentication. this.applyClientAuthenticationOptions(opts); try { const response = await this.transporter.request(opts); // Successful response. const tokenRefreshResponse = response.data; tokenRefreshResponse.res = response; return tokenRefreshResponse; } catch (error) { // Translate error to OAuthError. if (error instanceof gaxios_1.GaxiosError && error.response) { throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data, // Preserve other fields from the original error. error); } // Request could fail before the server responds. throw error; } } } /** * External Account Authorized User Client. This is used for OAuth2 credentials * sourced using external identities through Workforce Identity Federation. * Obtaining the initial access and refresh token can be done through the * Google Cloud CLI. */ class ExternalAccountAuthorizedUserClient extends authclient_1.AuthClient { /** * Instantiates an ExternalAccountAuthorizedUserClient instances using the * provided JSON object loaded from a credentials files. * An error is throws if the credential is not valid. * @param options The external account authorized user option object typically * from the external accoutn authorized user JSON credential file. * @param additionalOptions **DEPRECATED, all options are available in the * `options` parameter.** Optional additional behavior customization options. * These currently customize expiration threshold time and whether to retry * on 401/403 API request errors. */ constructor(options, additionalOptions) { var _a; super({ ...options, ...additionalOptions }); if (options.universe_domain) { this.universeDomain = options.universe_domain; } this.refreshToken = options.refresh_token; const clientAuth = { confidentialClientType: 'basic', clientId: options.client_id, clientSecret: options.client_secret, }; this.externalAccountAuthorizedUserHandler = new ExternalAccountAuthorizedUserHandler((_a = options.token_url) !== null && _a !== void 0 ? _a : DEFAULT_TOKEN_URL.replace('{universeDomain}', this.universeDomain), this.transporter, clientAuth); this.cachedAccessToken = null; this.quotaProjectId = options.quota_project_id; // As threshold could be zero, // eagerRefreshThresholdMillis || EXPIRATION_TIME_OFFSET will override the // zero value. if (typeof (additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.eagerRefreshThresholdMillis) !== 'number') { this.eagerRefreshThresholdMillis = baseexternalclient_1.EXPIRATION_TIME_OFFSET; } else { this.eagerRefreshThresholdMillis = additionalOptions .eagerRefreshThresholdMillis; } this.forceRefreshOnFailure = !!(additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.forceRefreshOnFailure); } async getAccessToken() { // If cached access token is unavailable or expired, force refresh. if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) { await this.refreshAccessTokenAsync(); } // Return GCP access token in GetAccessTokenResponse format. return { token: this.cachedAccessToken.access_token, res: this.cachedAccessToken.res, }; } async getRequestHeaders() { const accessTokenResponse = await this.getAccessToken(); const headers = { Authorization: `Bearer ${accessTokenResponse.token}`, }; return this.addSharedMetadataHeaders(headers); } request(opts, callback) { if (callback) { this.requestAsync(opts).then(r => callback(null, r), e => { return callback(e, e.response); }); } else { return this.requestAsync(opts); } } /** * Authenticates the provided HTTP request, processes it and resolves with the * returned response. * @param opts The HTTP request options. * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure. * @return A promise that resolves with the successful response. */ async requestAsync(opts, reAuthRetried = false) { let response; try { const requestHeaders = await this.getRequestHeaders(); opts.headers = opts.headers || {}; if (requestHeaders && requestHeaders['x-goog-user-project']) { opts.headers['x-goog-user-project'] = requestHeaders['x-goog-user-project']; } if (requestHeaders && requestHeaders.Authorization) { opts.headers.Authorization = requestHeaders.Authorization; } response = await this.transporter.request(opts); } catch (e) { const res = e.response; if (res) { const statusCode = res.status; // Retry the request for metadata if the following criteria are true: // - We haven't already retried. It only makes sense to retry once. // - The response was a 401 or a 403 // - The request didn't send a readableStream // - forceRefreshOnFailure is true const isReadableStream = res.config.data instanceof stream.Readable; const isAuthErr = statusCode === 401 || statusCode === 403; if (!reAuthRetried && isAuthErr && !isReadableStream && this.forceRefreshOnFailure) { await this.refreshAccessTokenAsync(); return await this.requestAsync(opts, true); } } throw e; } return response; } /** * Forces token refresh, even if unexpired tokens are currently cached. * @return A promise that resolves with the refreshed credential. */ async refreshAccessTokenAsync() { // Refresh the access token using the refresh token. const refreshResponse = await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken); this.cachedAccessToken = { access_token: refreshResponse.access_token, expiry_date: new Date().getTime() + refreshResponse.expires_in * 1000, res: refreshResponse.res, }; if (refreshResponse.refresh_token !== undefined) { this.refreshToken = refreshResponse.refresh_token; } return this.cachedAccessToken; } /** * Returns whether the provided credentials are expired or not. * If there is no expiry time, assumes the token is not expired or expiring. * @param credentials The credentials to check for expiration. * @return Whether the credentials are expired or not. */ isExpired(credentials) { const now = new Date().getTime(); return credentials.expiry_date ? now >= credentials.expiry_date - this.eagerRefreshThresholdMillis : false; } } exports.ExternalAccountAuthorizedUserClient = ExternalAccountAuthorizedUserClient; /***/ }), /***/ 8323: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ExternalAccountClient = void 0; const baseexternalclient_1 = __nccwpck_require__(142); const identitypoolclient_1 = __nccwpck_require__(9960); const awsclient_1 = __nccwpck_require__(1261); const pluggable_auth_client_1 = __nccwpck_require__(6077); /** * Dummy class with no constructor. Developers are expected to use fromJSON. */ class ExternalAccountClient { constructor() { throw new Error('ExternalAccountClients should be initialized via: ' + 'ExternalAccountClient.fromJSON(), ' + 'directly via explicit constructors, eg. ' + 'new AwsClient(options), new IdentityPoolClient(options), new' + 'PluggableAuthClientOptions, or via ' + 'new GoogleAuth(options).getClient()'); } /** * This static method will instantiate the * corresponding type of external account credential depending on the * underlying credential source. * @param options The external account options object typically loaded * from the external account JSON credential file. * @param additionalOptions **DEPRECATED, all options are available in the * `options` parameter.** Optional additional behavior customization options. * These currently customize expiration threshold time and whether to retry * on 401/403 API request errors. * @return A BaseExternalAccountClient instance or null if the options * provided do not correspond to an external account credential. */ static fromJSON(options, additionalOptions) { var _a, _b; if (options && options.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) { if ((_a = options.credential_source) === null || _a === void 0 ? void 0 : _a.environment_id) { return new awsclient_1.AwsClient(options, additionalOptions); } else if ((_b = options.credential_source) === null || _b === void 0 ? void 0 : _b.executable) { return new pluggable_auth_client_1.PluggableAuthClient(options, additionalOptions); } else { return new identitypoolclient_1.IdentityPoolClient(options, additionalOptions); } } else { return null; } } } exports.ExternalAccountClient = ExternalAccountClient; /***/ }), /***/ 932: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright 2024 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. var _a, _b, _c; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FileSubjectTokenSupplier = void 0; const util_1 = __nccwpck_require__(9023); const fs = __nccwpck_require__(9896); // fs.readfile is undefined in browser karma tests causing // `npm run browser-test` to fail as test.oauth2.ts imports this file via // src/index.ts. // Fallback to void function to avoid promisify throwing a TypeError. const readFile = (0, util_1.promisify)((_a = fs.readFile) !== null && _a !== void 0 ? _a : (() => { })); const realpath = (0, util_1.promisify)((_b = fs.realpath) !== null && _b !== void 0 ? _b : (() => { })); const lstat = (0, util_1.promisify)((_c = fs.lstat) !== null && _c !== void 0 ? _c : (() => { })); /** * Internal subject token supplier implementation used when a file location * is configured in the credential configuration used to build an {@link IdentityPoolClient} */ class FileSubjectTokenSupplier { /** * Instantiates a new file based subject token supplier. * @param opts The file subject token supplier options to build the supplier * with. */ constructor(opts) { this.filePath = opts.filePath; this.formatType = opts.formatType; this.subjectTokenFieldName = opts.subjectTokenFieldName; } /** * Returns the subject token stored at the file specified in the constructor. * @param context {@link ExternalAccountSupplierContext} from the calling * {@link IdentityPoolClient}, contains the requested audience and subject * token type for the external account identity. Not used. */ async getSubjectToken(context) { // Make sure there is a file at the path. lstatSync will throw if there is // nothing there. let parsedFilePath = this.filePath; try { // Resolve path to actual file in case of symlink. Expect a thrown error // if not resolvable. parsedFilePath = await realpath(parsedFilePath); if (!(await lstat(parsedFilePath)).isFile()) { throw new Error(); } } catch (err) { if (err instanceof Error) { err.message = `The file at ${parsedFilePath} does not exist, or it is not a file. ${err.message}`; } throw err; } let subjectToken; const rawText = await readFile(parsedFilePath, { encoding: 'utf8' }); if (this.formatType === 'text') { subjectToken = rawText; } else if (this.formatType === 'json' && this.subjectTokenFieldName) { const json = JSON.parse(rawText); subjectToken = json[this.subjectTokenFieldName]; } if (!subjectToken) { throw new Error('Unable to parse the subject_token from the credential_source file'); } return subjectToken; } } exports.FileSubjectTokenSupplier = FileSubjectTokenSupplier; /***/ }), /***/ 5934: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. var __classPrivateFieldGet = (this && this.__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); }; var __classPrivateFieldSet = (this && this.__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; }; var _GoogleAuth_instances, _GoogleAuth_pendingAuthClient, _GoogleAuth_prepareAndCacheClient, _GoogleAuth_determineClient; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GoogleAuth = exports.GoogleAuthExceptionMessages = exports.CLOUD_SDK_CLIENT_ID = void 0; const child_process_1 = __nccwpck_require__(5317); const fs = __nccwpck_require__(9896); const gcpMetadata = __nccwpck_require__(3046); const os = __nccwpck_require__(857); const path = __nccwpck_require__(6928); const crypto_1 = __nccwpck_require__(8851); const transporters_1 = __nccwpck_require__(7633); const computeclient_1 = __nccwpck_require__(977); const idtokenclient_1 = __nccwpck_require__(2718); const envDetect_1 = __nccwpck_require__(963); const jwtclient_1 = __nccwpck_require__(5277); const refreshclient_1 = __nccwpck_require__(9807); const impersonated_1 = __nccwpck_require__(9964); const externalclient_1 = __nccwpck_require__(8323); const baseexternalclient_1 = __nccwpck_require__(142); const authclient_1 = __nccwpck_require__(4810); const externalAccountAuthorizedUserClient_1 = __nccwpck_require__(4240); const util_1 = __nccwpck_require__(7870); exports.CLOUD_SDK_CLIENT_ID = '764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com'; exports.GoogleAuthExceptionMessages = { API_KEY_WITH_CREDENTIALS: 'API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.', NO_PROJECT_ID_FOUND: 'Unable to detect a Project Id in the current environment. \n' + 'To learn more about authentication and Google APIs, visit: \n' + 'https://cloud.google.com/docs/authentication/getting-started', NO_CREDENTIALS_FOUND: 'Unable to find credentials in current environment. \n' + 'To learn more about authentication and Google APIs, visit: \n' + 'https://cloud.google.com/docs/authentication/getting-started', NO_ADC_FOUND: 'Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.', NO_UNIVERSE_DOMAIN_FOUND: 'Unable to detect a Universe Domain in the current environment.\n' + 'To learn more about Universe Domain retrieval, visit: \n' + 'https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys', }; class GoogleAuth { // Note: this properly is only public to satisfy unit tests. // https://github.com/Microsoft/TypeScript/issues/5228 get isGCE() { return this.checkIsGCE; } /** * Configuration is resolved in the following order of precedence: * - {@link GoogleAuthOptions.credentials `credentials`} * - {@link GoogleAuthOptions.keyFilename `keyFilename`} * - {@link GoogleAuthOptions.keyFile `keyFile`} * * {@link GoogleAuthOptions.clientOptions `clientOptions`} are passed to the * {@link AuthClient `AuthClient`s}. * * @param opts */ constructor(opts = {}) { _GoogleAuth_instances.add(this); /** * Caches a value indicating whether the auth layer is running on Google * Compute Engine. * @private */ this.checkIsGCE = undefined; // To save the contents of the JSON credential file this.jsonContent = null; this.cachedCredential = null; /** * A pending {@link AuthClient}. Used for concurrent {@link GoogleAuth.getClient} calls. */ _GoogleAuth_pendingAuthClient.set(this, null); this.clientOptions = {}; this._cachedProjectId = opts.projectId || null; this.cachedCredential = opts.authClient || null; this.keyFilename = opts.keyFilename || opts.keyFile; this.scopes = opts.scopes; this.clientOptions = opts.clientOptions || {}; this.jsonContent = opts.credentials || null; this.apiKey = opts.apiKey || this.clientOptions.apiKey || null; // Cannot use both API Key + Credentials if (this.apiKey && (this.jsonContent || this.clientOptions.credentials)) { throw new RangeError(exports.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS); } if (opts.universeDomain) { this.clientOptions.universeDomain = opts.universeDomain; } } // GAPIC client libraries should always use self-signed JWTs. The following // variables are set on the JWT client in order to indicate the type of library, // and sign the JWT with the correct audience and scopes (if not supplied). setGapicJWTValues(client) { client.defaultServicePath = this.defaultServicePath; client.useJWTAccessWithScope = this.useJWTAccessWithScope; client.defaultScopes = this.defaultScopes; } getProjectId(callback) { if (callback) { this.getProjectIdAsync().then(r => callback(null, r), callback); } else { return this.getProjectIdAsync(); } } /** * A temporary method for internal `getProjectId` usages where `null` is * acceptable. In a future major release, `getProjectId` should return `null` * (as the `Promise` base signature describes) and this private * method should be removed. * * @returns Promise that resolves with project id (or `null`) */ async getProjectIdOptional() { try { return await this.getProjectId(); } catch (e) { if (e instanceof Error && e.message === exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND) { return null; } else { throw e; } } } /** * A private method for finding and caching a projectId. * * Supports environments in order of precedence: * - GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable * - GOOGLE_APPLICATION_CREDENTIALS JSON file * - Cloud SDK: `gcloud config config-helper --format json` * - GCE project ID from metadata server * * @returns projectId */ async findAndCacheProjectId() { let projectId = null; projectId || (projectId = await this.getProductionProjectId()); projectId || (projectId = await this.getFileProjectId()); projectId || (projectId = await this.getDefaultServiceProjectId()); projectId || (projectId = await this.getGCEProjectId()); projectId || (projectId = await this.getExternalAccountClientProjectId()); if (projectId) { this._cachedProjectId = projectId; return projectId; } else { throw new Error(exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND); } } async getProjectIdAsync() { if (this._cachedProjectId) { return this._cachedProjectId; } if (!this._findProjectIdPromise) { this._findProjectIdPromise = this.findAndCacheProjectId(); } return this._findProjectIdPromise; } /** * Retrieves a universe domain from the metadata server via * {@link gcpMetadata.universe}. * * @returns a universe domain */ async getUniverseDomainFromMetadataServer() { var _a; let universeDomain; try { universeDomain = await gcpMetadata.universe('universe-domain'); universeDomain || (universeDomain = authclient_1.DEFAULT_UNIVERSE); } catch (e) { if (e && ((_a = e === null || e === void 0 ? void 0 : e.response) === null || _a === void 0 ? void 0 : _a.status) === 404) { universeDomain = authclient_1.DEFAULT_UNIVERSE; } else { throw e; } } return universeDomain; } /** * Retrieves, caches, and returns the universe domain in the following order * of precedence: * - The universe domain in {@link GoogleAuth.clientOptions} * - An existing or ADC {@link AuthClient}'s universe domain * - {@link gcpMetadata.universe}, if {@link Compute} client * * @returns The universe domain */ async getUniverseDomain() { let universeDomain = (0, util_1.originalOrCamelOptions)(this.clientOptions).get('universe_domain'); try { universeDomain !== null && universeDomain !== void 0 ? universeDomain : (universeDomain = (await this.getClient()).universeDomain); } catch (_a) { // client or ADC is not available universeDomain !== null && universeDomain !== void 0 ? universeDomain : (universeDomain = authclient_1.DEFAULT_UNIVERSE); } return universeDomain; } /** * @returns Any scopes (user-specified or default scopes specified by the * client library) that need to be set on the current Auth client. */ getAnyScopes() { return this.scopes || this.defaultScopes; } getApplicationDefault(optionsOrCallback = {}, callback) { let options; if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; } else { options = optionsOrCallback; } if (callback) { this.getApplicationDefaultAsync(options).then(r => callback(null, r.credential, r.projectId), callback); } else { return this.getApplicationDefaultAsync(options); } } async getApplicationDefaultAsync(options = {}) { // If we've already got a cached credential, return it. // This will also preserve one's configured quota project, in case they // set one directly on the credential previously. if (this.cachedCredential) { // cache, while preserving existing quota project preferences return await __classPrivateFieldGet(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, this.cachedCredential, null); } let credential; // Check for the existence of a local environment variable pointing to the // location of the credential file. This is typically used in local // developer scenarios. credential = await this._tryGetApplicationCredentialsFromEnvironmentVariable(options); if (credential) { if (credential instanceof jwtclient_1.JWT) { credential.scopes = this.scopes; } else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) { credential.scopes = this.getAnyScopes(); } return await __classPrivateFieldGet(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, credential); } // Look in the well-known credential file location. credential = await this._tryGetApplicationCredentialsFromWellKnownFile(options); if (credential) { if (credential instanceof jwtclient_1.JWT) { credential.scopes = this.scopes; } else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) { credential.scopes = this.getAnyScopes(); } return await __classPrivateFieldGet(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, credential); } // Determine if we're running on GCE. if (await this._checkIsGCE()) { options.scopes = this.getAnyScopes(); return await __classPrivateFieldGet(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, new computeclient_1.Compute(options)); } throw new Error(exports.GoogleAuthExceptionMessages.NO_ADC_FOUND); } /** * Determines whether the auth layer is running on Google Compute Engine. * Checks for GCP Residency, then fallback to checking if metadata server * is available. * * @returns A promise that resolves with the boolean. * @api private */ async _checkIsGCE() { if (this.checkIsGCE === undefined) { this.checkIsGCE = gcpMetadata.getGCPResidency() || (await gcpMetadata.isAvailable()); } return this.checkIsGCE; } /** * Attempts to load default credentials from the environment variable path.. * @returns Promise that resolves with the OAuth2Client or null. * @api private */ async _tryGetApplicationCredentialsFromEnvironmentVariable(options) { const credentialsPath = process.env['GOOGLE_APPLICATION_CREDENTIALS'] || process.env['google_application_credentials']; if (!credentialsPath || credentialsPath.length === 0) { return null; } try { return this._getApplicationCredentialsFromFilePath(credentialsPath, options); } catch (e) { if (e instanceof Error) { e.message = `Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e.message}`; } throw e; } } /** * Attempts to load default credentials from a well-known file location * @return Promise that resolves with the OAuth2Client or null. * @api private */ async _tryGetApplicationCredentialsFromWellKnownFile(options) { // First, figure out the location of the file, depending upon the OS type. let location = null; if (this._isWindows()) { // Windows location = process.env['APPDATA']; } else { // Linux or Mac const home = process.env['HOME']; if (home) { location = path.join(home, '.config'); } } // If we found the root path, expand it. if (location) { location = path.join(location, 'gcloud', 'application_default_credentials.json'); if (!fs.existsSync(location)) { location = null; } } // The file does not exist. if (!location) { return null; } // The file seems to exist. Try to use it. const client = await this._getApplicationCredentialsFromFilePath(location, options); return client; } /** * Attempts to load default credentials from a file at the given path.. * @param filePath The path to the file to read. * @returns Promise that resolves with the OAuth2Client * @api private */ async _getApplicationCredentialsFromFilePath(filePath, options = {}) { // Make sure the path looks like a string. if (!filePath || filePath.length === 0) { throw new Error('The file path is invalid.'); } // Make sure there is a file at the path. lstatSync will throw if there is // nothing there. try { // Resolve path to actual file in case of symlink. Expect a thrown error // if not resolvable. filePath = fs.realpathSync(filePath); if (!fs.lstatSync(filePath).isFile()) { throw new Error(); } } catch (err) { if (err instanceof Error) { err.message = `The file at ${filePath} does not exist, or it is not a file. ${err.message}`; } throw err; } // Now open a read stream on the file, and parse it. const readStream = fs.createReadStream(filePath); return this.fromStream(readStream, options); } /** * Create a credentials instance using a given impersonated input options. * @param json The impersonated input object. * @returns JWT or UserRefresh Client with data */ fromImpersonatedJSON(json) { var _a, _b, _c, _d; if (!json) { throw new Error('Must pass in a JSON object containing an impersonated refresh token'); } if (json.type !== impersonated_1.IMPERSONATED_ACCOUNT_TYPE) { throw new Error(`The incoming JSON object does not have the "${impersonated_1.IMPERSONATED_ACCOUNT_TYPE}" type`); } if (!json.source_credentials) { throw new Error('The incoming JSON object does not contain a source_credentials field'); } if (!json.service_account_impersonation_url) { throw new Error('The incoming JSON object does not contain a service_account_impersonation_url field'); } const sourceClient = this.fromJSON(json.source_credentials); if (((_a = json.service_account_impersonation_url) === null || _a === void 0 ? void 0 : _a.length) > 256) { /** * Prevents DOS attacks. * @see {@link https://github.com/googleapis/google-auth-library-nodejs/security/code-scanning/85} **/ throw new RangeError(`Target principal is too long: ${json.service_account_impersonation_url}`); } // Extract service account from service_account_impersonation_url const targetPrincipal = (_c = (_b = /(?[^/]+):(generateAccessToken|generateIdToken)$/.exec(json.service_account_impersonation_url)) === null || _b === void 0 ? void 0 : _b.groups) === null || _c === void 0 ? void 0 : _c.target; if (!targetPrincipal) { throw new RangeError(`Cannot extract target principal from ${json.service_account_impersonation_url}`); } const targetScopes = (_d = this.getAnyScopes()) !== null && _d !== void 0 ? _d : []; return new impersonated_1.Impersonated({ ...json, sourceClient, targetPrincipal, targetScopes: Array.isArray(targetScopes) ? targetScopes : [targetScopes], }); } /** * Create a credentials instance using the given input options. * This client is not cached. * * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}. * * @param json The input object. * @param options The JWT or UserRefresh options for the client * @returns JWT or UserRefresh Client with data */ fromJSON(json, options = {}) { let client; // user's preferred universe domain const preferredUniverseDomain = (0, util_1.originalOrCamelOptions)(options).get('universe_domain'); if (json.type === refreshclient_1.USER_REFRESH_ACCOUNT_TYPE) { client = new refreshclient_1.UserRefreshClient(options); client.fromJSON(json); } else if (json.type === impersonated_1.IMPERSONATED_ACCOUNT_TYPE) { client = this.fromImpersonatedJSON(json); } else if (json.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) { client = externalclient_1.ExternalAccountClient.fromJSON(json, options); client.scopes = this.getAnyScopes(); } else if (json.type === externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE) { client = new externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient(json, options); } else { options.scopes = this.scopes; client = new jwtclient_1.JWT(options); this.setGapicJWTValues(client); client.fromJSON(json); } if (preferredUniverseDomain) { client.universeDomain = preferredUniverseDomain; } return client; } /** * Return a JWT or UserRefreshClient from JavaScript object, caching both the * object used to instantiate and the client. * @param json The input object. * @param options The JWT or UserRefresh options for the client * @returns JWT or UserRefresh Client with data */ _cacheClientFromJSON(json, options) { const client = this.fromJSON(json, options); // cache both raw data used to instantiate client and client itself. this.jsonContent = json; this.cachedCredential = client; return client; } fromStream(inputStream, optionsOrCallback = {}, callback) { let options = {}; if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; } else { options = optionsOrCallback; } if (callback) { this.fromStreamAsync(inputStream, options).then(r => callback(null, r), callback); } else { return this.fromStreamAsync(inputStream, options); } } fromStreamAsync(inputStream, options) { return new Promise((resolve, reject) => { if (!inputStream) { throw new Error('Must pass in a stream containing the Google auth settings.'); } const chunks = []; inputStream .setEncoding('utf8') .on('error', reject) .on('data', chunk => chunks.push(chunk)) .on('end', () => { try { try { const data = JSON.parse(chunks.join('')); const r = this._cacheClientFromJSON(data, options); return resolve(r); } catch (err) { // If we failed parsing this.keyFileName, assume that it // is a PEM or p12 certificate: if (!this.keyFilename) throw err; const client = new jwtclient_1.JWT({ ...this.clientOptions, keyFile: this.keyFilename, }); this.cachedCredential = client; this.setGapicJWTValues(client); return resolve(client); } } catch (err) { return reject(err); } }); }); } /** * Create a credentials instance using the given API key string. * The created client is not cached. In order to create and cache it use the {@link GoogleAuth.getClient `getClient`} method after first providing an {@link GoogleAuth.apiKey `apiKey`}. * * @param apiKey The API key string * @param options An optional options object. * @returns A JWT loaded from the key */ fromAPIKey(apiKey, options = {}) { return new jwtclient_1.JWT({ ...options, apiKey }); } /** * Determines whether the current operating system is Windows. * @api private */ _isWindows() { const sys = os.platform(); if (sys && sys.length >= 3) { if (sys.substring(0, 3).toLowerCase() === 'win') { return true; } } return false; } /** * Run the Google Cloud SDK command that prints the default project ID */ async getDefaultServiceProjectId() { return new Promise(resolve => { (0, child_process_1.exec)('gcloud config config-helper --format json', (err, stdout) => { if (!err && stdout) { try { const projectId = JSON.parse(stdout).configuration.properties.core.project; resolve(projectId); return; } catch (e) { // ignore errors } } resolve(null); }); }); } /** * Loads the project id from environment variables. * @api private */ getProductionProjectId() { return (process.env['GCLOUD_PROJECT'] || process.env['GOOGLE_CLOUD_PROJECT'] || process.env['gcloud_project'] || process.env['google_cloud_project']); } /** * Loads the project id from the GOOGLE_APPLICATION_CREDENTIALS json file. * @api private */ async getFileProjectId() { if (this.cachedCredential) { // Try to read the project ID from the cached credentials file return this.cachedCredential.projectId; } // Ensure the projectId is loaded from the keyFile if available. if (this.keyFilename) { const creds = await this.getClient(); if (creds && creds.projectId) { return creds.projectId; } } // Try to load a credentials file and read its project ID const r = await this._tryGetApplicationCredentialsFromEnvironmentVariable(); if (r) { return r.projectId; } else { return null; } } /** * Gets the project ID from external account client if available. */ async getExternalAccountClientProjectId() { if (!this.jsonContent || this.jsonContent.type !== baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) { return null; } const creds = await this.getClient(); // Do not suppress the underlying error, as the error could contain helpful // information for debugging and fixing. This is especially true for // external account creds as in order to get the project ID, the following // operations have to succeed: // 1. Valid credentials file should be supplied. // 2. Ability to retrieve access tokens from STS token exchange API. // 3. Ability to exchange for service account impersonated credentials (if // enabled). // 4. Ability to get project info using the access token from step 2 or 3. // Without surfacing the error, it is harder for developers to determine // which step went wrong. return await creds.getProjectId(); } /** * Gets the Compute Engine project ID if it can be inferred. */ async getGCEProjectId() { try { const r = await gcpMetadata.project('project-id'); return r; } catch (e) { // Ignore any errors return null; } } getCredentials(callback) { if (callback) { this.getCredentialsAsync().then(r => callback(null, r), callback); } else { return this.getCredentialsAsync(); } } async getCredentialsAsync() { const client = await this.getClient(); if (client instanceof impersonated_1.Impersonated) { return { client_email: client.getTargetPrincipal() }; } if (client instanceof baseexternalclient_1.BaseExternalAccountClient) { const serviceAccountEmail = client.getServiceAccountEmail(); if (serviceAccountEmail) { return { client_email: serviceAccountEmail, universe_domain: client.universeDomain, }; } } if (this.jsonContent) { return { client_email: this.jsonContent.client_email, private_key: this.jsonContent.private_key, universe_domain: this.jsonContent.universe_domain, }; } if (await this._checkIsGCE()) { const [client_email, universe_domain] = await Promise.all([ gcpMetadata.instance('service-accounts/default/email'), this.getUniverseDomain(), ]); return { client_email, universe_domain }; } throw new Error(exports.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND); } /** * Automatically obtain an {@link AuthClient `AuthClient`} based on the * provided configuration. If no options were passed, use Application * Default Credentials. */ async getClient() { if (this.cachedCredential) { return this.cachedCredential; } // Use an existing auth client request, or cache a new one __classPrivateFieldSet(this, _GoogleAuth_pendingAuthClient, __classPrivateFieldGet(this, _GoogleAuth_pendingAuthClient, "f") || __classPrivateFieldGet(this, _GoogleAuth_instances, "m", _GoogleAuth_determineClient).call(this), "f"); try { return await __classPrivateFieldGet(this, _GoogleAuth_pendingAuthClient, "f"); } finally { // reset the pending auth client in case it is changed later __classPrivateFieldSet(this, _GoogleAuth_pendingAuthClient, null, "f"); } } /** * Creates a client which will fetch an ID token for authorization. * @param targetAudience the audience for the fetched ID token. * @returns IdTokenClient for making HTTP calls authenticated with ID tokens. */ async getIdTokenClient(targetAudience) { const client = await this.getClient(); if (!('fetchIdToken' in client)) { throw new Error('Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.'); } return new idtokenclient_1.IdTokenClient({ targetAudience, idTokenProvider: client }); } /** * Automatically obtain application default credentials, and return * an access token for making requests. */ async getAccessToken() { const client = await this.getClient(); return (await client.getAccessToken()).token; } /** * Obtain the HTTP headers that will provide authorization for a given * request. */ async getRequestHeaders(url) { const client = await this.getClient(); return client.getRequestHeaders(url); } /** * Obtain credentials for a request, then attach the appropriate headers to * the request options. * @param opts Axios or Request options on which to attach the headers */ async authorizeRequest(opts) { opts = opts || {}; const url = opts.url || opts.uri; const client = await this.getClient(); const headers = await client.getRequestHeaders(url); opts.headers = Object.assign(opts.headers || {}, headers); return opts; } /** * Automatically obtain application default credentials, and make an * HTTP request using the given options. * @param opts Axios request options for the HTTP request. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any async request(opts) { const client = await this.getClient(); return client.request(opts); } /** * Determine the compute environment in which the code is running. */ getEnv() { return (0, envDetect_1.getEnv)(); } /** * Sign the given data with the current private key, or go out * to the IAM API to sign it. * @param data The data to be signed. * @param endpoint A custom endpoint to use. * * @example * ``` * sign('data', 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/'); * ``` */ async sign(data, endpoint) { const client = await this.getClient(); const universe = await this.getUniverseDomain(); endpoint = endpoint || `https://iamcredentials.${universe}/v1/projects/-/serviceAccounts/`; if (client instanceof impersonated_1.Impersonated) { const signed = await client.sign(data); return signed.signedBlob; } const crypto = (0, crypto_1.createCrypto)(); if (client instanceof jwtclient_1.JWT && client.key) { const sign = await crypto.sign(client.key, data); return sign; } const creds = await this.getCredentials(); if (!creds.client_email) { throw new Error('Cannot sign data without `client_email`.'); } return this.signBlob(crypto, creds.client_email, data, endpoint); } async signBlob(crypto, emailOrUniqueId, data, endpoint) { const url = new URL(endpoint + `${emailOrUniqueId}:signBlob`); const res = await this.request({ method: 'POST', url: url.href, data: { payload: crypto.encodeBase64StringUtf8(data), }, retry: true, retryConfig: { httpMethodsToRetry: ['POST'], }, }); return res.data.signedBlob; } } exports.GoogleAuth = GoogleAuth; _GoogleAuth_pendingAuthClient = new WeakMap(), _GoogleAuth_instances = new WeakSet(), _GoogleAuth_prepareAndCacheClient = async function _GoogleAuth_prepareAndCacheClient(credential, quotaProjectIdOverride = process.env['GOOGLE_CLOUD_QUOTA_PROJECT'] || null) { const projectId = await this.getProjectIdOptional(); if (quotaProjectIdOverride) { credential.quotaProjectId = quotaProjectIdOverride; } this.cachedCredential = credential; return { credential, projectId }; }, _GoogleAuth_determineClient = async function _GoogleAuth_determineClient() { if (this.jsonContent) { return this._cacheClientFromJSON(this.jsonContent, this.clientOptions); } else if (this.keyFilename) { const filePath = path.resolve(this.keyFilename); const stream = fs.createReadStream(filePath); return await this.fromStreamAsync(stream, this.clientOptions); } else if (this.apiKey) { const client = await this.fromAPIKey(this.apiKey, this.clientOptions); client.scopes = this.scopes; const { credential } = await __classPrivateFieldGet(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, client); return credential; } else { const { credential } = await this.getApplicationDefaultAsync(this.clientOptions); return credential; } }; /** * Export DefaultTransporter as a static property of the class. */ GoogleAuth.DefaultTransporter = transporters_1.DefaultTransporter; /***/ }), /***/ 7009: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright 2014 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.IAMAuth = void 0; class IAMAuth { /** * IAM credentials. * * @param selector the iam authority selector * @param token the token * @constructor */ constructor(selector, token) { this.selector = selector; this.token = token; this.selector = selector; this.token = token; } /** * Acquire the HTTP headers required to make an authenticated request. */ getRequestHeaders() { return { 'x-goog-iam-authority-selector': this.selector, 'x-goog-iam-authorization-token': this.token, }; } } exports.IAMAuth = IAMAuth; /***/ }), /***/ 9960: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.IdentityPoolClient = void 0; const baseexternalclient_1 = __nccwpck_require__(142); const util_1 = __nccwpck_require__(7870); const filesubjecttokensupplier_1 = __nccwpck_require__(932); const urlsubjecttokensupplier_1 = __nccwpck_require__(4627); /** * Defines the Url-sourced and file-sourced external account clients mainly * used for K8s and Azure workloads. */ class IdentityPoolClient extends baseexternalclient_1.BaseExternalAccountClient { /** * Instantiate an IdentityPoolClient instance using the provided JSON * object loaded from an external account credentials file. * An error is thrown if the credential is not a valid file-sourced or * url-sourced credential or a workforce pool user project is provided * with a non workforce audience. * @param options The external account options object typically loaded * from the external account JSON credential file. The camelCased options * are aliases for the snake_cased options. * @param additionalOptions **DEPRECATED, all options are available in the * `options` parameter.** Optional additional behavior customization options. * These currently customize expiration threshold time and whether to retry * on 401/403 API request errors. */ constructor(options, additionalOptions) { super(options, additionalOptions); const opts = (0, util_1.originalOrCamelOptions)(options); const credentialSource = opts.get('credential_source'); const subjectTokenSupplier = opts.get('subject_token_supplier'); // Validate credential sourcing configuration. if (!credentialSource && !subjectTokenSupplier) { throw new Error('A credential source or subject token supplier must be specified.'); } if (credentialSource && subjectTokenSupplier) { throw new Error('Only one of credential source or subject token supplier can be specified.'); } if (subjectTokenSupplier) { this.subjectTokenSupplier = subjectTokenSupplier; this.credentialSourceType = 'programmatic'; } else { const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource); const formatOpts = (0, util_1.originalOrCamelOptions)(credentialSourceOpts.get('format')); // Text is the default format type. const formatType = formatOpts.get('type') || 'text'; const formatSubjectTokenFieldName = formatOpts.get('subject_token_field_name'); if (formatType !== 'json' && formatType !== 'text') { throw new Error(`Invalid credential_source format "${formatType}"`); } if (formatType === 'json' && !formatSubjectTokenFieldName) { throw new Error('Missing subject_token_field_name for JSON credential_source format'); } const file = credentialSourceOpts.get('file'); const url = credentialSourceOpts.get('url'); const headers = credentialSourceOpts.get('headers'); if (file && url) { throw new Error('No valid Identity Pool "credential_source" provided, must be either file or url.'); } else if (file && !url) { this.credentialSourceType = 'file'; this.subjectTokenSupplier = new filesubjecttokensupplier_1.FileSubjectTokenSupplier({ filePath: file, formatType: formatType, subjectTokenFieldName: formatSubjectTokenFieldName, }); } else if (!file && url) { this.credentialSourceType = 'url'; this.subjectTokenSupplier = new urlsubjecttokensupplier_1.UrlSubjectTokenSupplier({ url: url, formatType: formatType, subjectTokenFieldName: formatSubjectTokenFieldName, headers: headers, additionalGaxiosOptions: IdentityPoolClient.RETRY_CONFIG, }); } else { throw new Error('No valid Identity Pool "credential_source" provided, must be either file or url.'); } } } /** * Triggered when a external subject token is needed to be exchanged for a GCP * access token via GCP STS endpoint. Gets a subject token by calling * the configured {@link SubjectTokenSupplier} * @return A promise that resolves with the external subject token. */ async retrieveSubjectToken() { return this.subjectTokenSupplier.getSubjectToken(this.supplierContext); } } exports.IdentityPoolClient = IdentityPoolClient; /***/ }), /***/ 2718: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.IdTokenClient = void 0; const oauth2client_1 = __nccwpck_require__(91); class IdTokenClient extends oauth2client_1.OAuth2Client { /** * Google ID Token client * * Retrieve ID token from the metadata server. * See: https://cloud.google.com/docs/authentication/get-id-token#metadata-server */ constructor(options) { super(options); this.targetAudience = options.targetAudience; this.idTokenProvider = options.idTokenProvider; } async getRequestMetadataAsync( // eslint-disable-next-line @typescript-eslint/no-unused-vars url) { if (!this.credentials.id_token || !this.credentials.expiry_date || this.isTokenExpiring()) { const idToken = await this.idTokenProvider.fetchIdToken(this.targetAudience); this.credentials = { id_token: idToken, expiry_date: this.getIdTokenExpiryDate(idToken), }; } const headers = { Authorization: 'Bearer ' + this.credentials.id_token, }; return { headers }; } getIdTokenExpiryDate(idToken) { const payloadB64 = idToken.split('.')[1]; if (payloadB64) { const payload = JSON.parse(Buffer.from(payloadB64, 'base64').toString('ascii')); return payload.exp * 1000; } } } exports.IdTokenClient = IdTokenClient; /***/ }), /***/ 9964: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /** * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Impersonated = exports.IMPERSONATED_ACCOUNT_TYPE = void 0; const oauth2client_1 = __nccwpck_require__(91); const gaxios_1 = __nccwpck_require__(7003); const util_1 = __nccwpck_require__(7870); exports.IMPERSONATED_ACCOUNT_TYPE = 'impersonated_service_account'; class Impersonated extends oauth2client_1.OAuth2Client { /** * Impersonated service account credentials. * * Create a new access token by impersonating another service account. * * Impersonated Credentials allowing credentials issued to a user or * service account to impersonate another. The source project using * Impersonated Credentials must enable the "IAMCredentials" API. * Also, the target service account must grant the orginating principal * the "Service Account Token Creator" IAM role. * * @param {object} options - The configuration object. * @param {object} [options.sourceClient] the source credential used as to * acquire the impersonated credentials. * @param {string} [options.targetPrincipal] the service account to * impersonate. * @param {string[]} [options.delegates] the chained list of delegates * required to grant the final access_token. If set, the sequence of * identities must have "Service Account Token Creator" capability granted to * the preceding identity. For example, if set to [serviceAccountB, * serviceAccountC], the sourceCredential must have the Token Creator role on * serviceAccountB. serviceAccountB must have the Token Creator on * serviceAccountC. Finally, C must have Token Creator on target_principal. * If left unset, sourceCredential must have that role on targetPrincipal. * @param {string[]} [options.targetScopes] scopes to request during the * authorization grant. * @param {number} [options.lifetime] number of seconds the delegated * credential should be valid for up to 3600 seconds by default, or 43,200 * seconds by extending the token's lifetime, see: * https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials#sa-credentials-oauth * @param {string} [options.endpoint] api endpoint override. */ constructor(options = {}) { var _a, _b, _c, _d, _e, _f; super(options); // Start with an expired refresh token, which will automatically be // refreshed before the first API call is made. this.credentials = { expiry_date: 1, refresh_token: 'impersonated-placeholder', }; this.sourceClient = (_a = options.sourceClient) !== null && _a !== void 0 ? _a : new oauth2client_1.OAuth2Client(); this.targetPrincipal = (_b = options.targetPrincipal) !== null && _b !== void 0 ? _b : ''; this.delegates = (_c = options.delegates) !== null && _c !== void 0 ? _c : []; this.targetScopes = (_d = options.targetScopes) !== null && _d !== void 0 ? _d : []; this.lifetime = (_e = options.lifetime) !== null && _e !== void 0 ? _e : 3600; const usingExplicitUniverseDomain = !!(0, util_1.originalOrCamelOptions)(options).get('universe_domain'); if (!usingExplicitUniverseDomain) { // override the default universe with the source's universe this.universeDomain = this.sourceClient.universeDomain; } else if (this.sourceClient.universeDomain !== this.universeDomain) { // non-default universe and is not matching the source - this could be a credential leak throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`); } this.endpoint = (_f = options.endpoint) !== null && _f !== void 0 ? _f : `https://iamcredentials.${this.universeDomain}`; } /** * Signs some bytes. * * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob Reference Documentation} * @param blobToSign String to sign. * * @returns A {@link SignBlobResponse} denoting the keyID and signedBlob in base64 string */ async sign(blobToSign) { await this.sourceClient.getAccessToken(); const name = `projects/-/serviceAccounts/${this.targetPrincipal}`; const u = `${this.endpoint}/v1/${name}:signBlob`; const body = { delegates: this.delegates, payload: Buffer.from(blobToSign).toString('base64'), }; const res = await this.sourceClient.request({ ...Impersonated.RETRY_CONFIG, url: u, data: body, method: 'POST', }); return res.data; } /** The service account email to be impersonated. */ getTargetPrincipal() { return this.targetPrincipal; } /** * Refreshes the access token. */ async refreshToken() { var _a, _b, _c, _d, _e, _f; try { await this.sourceClient.getAccessToken(); const name = 'projects/-/serviceAccounts/' + this.targetPrincipal; const u = `${this.endpoint}/v1/${name}:generateAccessToken`; const body = { delegates: this.delegates, scope: this.targetScopes, lifetime: this.lifetime + 's', }; const res = await this.sourceClient.request({ ...Impersonated.RETRY_CONFIG, url: u, data: body, method: 'POST', }); const tokenResponse = res.data; this.credentials.access_token = tokenResponse.accessToken; this.credentials.expiry_date = Date.parse(tokenResponse.expireTime); return { tokens: this.credentials, res, }; } catch (error) { if (!(error instanceof Error)) throw error; let status = 0; let message = ''; if (error instanceof gaxios_1.GaxiosError) { status = (_c = (_b = (_a = error === null || error === void 0 ? void 0 : error.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.error) === null || _c === void 0 ? void 0 : _c.status; message = (_f = (_e = (_d = error === null || error === void 0 ? void 0 : error.response) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.error) === null || _f === void 0 ? void 0 : _f.message; } if (status && message) { error.message = `${status}: unable to impersonate: ${message}`; throw error; } else { error.message = `unable to impersonate: ${error}`; throw error; } } } /** * Generates an OpenID Connect ID token for a service account. * * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateIdToken Reference Documentation} * * @param targetAudience the audience for the fetched ID token. * @param options the for the request * @return an OpenID Connect ID token */ async fetchIdToken(targetAudience, options) { var _a, _b; await this.sourceClient.getAccessToken(); const name = `projects/-/serviceAccounts/${this.targetPrincipal}`; const u = `${this.endpoint}/v1/${name}:generateIdToken`; const body = { delegates: this.delegates, audience: targetAudience, includeEmail: (_a = options === null || options === void 0 ? void 0 : options.includeEmail) !== null && _a !== void 0 ? _a : true, useEmailAzp: (_b = options === null || options === void 0 ? void 0 : options.includeEmail) !== null && _b !== void 0 ? _b : true, }; const res = await this.sourceClient.request({ ...Impersonated.RETRY_CONFIG, url: u, data: body, method: 'POST', }); return res.data.token; } } exports.Impersonated = Impersonated; /***/ }), /***/ 7060: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright 2015 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JWTAccess = void 0; const jws = __nccwpck_require__(3324); const util_1 = __nccwpck_require__(7870); const DEFAULT_HEADER = { alg: 'RS256', typ: 'JWT', }; class JWTAccess { /** * JWTAccess service account credentials. * * Create a new access token by using the credential to create a new JWT token * that's recognized as the access token. * * @param email the service account email address. * @param key the private key that will be used to sign the token. * @param keyId the ID of the private key used to sign the token. */ constructor(email, key, keyId, eagerRefreshThresholdMillis) { this.cache = new util_1.LRUCache({ capacity: 500, maxAge: 60 * 60 * 1000, }); this.email = email; this.key = key; this.keyId = keyId; this.eagerRefreshThresholdMillis = eagerRefreshThresholdMillis !== null && eagerRefreshThresholdMillis !== void 0 ? eagerRefreshThresholdMillis : 5 * 60 * 1000; } /** * Ensures that we're caching a key appropriately, giving precedence to scopes vs. url * * @param url The URI being authorized. * @param scopes The scope or scopes being authorized * @returns A string that returns the cached key. */ getCachedKey(url, scopes) { let cacheKey = url; if (scopes && Array.isArray(scopes) && scopes.length) { cacheKey = url ? `${url}_${scopes.join('_')}` : `${scopes.join('_')}`; } else if (typeof scopes === 'string') { cacheKey = url ? `${url}_${scopes}` : scopes; } if (!cacheKey) { throw Error('Scopes or url must be provided'); } return cacheKey; } /** * Get a non-expired access token, after refreshing if necessary. * * @param url The URI being authorized. * @param additionalClaims An object with a set of additional claims to * include in the payload. * @returns An object that includes the authorization header. */ getRequestHeaders(url, additionalClaims, scopes) { // Return cached authorization headers, unless we are within // eagerRefreshThresholdMillis ms of them expiring: const key = this.getCachedKey(url, scopes); const cachedToken = this.cache.get(key); const now = Date.now(); if (cachedToken && cachedToken.expiration - now > this.eagerRefreshThresholdMillis) { return cachedToken.headers; } const iat = Math.floor(Date.now() / 1000); const exp = JWTAccess.getExpirationTime(iat); let defaultClaims; // Turn scopes into space-separated string if (Array.isArray(scopes)) { scopes = scopes.join(' '); } // If scopes are specified, sign with scopes if (scopes) { defaultClaims = { iss: this.email, sub: this.email, scope: scopes, exp, iat, }; } else { defaultClaims = { iss: this.email, sub: this.email, aud: url, exp, iat, }; } // if additionalClaims are provided, ensure they do not collide with // other required claims. if (additionalClaims) { for (const claim in defaultClaims) { if (additionalClaims[claim]) { throw new Error(`The '${claim}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`); } } } const header = this.keyId ? { ...DEFAULT_HEADER, kid: this.keyId } : DEFAULT_HEADER; const payload = Object.assign(defaultClaims, additionalClaims); // Sign the jwt and add it to the cache const signedJWT = jws.sign({ header, payload, secret: this.key }); const headers = { Authorization: `Bearer ${signedJWT}` }; this.cache.set(key, { expiration: exp * 1000, headers, }); return headers; } /** * Returns an expiration time for the JWT token. * * @param iat The issued at time for the JWT. * @returns An expiration time for the JWT. */ static getExpirationTime(iat) { const exp = iat + 3600; // 3600 seconds = 1 hour return exp; } /** * Create a JWTAccess credentials instance using the given input options. * @param json The input object. */ fromJSON(json) { if (!json) { throw new Error('Must pass in a JSON object containing the service account auth settings.'); } if (!json.client_email) { throw new Error('The incoming JSON object does not contain a client_email field'); } if (!json.private_key) { throw new Error('The incoming JSON object does not contain a private_key field'); } // Extract the relevant information from the json key file. this.email = json.client_email; this.key = json.private_key; this.keyId = json.private_key_id; this.projectId = json.project_id; } fromStream(inputStream, callback) { if (callback) { this.fromStreamAsync(inputStream).then(() => callback(), callback); } else { return this.fromStreamAsync(inputStream); } } fromStreamAsync(inputStream) { return new Promise((resolve, reject) => { if (!inputStream) { reject(new Error('Must pass in a stream containing the service account auth settings.')); } let s = ''; inputStream .setEncoding('utf8') .on('data', chunk => (s += chunk)) .on('error', reject) .on('end', () => { try { const data = JSON.parse(s); this.fromJSON(data); resolve(); } catch (err) { reject(err); } }); }); } } exports.JWTAccess = JWTAccess; /***/ }), /***/ 5277: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright 2013 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JWT = void 0; const gtoken_1 = __nccwpck_require__(8568); const jwtaccess_1 = __nccwpck_require__(7060); const oauth2client_1 = __nccwpck_require__(91); const authclient_1 = __nccwpck_require__(4810); class JWT extends oauth2client_1.OAuth2Client { constructor(optionsOrEmail, keyFile, key, scopes, subject, keyId) { const opts = optionsOrEmail && typeof optionsOrEmail === 'object' ? optionsOrEmail : { email: optionsOrEmail, keyFile, key, keyId, scopes, subject }; super(opts); this.email = opts.email; this.keyFile = opts.keyFile; this.key = opts.key; this.keyId = opts.keyId; this.scopes = opts.scopes; this.subject = opts.subject; this.additionalClaims = opts.additionalClaims; // Start with an expired refresh token, which will automatically be // refreshed before the first API call is made. this.credentials = { refresh_token: 'jwt-placeholder', expiry_date: 1 }; } /** * Creates a copy of the credential with the specified scopes. * @param scopes List of requested scopes or a single scope. * @return The cloned instance. */ createScoped(scopes) { const jwt = new JWT(this); jwt.scopes = scopes; return jwt; } /** * Obtains the metadata to be sent with the request. * * @param url the URI being authorized. */ async getRequestMetadataAsync(url) { url = this.defaultServicePath ? `https://${this.defaultServicePath}/` : url; const useSelfSignedJWT = (!this.hasUserScopes() && url) || (this.useJWTAccessWithScope && this.hasAnyScopes()) || this.universeDomain !== authclient_1.DEFAULT_UNIVERSE; if (this.subject && this.universeDomain !== authclient_1.DEFAULT_UNIVERSE) { throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${authclient_1.DEFAULT_UNIVERSE}`); } if (!this.apiKey && useSelfSignedJWT) { if (this.additionalClaims && this.additionalClaims.target_audience) { const { tokens } = await this.refreshToken(); return { headers: this.addSharedMetadataHeaders({ Authorization: `Bearer ${tokens.id_token}`, }), }; } else { // no scopes have been set, but a uri has been provided. Use JWTAccess // credentials. if (!this.access) { this.access = new jwtaccess_1.JWTAccess(this.email, this.key, this.keyId, this.eagerRefreshThresholdMillis); } let scopes; if (this.hasUserScopes()) { scopes = this.scopes; } else if (!url) { scopes = this.defaultScopes; } const useScopes = this.useJWTAccessWithScope || this.universeDomain !== authclient_1.DEFAULT_UNIVERSE; const headers = await this.access.getRequestHeaders(url !== null && url !== void 0 ? url : undefined, this.additionalClaims, // Scopes take precedent over audience for signing, // so we only provide them if `useJWTAccessWithScope` is on or // if we are in a non-default universe useScopes ? scopes : undefined); return { headers: this.addSharedMetadataHeaders(headers) }; } } else if (this.hasAnyScopes() || this.apiKey) { return super.getRequestMetadataAsync(url); } else { // If no audience, apiKey, or scopes are provided, we should not attempt // to populate any headers: return { headers: {} }; } } /** * Fetches an ID token. * @param targetAudience the audience for the fetched ID token. */ async fetchIdToken(targetAudience) { // Create a new gToken for fetching an ID token const gtoken = new gtoken_1.GoogleToken({ iss: this.email, sub: this.subject, scope: this.scopes || this.defaultScopes, keyFile: this.keyFile, key: this.key, additionalClaims: { target_audience: targetAudience }, transporter: this.transporter, }); await gtoken.getToken({ forceRefresh: true, }); if (!gtoken.idToken) { throw new Error('Unknown error: Failed to fetch ID token'); } return gtoken.idToken; } /** * Determine if there are currently scopes available. */ hasUserScopes() { if (!this.scopes) { return false; } return this.scopes.length > 0; } /** * Are there any default or user scopes defined. */ hasAnyScopes() { if (this.scopes && this.scopes.length > 0) return true; if (this.defaultScopes && this.defaultScopes.length > 0) return true; return false; } authorize(callback) { if (callback) { this.authorizeAsync().then(r => callback(null, r), callback); } else { return this.authorizeAsync(); } } async authorizeAsync() { const result = await this.refreshToken(); if (!result) { throw new Error('No result returned'); } this.credentials = result.tokens; this.credentials.refresh_token = 'jwt-placeholder'; this.key = this.gtoken.key; this.email = this.gtoken.iss; return result.tokens; } /** * Refreshes the access token. * @param refreshToken ignored * @private */ async refreshTokenNoCache( // eslint-disable-next-line @typescript-eslint/no-unused-vars refreshToken) { const gtoken = this.createGToken(); const token = await gtoken.getToken({ forceRefresh: this.isTokenExpiring(), }); const tokens = { access_token: token.access_token, token_type: 'Bearer', expiry_date: gtoken.expiresAt, id_token: gtoken.idToken, }; this.emit('tokens', tokens); return { res: null, tokens }; } /** * Create a gToken if it doesn't already exist. */ createGToken() { if (!this.gtoken) { this.gtoken = new gtoken_1.GoogleToken({ iss: this.email, sub: this.subject, scope: this.scopes || this.defaultScopes, keyFile: this.keyFile, key: this.key, additionalClaims: this.additionalClaims, transporter: this.transporter, }); } return this.gtoken; } /** * Create a JWT credentials instance using the given input options. * @param json The input object. * * @remarks * * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}. */ fromJSON(json) { if (!json) { throw new Error('Must pass in a JSON object containing the service account auth settings.'); } if (!json.client_email) { throw new Error('The incoming JSON object does not contain a client_email field'); } if (!json.private_key) { throw new Error('The incoming JSON object does not contain a private_key field'); } // Extract the relevant information from the json key file. this.email = json.client_email; this.key = json.private_key; this.keyId = json.private_key_id; this.projectId = json.project_id; this.quotaProjectId = json.quota_project_id; this.universeDomain = json.universe_domain || this.universeDomain; } fromStream(inputStream, callback) { if (callback) { this.fromStreamAsync(inputStream).then(() => callback(), callback); } else { return this.fromStreamAsync(inputStream); } } fromStreamAsync(inputStream) { return new Promise((resolve, reject) => { if (!inputStream) { throw new Error('Must pass in a stream containing the service account auth settings.'); } let s = ''; inputStream .setEncoding('utf8') .on('error', reject) .on('data', chunk => (s += chunk)) .on('end', () => { try { const data = JSON.parse(s); this.fromJSON(data); resolve(); } catch (e) { reject(e); } }); }); } /** * Creates a JWT credentials instance using an API Key for authentication. * @param apiKey The API Key in string form. */ fromAPIKey(apiKey) { if (typeof apiKey !== 'string') { throw new Error('Must provide an API Key string.'); } this.apiKey = apiKey; } /** * Using the key or keyFile on the JWT client, obtain an object that contains * the key and the client email. */ async getCredentials() { if (this.key) { return { private_key: this.key, client_email: this.email }; } else if (this.keyFile) { const gtoken = this.createGToken(); const creds = await gtoken.getCredentials(this.keyFile); return { private_key: creds.privateKey, client_email: creds.clientEmail }; } throw new Error('A key or a keyFile must be provided to getCredentials.'); } } exports.JWT = JWT; /***/ }), /***/ 3882: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright 2014 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LoginTicket = void 0; class LoginTicket { /** * Create a simple class to extract user ID from an ID Token * * @param {string} env Envelope of the jwt * @param {TokenPayload} pay Payload of the jwt * @constructor */ constructor(env, pay) { this.envelope = env; this.payload = pay; } getEnvelope() { return this.envelope; } getPayload() { return this.payload; } /** * Create a simple class to extract user ID from an ID Token * * @return The user ID */ getUserId() { const payload = this.getPayload(); if (payload && payload.sub) { return payload.sub; } return null; } /** * Returns attributes from the login ticket. This can contain * various information about the user session. * * @return The envelope and payload */ getAttributes() { return { envelope: this.getEnvelope(), payload: this.getPayload() }; } } exports.LoginTicket = LoginTicket; /***/ }), /***/ 91: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.OAuth2Client = exports.ClientAuthentication = exports.CertificateFormat = exports.CodeChallengeMethod = void 0; const gaxios_1 = __nccwpck_require__(7003); const querystring = __nccwpck_require__(3480); const stream = __nccwpck_require__(2203); const formatEcdsa = __nccwpck_require__(325); const crypto_1 = __nccwpck_require__(8851); const authclient_1 = __nccwpck_require__(4810); const loginticket_1 = __nccwpck_require__(3882); var CodeChallengeMethod; (function (CodeChallengeMethod) { CodeChallengeMethod["Plain"] = "plain"; CodeChallengeMethod["S256"] = "S256"; })(CodeChallengeMethod || (exports.CodeChallengeMethod = CodeChallengeMethod = {})); var CertificateFormat; (function (CertificateFormat) { CertificateFormat["PEM"] = "PEM"; CertificateFormat["JWK"] = "JWK"; })(CertificateFormat || (exports.CertificateFormat = CertificateFormat = {})); /** * The client authentication type. Supported values are basic, post, and none. * https://datatracker.ietf.org/doc/html/rfc7591#section-2 */ var ClientAuthentication; (function (ClientAuthentication) { ClientAuthentication["ClientSecretPost"] = "ClientSecretPost"; ClientAuthentication["ClientSecretBasic"] = "ClientSecretBasic"; ClientAuthentication["None"] = "None"; })(ClientAuthentication || (exports.ClientAuthentication = ClientAuthentication = {})); class OAuth2Client extends authclient_1.AuthClient { constructor(optionsOrClientId, clientSecret, redirectUri) { const opts = optionsOrClientId && typeof optionsOrClientId === 'object' ? optionsOrClientId : { clientId: optionsOrClientId, clientSecret, redirectUri }; super(opts); this.certificateCache = {}; this.certificateExpiry = null; this.certificateCacheFormat = CertificateFormat.PEM; this.refreshTokenPromises = new Map(); this._clientId = opts.clientId; this._clientSecret = opts.clientSecret; this.redirectUri = opts.redirectUri; this.endpoints = { tokenInfoUrl: 'https://oauth2.googleapis.com/tokeninfo', oauth2AuthBaseUrl: 'https://accounts.google.com/o/oauth2/v2/auth', oauth2TokenUrl: 'https://oauth2.googleapis.com/token', oauth2RevokeUrl: 'https://oauth2.googleapis.com/revoke', oauth2FederatedSignonPemCertsUrl: 'https://www.googleapis.com/oauth2/v1/certs', oauth2FederatedSignonJwkCertsUrl: 'https://www.googleapis.com/oauth2/v3/certs', oauth2IapPublicKeyUrl: 'https://www.gstatic.com/iap/verify/public_key', ...opts.endpoints, }; this.clientAuthentication = opts.clientAuthentication || ClientAuthentication.ClientSecretPost; this.issuers = opts.issuers || [ 'accounts.google.com', 'https://accounts.google.com', this.universeDomain, ]; } /** * Generates URL for consent page landing. * @param opts Options. * @return URL to consent page. */ generateAuthUrl(opts = {}) { if (opts.code_challenge_method && !opts.code_challenge) { throw new Error('If a code_challenge_method is provided, code_challenge must be included.'); } opts.response_type = opts.response_type || 'code'; opts.client_id = opts.client_id || this._clientId; opts.redirect_uri = opts.redirect_uri || this.redirectUri; // Allow scopes to be passed either as array or a string if (Array.isArray(opts.scope)) { opts.scope = opts.scope.join(' '); } const rootUrl = this.endpoints.oauth2AuthBaseUrl.toString(); return (rootUrl + '?' + querystring.stringify(opts)); } generateCodeVerifier() { // To make the code compatible with browser SubtleCrypto we need to make // this method async. throw new Error('generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.'); } /** * Convenience method to automatically generate a code_verifier, and its * resulting SHA256. If used, this must be paired with a S256 * code_challenge_method. * * For a full example see: * https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js */ async generateCodeVerifierAsync() { // base64 encoding uses 6 bits per character, and we want to generate128 // characters. 6*128/8 = 96. const crypto = (0, crypto_1.createCrypto)(); const randomString = crypto.randomBytesBase64(96); // The valid characters in the code_verifier are [A-Z]/[a-z]/[0-9]/ // "-"/"."/"_"/"~". Base64 encoded strings are pretty close, so we're just // swapping out a few chars. const codeVerifier = randomString .replace(/\+/g, '~') .replace(/=/g, '_') .replace(/\//g, '-'); // Generate the base64 encoded SHA256 const unencodedCodeChallenge = await crypto.sha256DigestBase64(codeVerifier); // We need to use base64UrlEncoding instead of standard base64 const codeChallenge = unencodedCodeChallenge .split('=')[0] .replace(/\+/g, '-') .replace(/\//g, '_'); return { codeVerifier, codeChallenge }; } getToken(codeOrOptions, callback) { const options = typeof codeOrOptions === 'string' ? { code: codeOrOptions } : codeOrOptions; if (callback) { this.getTokenAsync(options).then(r => callback(null, r.tokens, r.res), e => callback(e, null, e.response)); } else { return this.getTokenAsync(options); } } async getTokenAsync(options) { const url = this.endpoints.oauth2TokenUrl.toString(); const headers = { 'Content-Type': 'application/x-www-form-urlencoded', }; const values = { client_id: options.client_id || this._clientId, code_verifier: options.codeVerifier, code: options.code, grant_type: 'authorization_code', redirect_uri: options.redirect_uri || this.redirectUri, }; if (this.clientAuthentication === ClientAuthentication.ClientSecretBasic) { const basic = Buffer.from(`${this._clientId}:${this._clientSecret}`); headers['Authorization'] = `Basic ${basic.toString('base64')}`; } if (this.clientAuthentication === ClientAuthentication.ClientSecretPost) { values.client_secret = this._clientSecret; } const res = await this.transporter.request({ ...OAuth2Client.RETRY_CONFIG, method: 'POST', url, data: querystring.stringify(values), headers, }); const tokens = res.data; if (res.data && res.data.expires_in) { tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000; delete tokens.expires_in; } this.emit('tokens', tokens); return { tokens, res }; } /** * Refreshes the access token. * @param refresh_token Existing refresh token. * @private */ async refreshToken(refreshToken) { if (!refreshToken) { return this.refreshTokenNoCache(refreshToken); } // If a request to refresh using the same token has started, // return the same promise. if (this.refreshTokenPromises.has(refreshToken)) { return this.refreshTokenPromises.get(refreshToken); } const p = this.refreshTokenNoCache(refreshToken).then(r => { this.refreshTokenPromises.delete(refreshToken); return r; }, e => { this.refreshTokenPromises.delete(refreshToken); throw e; }); this.refreshTokenPromises.set(refreshToken, p); return p; } async refreshTokenNoCache(refreshToken) { var _a; if (!refreshToken) { throw new Error('No refresh token is set.'); } const url = this.endpoints.oauth2TokenUrl.toString(); const data = { refresh_token: refreshToken, client_id: this._clientId, client_secret: this._clientSecret, grant_type: 'refresh_token', }; let res; try { // request for new token res = await this.transporter.request({ ...OAuth2Client.RETRY_CONFIG, method: 'POST', url, data: querystring.stringify(data), headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, }); } catch (e) { if (e instanceof gaxios_1.GaxiosError && e.message === 'invalid_grant' && ((_a = e.response) === null || _a === void 0 ? void 0 : _a.data) && /ReAuth/i.test(e.response.data.error_description)) { e.message = JSON.stringify(e.response.data); } throw e; } const tokens = res.data; // TODO: de-duplicate this code from a few spots if (res.data && res.data.expires_in) { tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000; delete tokens.expires_in; } this.emit('tokens', tokens); return { tokens, res }; } refreshAccessToken(callback) { if (callback) { this.refreshAccessTokenAsync().then(r => callback(null, r.credentials, r.res), callback); } else { return this.refreshAccessTokenAsync(); } } async refreshAccessTokenAsync() { const r = await this.refreshToken(this.credentials.refresh_token); const tokens = r.tokens; tokens.refresh_token = this.credentials.refresh_token; this.credentials = tokens; return { credentials: this.credentials, res: r.res }; } getAccessToken(callback) { if (callback) { this.getAccessTokenAsync().then(r => callback(null, r.token, r.res), callback); } else { return this.getAccessTokenAsync(); } } async getAccessTokenAsync() { const shouldRefresh = !this.credentials.access_token || this.isTokenExpiring(); if (shouldRefresh) { if (!this.credentials.refresh_token) { if (this.refreshHandler) { const refreshedAccessToken = await this.processAndValidateRefreshHandler(); if (refreshedAccessToken === null || refreshedAccessToken === void 0 ? void 0 : refreshedAccessToken.access_token) { this.setCredentials(refreshedAccessToken); return { token: this.credentials.access_token }; } } else { throw new Error('No refresh token or refresh handler callback is set.'); } } const r = await this.refreshAccessTokenAsync(); if (!r.credentials || (r.credentials && !r.credentials.access_token)) { throw new Error('Could not refresh access token.'); } return { token: r.credentials.access_token, res: r.res }; } else { return { token: this.credentials.access_token }; } } /** * The main authentication interface. It takes an optional url which when * present is the endpoint being accessed, and returns a Promise which * resolves with authorization header fields. * * In OAuth2Client, the result has the form: * { Authorization: 'Bearer ' } * @param url The optional url being authorized */ async getRequestHeaders(url) { const headers = (await this.getRequestMetadataAsync(url)).headers; return headers; } async getRequestMetadataAsync( // eslint-disable-next-line @typescript-eslint/no-unused-vars url) { const thisCreds = this.credentials; if (!thisCreds.access_token && !thisCreds.refresh_token && !this.apiKey && !this.refreshHandler) { throw new Error('No access, refresh token, API key or refresh handler callback is set.'); } if (thisCreds.access_token && !this.isTokenExpiring()) { thisCreds.token_type = thisCreds.token_type || 'Bearer'; const headers = { Authorization: thisCreds.token_type + ' ' + thisCreds.access_token, }; return { headers: this.addSharedMetadataHeaders(headers) }; } // If refreshHandler exists, call processAndValidateRefreshHandler(). if (this.refreshHandler) { const refreshedAccessToken = await this.processAndValidateRefreshHandler(); if (refreshedAccessToken === null || refreshedAccessToken === void 0 ? void 0 : refreshedAccessToken.access_token) { this.setCredentials(refreshedAccessToken); const headers = { Authorization: 'Bearer ' + this.credentials.access_token, }; return { headers: this.addSharedMetadataHeaders(headers) }; } } if (this.apiKey) { return { headers: { 'X-Goog-Api-Key': this.apiKey } }; } let r = null; let tokens = null; try { r = await this.refreshToken(thisCreds.refresh_token); tokens = r.tokens; } catch (err) { const e = err; if (e.response && (e.response.status === 403 || e.response.status === 404)) { e.message = `Could not refresh access token: ${e.message}`; } throw e; } const credentials = this.credentials; credentials.token_type = credentials.token_type || 'Bearer'; tokens.refresh_token = credentials.refresh_token; this.credentials = tokens; const headers = { Authorization: credentials.token_type + ' ' + tokens.access_token, }; return { headers: this.addSharedMetadataHeaders(headers), res: r.res }; } /** * Generates an URL to revoke the given token. * @param token The existing token to be revoked. * * @deprecated use instance method {@link OAuth2Client.getRevokeTokenURL} */ static getRevokeTokenUrl(token) { return new OAuth2Client().getRevokeTokenURL(token).toString(); } /** * Generates a URL to revoke the given token. * * @param token The existing token to be revoked. */ getRevokeTokenURL(token) { const url = new URL(this.endpoints.oauth2RevokeUrl); url.searchParams.append('token', token); return url; } revokeToken(token, callback) { const opts = { ...OAuth2Client.RETRY_CONFIG, url: this.getRevokeTokenURL(token).toString(), method: 'POST', }; if (callback) { this.transporter .request(opts) .then(r => callback(null, r), callback); } else { return this.transporter.request(opts); } } revokeCredentials(callback) { if (callback) { this.revokeCredentialsAsync().then(res => callback(null, res), callback); } else { return this.revokeCredentialsAsync(); } } async revokeCredentialsAsync() { const token = this.credentials.access_token; this.credentials = {}; if (token) { return this.revokeToken(token); } else { throw new Error('No access token to revoke.'); } } request(opts, callback) { if (callback) { this.requestAsync(opts).then(r => callback(null, r), e => { return callback(e, e.response); }); } else { return this.requestAsync(opts); } } async requestAsync(opts, reAuthRetried = false) { let r2; try { const r = await this.getRequestMetadataAsync(opts.url); opts.headers = opts.headers || {}; if (r.headers && r.headers['x-goog-user-project']) { opts.headers['x-goog-user-project'] = r.headers['x-goog-user-project']; } if (r.headers && r.headers.Authorization) { opts.headers.Authorization = r.headers.Authorization; } if (this.apiKey) { opts.headers['X-Goog-Api-Key'] = this.apiKey; } r2 = await this.transporter.request(opts); } catch (e) { const res = e.response; if (res) { const statusCode = res.status; // Retry the request for metadata if the following criteria are true: // - We haven't already retried. It only makes sense to retry once. // - The response was a 401 or a 403 // - The request didn't send a readableStream // - An access_token and refresh_token were available, but either no // expiry_date was available or the forceRefreshOnFailure flag is set. // The absent expiry_date case can happen when developers stash the // access_token and refresh_token for later use, but the access_token // fails on the first try because it's expired. Some developers may // choose to enable forceRefreshOnFailure to mitigate time-related // errors. // Or the following criteria are true: // - We haven't already retried. It only makes sense to retry once. // - The response was a 401 or a 403 // - The request didn't send a readableStream // - No refresh_token was available // - An access_token and a refreshHandler callback were available, but // either no expiry_date was available or the forceRefreshOnFailure // flag is set. The access_token fails on the first try because it's // expired. Some developers may choose to enable forceRefreshOnFailure // to mitigate time-related errors. const mayRequireRefresh = this.credentials && this.credentials.access_token && this.credentials.refresh_token && (!this.credentials.expiry_date || this.forceRefreshOnFailure); const mayRequireRefreshWithNoRefreshToken = this.credentials && this.credentials.access_token && !this.credentials.refresh_token && (!this.credentials.expiry_date || this.forceRefreshOnFailure) && this.refreshHandler; const isReadableStream = res.config.data instanceof stream.Readable; const isAuthErr = statusCode === 401 || statusCode === 403; if (!reAuthRetried && isAuthErr && !isReadableStream && mayRequireRefresh) { await this.refreshAccessTokenAsync(); return this.requestAsync(opts, true); } else if (!reAuthRetried && isAuthErr && !isReadableStream && mayRequireRefreshWithNoRefreshToken) { const refreshedAccessToken = await this.processAndValidateRefreshHandler(); if (refreshedAccessToken === null || refreshedAccessToken === void 0 ? void 0 : refreshedAccessToken.access_token) { this.setCredentials(refreshedAccessToken); } return this.requestAsync(opts, true); } } throw e; } return r2; } verifyIdToken(options, callback) { // This function used to accept two arguments instead of an options object. // Check the types to help users upgrade with less pain. // This check can be removed after a 2.0 release. if (callback && typeof callback !== 'function') { throw new Error('This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.'); } if (callback) { this.verifyIdTokenAsync(options).then(r => callback(null, r), callback); } else { return this.verifyIdTokenAsync(options); } } async verifyIdTokenAsync(options) { if (!options.idToken) { throw new Error('The verifyIdToken method requires an ID Token'); } const response = await this.getFederatedSignonCertsAsync(); const login = await this.verifySignedJwtWithCertsAsync(options.idToken, response.certs, options.audience, this.issuers, options.maxExpiry); return login; } /** * Obtains information about the provisioned access token. Especially useful * if you want to check the scopes that were provisioned to a given token. * * @param accessToken Required. The Access Token for which you want to get * user info. */ async getTokenInfo(accessToken) { const { data } = await this.transporter.request({ ...OAuth2Client.RETRY_CONFIG, method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', Authorization: `Bearer ${accessToken}`, }, url: this.endpoints.tokenInfoUrl.toString(), }); const info = Object.assign({ expiry_date: new Date().getTime() + data.expires_in * 1000, scopes: data.scope.split(' '), }, data); delete info.expires_in; delete info.scope; return info; } getFederatedSignonCerts(callback) { if (callback) { this.getFederatedSignonCertsAsync().then(r => callback(null, r.certs, r.res), callback); } else { return this.getFederatedSignonCertsAsync(); } } async getFederatedSignonCertsAsync() { const nowTime = new Date().getTime(); const format = (0, crypto_1.hasBrowserCrypto)() ? CertificateFormat.JWK : CertificateFormat.PEM; if (this.certificateExpiry && nowTime < this.certificateExpiry.getTime() && this.certificateCacheFormat === format) { return { certs: this.certificateCache, format }; } let res; let url; switch (format) { case CertificateFormat.PEM: url = this.endpoints.oauth2FederatedSignonPemCertsUrl.toString(); break; case CertificateFormat.JWK: url = this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString(); break; default: throw new Error(`Unsupported certificate format ${format}`); } try { res = await this.transporter.request({ ...OAuth2Client.RETRY_CONFIG, url, }); } catch (e) { if (e instanceof Error) { e.message = `Failed to retrieve verification certificates: ${e.message}`; } throw e; } const cacheControl = res ? res.headers['cache-control'] : undefined; let cacheAge = -1; if (cacheControl) { const pattern = new RegExp('max-age=([0-9]*)'); const regexResult = pattern.exec(cacheControl); if (regexResult && regexResult.length === 2) { // Cache results with max-age (in seconds) cacheAge = Number(regexResult[1]) * 1000; // milliseconds } } let certificates = {}; switch (format) { case CertificateFormat.PEM: certificates = res.data; break; case CertificateFormat.JWK: for (const key of res.data.keys) { certificates[key.kid] = key; } break; default: throw new Error(`Unsupported certificate format ${format}`); } const now = new Date(); this.certificateExpiry = cacheAge === -1 ? null : new Date(now.getTime() + cacheAge); this.certificateCache = certificates; this.certificateCacheFormat = format; return { certs: certificates, format, res }; } getIapPublicKeys(callback) { if (callback) { this.getIapPublicKeysAsync().then(r => callback(null, r.pubkeys, r.res), callback); } else { return this.getIapPublicKeysAsync(); } } async getIapPublicKeysAsync() { let res; const url = this.endpoints.oauth2IapPublicKeyUrl.toString(); try { res = await this.transporter.request({ ...OAuth2Client.RETRY_CONFIG, url, }); } catch (e) { if (e instanceof Error) { e.message = `Failed to retrieve verification certificates: ${e.message}`; } throw e; } return { pubkeys: res.data, res }; } verifySignedJwtWithCerts() { // To make the code compatible with browser SubtleCrypto we need to make // this method async. throw new Error('verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.'); } /** * Verify the id token is signed with the correct certificate * and is from the correct audience. * @param jwt The jwt to verify (The ID Token in this case). * @param certs The array of certs to test the jwt against. * @param requiredAudience The audience to test the jwt against. * @param issuers The allowed issuers of the jwt (Optional). * @param maxExpiry The max expiry the certificate can be (Optional). * @return Returns a promise resolving to LoginTicket on verification. */ async verifySignedJwtWithCertsAsync(jwt, certs, requiredAudience, issuers, maxExpiry) { const crypto = (0, crypto_1.createCrypto)(); if (!maxExpiry) { maxExpiry = OAuth2Client.DEFAULT_MAX_TOKEN_LIFETIME_SECS_; } const segments = jwt.split('.'); if (segments.length !== 3) { throw new Error('Wrong number of segments in token: ' + jwt); } const signed = segments[0] + '.' + segments[1]; let signature = segments[2]; let envelope; let payload; try { envelope = JSON.parse(crypto.decodeBase64StringUtf8(segments[0])); } catch (err) { if (err instanceof Error) { err.message = `Can't parse token envelope: ${segments[0]}': ${err.message}`; } throw err; } if (!envelope) { throw new Error("Can't parse token envelope: " + segments[0]); } try { payload = JSON.parse(crypto.decodeBase64StringUtf8(segments[1])); } catch (err) { if (err instanceof Error) { err.message = `Can't parse token payload '${segments[0]}`; } throw err; } if (!payload) { throw new Error("Can't parse token payload: " + segments[1]); } if (!Object.prototype.hasOwnProperty.call(certs, envelope.kid)) { // If this is not present, then there's no reason to attempt verification throw new Error('No pem found for envelope: ' + JSON.stringify(envelope)); } const cert = certs[envelope.kid]; if (envelope.alg === 'ES256') { signature = formatEcdsa.joseToDer(signature, 'ES256').toString('base64'); } const verified = await crypto.verify(cert, signed, signature); if (!verified) { throw new Error('Invalid token signature: ' + jwt); } if (!payload.iat) { throw new Error('No issue time in token: ' + JSON.stringify(payload)); } if (!payload.exp) { throw new Error('No expiration time in token: ' + JSON.stringify(payload)); } const iat = Number(payload.iat); if (isNaN(iat)) throw new Error('iat field using invalid format'); const exp = Number(payload.exp); if (isNaN(exp)) throw new Error('exp field using invalid format'); const now = new Date().getTime() / 1000; if (exp >= now + maxExpiry) { throw new Error('Expiration time too far in future: ' + JSON.stringify(payload)); } const earliest = iat - OAuth2Client.CLOCK_SKEW_SECS_; const latest = exp + OAuth2Client.CLOCK_SKEW_SECS_; if (now < earliest) { throw new Error('Token used too early, ' + now + ' < ' + earliest + ': ' + JSON.stringify(payload)); } if (now > latest) { throw new Error('Token used too late, ' + now + ' > ' + latest + ': ' + JSON.stringify(payload)); } if (issuers && issuers.indexOf(payload.iss) < 0) { throw new Error('Invalid issuer, expected one of [' + issuers + '], but got ' + payload.iss); } // Check the audience matches if we have one if (typeof requiredAudience !== 'undefined' && requiredAudience !== null) { const aud = payload.aud; let audVerified = false; // If the requiredAudience is an array, check if it contains token // audience if (requiredAudience.constructor === Array) { audVerified = requiredAudience.indexOf(aud) > -1; } else { audVerified = aud === requiredAudience; } if (!audVerified) { throw new Error('Wrong recipient, payload audience != requiredAudience'); } } return new loginticket_1.LoginTicket(envelope, payload); } /** * Returns a promise that resolves with AccessTokenResponse type if * refreshHandler is defined. * If not, nothing is returned. */ async processAndValidateRefreshHandler() { if (this.refreshHandler) { const accessTokenResponse = await this.refreshHandler(); if (!accessTokenResponse.access_token) { throw new Error('No access token is returned by the refreshHandler callback.'); } return accessTokenResponse; } return; } /** * Returns true if a token is expired or will expire within * eagerRefreshThresholdMillismilliseconds. * If there is no expiry time, assumes the token is not expired or expiring. */ isTokenExpiring() { const expiryDate = this.credentials.expiry_date; return expiryDate ? expiryDate <= new Date().getTime() + this.eagerRefreshThresholdMillis : false; } } exports.OAuth2Client = OAuth2Client; /** * @deprecated use instance's {@link OAuth2Client.endpoints} */ OAuth2Client.GOOGLE_TOKEN_INFO_URL = 'https://oauth2.googleapis.com/tokeninfo'; /** * Clock skew - five minutes in seconds */ OAuth2Client.CLOCK_SKEW_SECS_ = 300; /** * The default max Token Lifetime is one day in seconds */ OAuth2Client.DEFAULT_MAX_TOKEN_LIFETIME_SECS_ = 86400; /***/ }), /***/ 6653: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.OAuthClientAuthHandler = void 0; exports.getErrorFromOAuthErrorResponse = getErrorFromOAuthErrorResponse; const querystring = __nccwpck_require__(3480); const crypto_1 = __nccwpck_require__(8851); /** List of HTTP methods that accept request bodies. */ const METHODS_SUPPORTING_REQUEST_BODY = ['PUT', 'POST', 'PATCH']; /** * Abstract class for handling client authentication in OAuth-based * operations. * When request-body client authentication is used, only application/json and * application/x-www-form-urlencoded content types for HTTP methods that support * request bodies are supported. */ class OAuthClientAuthHandler { /** * Instantiates an OAuth client authentication handler. * @param clientAuthentication The client auth credentials. */ constructor(clientAuthentication) { this.clientAuthentication = clientAuthentication; this.crypto = (0, crypto_1.createCrypto)(); } /** * Applies client authentication on the OAuth request's headers or POST * body but does not process the request. * @param opts The GaxiosOptions whose headers or data are to be modified * depending on the client authentication mechanism to be used. * @param bearerToken The optional bearer token to use for authentication. * When this is used, no client authentication credentials are needed. */ applyClientAuthenticationOptions(opts, bearerToken) { // Inject authenticated header. this.injectAuthenticatedHeaders(opts, bearerToken); // Inject authenticated request body. if (!bearerToken) { this.injectAuthenticatedRequestBody(opts); } } /** * Applies client authentication on the request's header if either * basic authentication or bearer token authentication is selected. * * @param opts The GaxiosOptions whose headers or data are to be modified * depending on the client authentication mechanism to be used. * @param bearerToken The optional bearer token to use for authentication. * When this is used, no client authentication credentials are needed. */ injectAuthenticatedHeaders(opts, bearerToken) { var _a; // Bearer token prioritized higher than basic Auth. if (bearerToken) { opts.headers = opts.headers || {}; Object.assign(opts.headers, { Authorization: `Bearer ${bearerToken}}`, }); } else if (((_a = this.clientAuthentication) === null || _a === void 0 ? void 0 : _a.confidentialClientType) === 'basic') { opts.headers = opts.headers || {}; const clientId = this.clientAuthentication.clientId; const clientSecret = this.clientAuthentication.clientSecret || ''; const base64EncodedCreds = this.crypto.encodeBase64StringUtf8(`${clientId}:${clientSecret}`); Object.assign(opts.headers, { Authorization: `Basic ${base64EncodedCreds}`, }); } } /** * Applies client authentication on the request's body if request-body * client authentication is selected. * * @param opts The GaxiosOptions whose headers or data are to be modified * depending on the client authentication mechanism to be used. */ injectAuthenticatedRequestBody(opts) { var _a; if (((_a = this.clientAuthentication) === null || _a === void 0 ? void 0 : _a.confidentialClientType) === 'request-body') { const method = (opts.method || 'GET').toUpperCase(); // Inject authenticated request body. if (METHODS_SUPPORTING_REQUEST_BODY.indexOf(method) !== -1) { // Get content-type. let contentType; const headers = opts.headers || {}; for (const key in headers) { if (key.toLowerCase() === 'content-type' && headers[key]) { contentType = headers[key].toLowerCase(); break; } } if (contentType === 'application/x-www-form-urlencoded') { opts.data = opts.data || ''; const data = querystring.parse(opts.data); Object.assign(data, { client_id: this.clientAuthentication.clientId, client_secret: this.clientAuthentication.clientSecret || '', }); opts.data = querystring.stringify(data); } else if (contentType === 'application/json') { opts.data = opts.data || {}; Object.assign(opts.data, { client_id: this.clientAuthentication.clientId, client_secret: this.clientAuthentication.clientSecret || '', }); } else { throw new Error(`${contentType} content-types are not supported with ` + `${this.clientAuthentication.confidentialClientType} ` + 'client authentication'); } } else { throw new Error(`${method} HTTP method does not support ` + `${this.clientAuthentication.confidentialClientType} ` + 'client authentication'); } } } /** * Retry config for Auth-related requests. * * @remarks * * This is not a part of the default {@link AuthClient.transporter transporter/gaxios} * config as some downstream APIs would prefer if customers explicitly enable retries, * such as GCS. */ static get RETRY_CONFIG() { return { retry: true, retryConfig: { httpMethodsToRetry: ['GET', 'PUT', 'POST', 'HEAD', 'OPTIONS', 'DELETE'], }, }; } } exports.OAuthClientAuthHandler = OAuthClientAuthHandler; /** * Converts an OAuth error response to a native JavaScript Error. * @param resp The OAuth error response to convert to a native Error object. * @param err The optional original error. If provided, the error properties * will be copied to the new error. * @return The converted native Error object. */ function getErrorFromOAuthErrorResponse(resp, err) { // Error response. const errorCode = resp.error; const errorDescription = resp.error_description; const errorUri = resp.error_uri; let message = `Error code ${errorCode}`; if (typeof errorDescription !== 'undefined') { message += `: ${errorDescription}`; } if (typeof errorUri !== 'undefined') { message += ` - ${errorUri}`; } const newError = new Error(message); // Copy properties from original error to newly generated error. if (err) { const keys = Object.keys(err); if (err.stack) { // Copy error.stack if available. keys.push('stack'); } keys.forEach(key => { // Do not overwrite the message field. if (key !== 'message') { Object.defineProperty(newError, key, { // eslint-disable-next-line @typescript-eslint/no-explicit-any value: err[key], writable: false, enumerable: true, }); } }); } return newError; } /***/ }), /***/ 2045: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright 2024 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PassThroughClient = void 0; const authclient_1 = __nccwpck_require__(4810); /** * An AuthClient without any Authentication information. Useful for: * - Anonymous access * - Local Emulators * - Testing Environments * */ class PassThroughClient extends authclient_1.AuthClient { /** * Creates a request without any authentication headers or checks. * * @remarks * * In testing environments it may be useful to change the provided * {@link AuthClient.transporter} for any desired request overrides/handling. * * @param opts * @returns The response of the request. */ async request(opts) { return this.transporter.request(opts); } /** * A required method of the base class. * Always will return an empty object. * * @returns {} */ async getAccessToken() { return {}; } /** * A required method of the base class. * Always will return an empty object. * * @returns {} */ async getRequestHeaders() { return {}; } } exports.PassThroughClient = PassThroughClient; const a = new PassThroughClient(); a.getAccessToken(); /***/ }), /***/ 6077: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PluggableAuthClient = exports.ExecutableError = void 0; const baseexternalclient_1 = __nccwpck_require__(142); const executable_response_1 = __nccwpck_require__(3247); const pluggable_auth_handler_1 = __nccwpck_require__(908); /** * Error thrown from the executable run by PluggableAuthClient. */ class ExecutableError extends Error { constructor(message, code) { super(`The executable failed with exit code: ${code} and error message: ${message}.`); this.code = code; Object.setPrototypeOf(this, new.target.prototype); } } exports.ExecutableError = ExecutableError; /** * The default executable timeout when none is provided, in milliseconds. */ const DEFAULT_EXECUTABLE_TIMEOUT_MILLIS = 30 * 1000; /** * The minimum allowed executable timeout in milliseconds. */ const MINIMUM_EXECUTABLE_TIMEOUT_MILLIS = 5 * 1000; /** * The maximum allowed executable timeout in milliseconds. */ const MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS = 120 * 1000; /** * The environment variable to check to see if executable can be run. * Value must be set to '1' for the executable to run. */ const GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES = 'GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES'; /** * The maximum currently supported executable version. */ const MAXIMUM_EXECUTABLE_VERSION = 1; /** * PluggableAuthClient enables the exchange of workload identity pool external credentials for * Google access tokens by retrieving 3rd party tokens through a user supplied executable. These * scripts/executables are completely independent of the Google Cloud Auth libraries. These * credentials plug into ADC and will call the specified executable to retrieve the 3rd party token * to be exchanged for a Google access token. * *

To use these credentials, the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable * must be set to '1'. This is for security reasons. * *

Both OIDC and SAML are supported. The executable must adhere to a specific response format * defined below. * *

The executable must print out the 3rd party token to STDOUT in JSON format. When an * output_file is specified in the credential configuration, the executable must also handle writing the * JSON response to this file. * *

 * OIDC response sample:
 * {
 *   "version": 1,
 *   "success": true,
 *   "token_type": "urn:ietf:params:oauth:token-type:id_token",
 *   "id_token": "HEADER.PAYLOAD.SIGNATURE",
 *   "expiration_time": 1620433341
 * }
 *
 * SAML2 response sample:
 * {
 *   "version": 1,
 *   "success": true,
 *   "token_type": "urn:ietf:params:oauth:token-type:saml2",
 *   "saml_response": "...",
 *   "expiration_time": 1620433341
 * }
 *
 * Error response sample:
 * {
 *   "version": 1,
 *   "success": false,
 *   "code": "401",
 *   "message": "Error message."
 * }
 * 
* *

The "expiration_time" field in the JSON response is only required for successful * responses when an output file was specified in the credential configuration * *

The auth libraries will populate certain environment variables that will be accessible by the * executable, such as: GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE, GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE, * GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE, GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL, and * GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE. * *

Please see this repositories README for a complete executable request/response specification. */ class PluggableAuthClient extends baseexternalclient_1.BaseExternalAccountClient { /** * Instantiates a PluggableAuthClient instance using the provided JSON * object loaded from an external account credentials file. * An error is thrown if the credential is not a valid pluggable auth credential. * @param options The external account options object typically loaded from * the external account JSON credential file. * @param additionalOptions **DEPRECATED, all options are available in the * `options` parameter.** Optional additional behavior customization options. * These currently customize expiration threshold time and whether to retry * on 401/403 API request errors. */ constructor(options, additionalOptions) { super(options, additionalOptions); if (!options.credential_source.executable) { throw new Error('No valid Pluggable Auth "credential_source" provided.'); } this.command = options.credential_source.executable.command; if (!this.command) { throw new Error('No valid Pluggable Auth "credential_source" provided.'); } // Check if the provided timeout exists and if it is valid. if (options.credential_source.executable.timeout_millis === undefined) { this.timeoutMillis = DEFAULT_EXECUTABLE_TIMEOUT_MILLIS; } else { this.timeoutMillis = options.credential_source.executable.timeout_millis; if (this.timeoutMillis < MINIMUM_EXECUTABLE_TIMEOUT_MILLIS || this.timeoutMillis > MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS) { throw new Error(`Timeout must be between ${MINIMUM_EXECUTABLE_TIMEOUT_MILLIS} and ` + `${MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS} milliseconds.`); } } this.outputFile = options.credential_source.executable.output_file; this.handler = new pluggable_auth_handler_1.PluggableAuthHandler({ command: this.command, timeoutMillis: this.timeoutMillis, outputFile: this.outputFile, }); this.credentialSourceType = 'executable'; } /** * Triggered when an external subject token is needed to be exchanged for a * GCP access token via GCP STS endpoint. * This uses the `options.credential_source` object to figure out how * to retrieve the token using the current environment. In this case, * this calls a user provided executable which returns the subject token. * The logic is summarized as: * 1. Validated that the executable is allowed to run. The * GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment must be set to * 1 for security reasons. * 2. If an output file is specified by the user, check the file location * for a response. If the file exists and contains a valid response, * return the subject token from the file. * 3. Call the provided executable and return response. * @return A promise that resolves with the external subject token. */ async retrieveSubjectToken() { // Check if the executable is allowed to run. if (process.env[GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES] !== '1') { throw new Error('Pluggable Auth executables need to be explicitly allowed to run by ' + 'setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment ' + 'Variable to 1.'); } let executableResponse = undefined; // Try to get cached executable response from output file. if (this.outputFile) { executableResponse = await this.handler.retrieveCachedResponse(); } // If no response from output file, call the executable. if (!executableResponse) { // Set up environment map with required values for the executable. const envMap = new Map(); envMap.set('GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE', this.audience); envMap.set('GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE', this.subjectTokenType); // Always set to 0 because interactive mode is not supported. envMap.set('GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE', '0'); if (this.outputFile) { envMap.set('GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE', this.outputFile); } const serviceAccountEmail = this.getServiceAccountEmail(); if (serviceAccountEmail) { envMap.set('GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL', serviceAccountEmail); } executableResponse = await this.handler.retrieveResponseFromExecutable(envMap); } if (executableResponse.version > MAXIMUM_EXECUTABLE_VERSION) { throw new Error(`Version of executable is not currently supported, maximum supported version is ${MAXIMUM_EXECUTABLE_VERSION}.`); } // Check that response was successful. if (!executableResponse.success) { throw new ExecutableError(executableResponse.errorMessage, executableResponse.errorCode); } // Check that response contains expiration time if output file was specified. if (this.outputFile) { if (!executableResponse.expirationTime) { throw new executable_response_1.InvalidExpirationTimeFieldError('The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.'); } } // Check that response is not expired. if (executableResponse.isExpired()) { throw new Error('Executable response is expired.'); } // Return subject token from response. return executableResponse.subjectToken; } } exports.PluggableAuthClient = PluggableAuthClient; /***/ }), /***/ 908: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PluggableAuthHandler = void 0; const pluggable_auth_client_1 = __nccwpck_require__(6077); const executable_response_1 = __nccwpck_require__(3247); const childProcess = __nccwpck_require__(5317); const fs = __nccwpck_require__(9896); /** * A handler used to retrieve 3rd party token responses from user defined * executables and cached file output for the PluggableAuthClient class. */ class PluggableAuthHandler { /** * Instantiates a PluggableAuthHandler instance using the provided * PluggableAuthHandlerOptions object. */ constructor(options) { if (!options.command) { throw new Error('No command provided.'); } this.commandComponents = PluggableAuthHandler.parseCommand(options.command); this.timeoutMillis = options.timeoutMillis; if (!this.timeoutMillis) { throw new Error('No timeoutMillis provided.'); } this.outputFile = options.outputFile; } /** * Calls user provided executable to get a 3rd party subject token and * returns the response. * @param envMap a Map of additional Environment Variables required for * the executable. * @return A promise that resolves with the executable response. */ retrieveResponseFromExecutable(envMap) { return new Promise((resolve, reject) => { // Spawn process to run executable using added environment variables. const child = childProcess.spawn(this.commandComponents[0], this.commandComponents.slice(1), { env: { ...process.env, ...Object.fromEntries(envMap) }, }); let output = ''; // Append stdout to output as executable runs. child.stdout.on('data', (data) => { output += data; }); // Append stderr as executable runs. child.stderr.on('data', (err) => { output += err; }); // Set up a timeout to end the child process and throw an error. const timeout = setTimeout(() => { // Kill child process and remove listeners so 'close' event doesn't get // read after child process is killed. child.removeAllListeners(); child.kill(); return reject(new Error('The executable failed to finish within the timeout specified.')); }, this.timeoutMillis); child.on('close', (code) => { // Cancel timeout if executable closes before timeout is reached. clearTimeout(timeout); if (code === 0) { // If the executable completed successfully, try to return the parsed response. try { const responseJson = JSON.parse(output); const response = new executable_response_1.ExecutableResponse(responseJson); return resolve(response); } catch (error) { if (error instanceof executable_response_1.ExecutableResponseError) { return reject(error); } return reject(new executable_response_1.ExecutableResponseError(`The executable returned an invalid response: ${output}`)); } } else { return reject(new pluggable_auth_client_1.ExecutableError(output, code.toString())); } }); }); } /** * Checks user provided output file for response from previous run of * executable and return the response if it exists, is formatted correctly, and is not expired. */ async retrieveCachedResponse() { if (!this.outputFile || this.outputFile.length === 0) { return undefined; } let filePath; try { filePath = await fs.promises.realpath(this.outputFile); } catch (_a) { // If file path cannot be resolved, return undefined. return undefined; } if (!(await fs.promises.lstat(filePath)).isFile()) { // If path does not lead to file, return undefined. return undefined; } const responseString = await fs.promises.readFile(filePath, { encoding: 'utf8', }); if (responseString === '') { return undefined; } try { const responseJson = JSON.parse(responseString); const response = new executable_response_1.ExecutableResponse(responseJson); // Check if response is successful and unexpired. if (response.isValid()) { return new executable_response_1.ExecutableResponse(responseJson); } return undefined; } catch (error) { if (error instanceof executable_response_1.ExecutableResponseError) { throw error; } throw new executable_response_1.ExecutableResponseError(`The output file contained an invalid response: ${responseString}`); } } /** * Parses given command string into component array, splitting on spaces unless * spaces are between quotation marks. */ static parseCommand(command) { // Split the command into components by splitting on spaces, // unless spaces are contained in quotation marks. const components = command.match(/(?:[^\s"]+|"[^"]*")+/g); if (!components) { throw new Error(`Provided command: "${command}" could not be parsed.`); } // Remove quotation marks from the beginning and end of each component if they are present. for (let i = 0; i < components.length; i++) { if (components[i][0] === '"' && components[i].slice(-1) === '"') { components[i] = components[i].slice(1, -1); } } return components; } } exports.PluggableAuthHandler = PluggableAuthHandler; /***/ }), /***/ 9807: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright 2015 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UserRefreshClient = exports.USER_REFRESH_ACCOUNT_TYPE = void 0; const oauth2client_1 = __nccwpck_require__(91); const querystring_1 = __nccwpck_require__(3480); exports.USER_REFRESH_ACCOUNT_TYPE = 'authorized_user'; class UserRefreshClient extends oauth2client_1.OAuth2Client { constructor(optionsOrClientId, clientSecret, refreshToken, eagerRefreshThresholdMillis, forceRefreshOnFailure) { const opts = optionsOrClientId && typeof optionsOrClientId === 'object' ? optionsOrClientId : { clientId: optionsOrClientId, clientSecret, refreshToken, eagerRefreshThresholdMillis, forceRefreshOnFailure, }; super(opts); this._refreshToken = opts.refreshToken; this.credentials.refresh_token = opts.refreshToken; } /** * Refreshes the access token. * @param refreshToken An ignored refreshToken.. * @param callback Optional callback. */ async refreshTokenNoCache( // eslint-disable-next-line @typescript-eslint/no-unused-vars refreshToken) { return super.refreshTokenNoCache(this._refreshToken); } async fetchIdToken(targetAudience) { const res = await this.transporter.request({ ...UserRefreshClient.RETRY_CONFIG, url: this.endpoints.oauth2TokenUrl, headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, method: 'POST', data: (0, querystring_1.stringify)({ client_id: this._clientId, client_secret: this._clientSecret, grant_type: 'refresh_token', refresh_token: this._refreshToken, target_audience: targetAudience, }), }); return res.data.id_token; } /** * Create a UserRefreshClient credentials instance using the given input * options. * @param json The input object. */ fromJSON(json) { if (!json) { throw new Error('Must pass in a JSON object containing the user refresh token'); } if (json.type !== 'authorized_user') { throw new Error('The incoming JSON object does not have the "authorized_user" type'); } if (!json.client_id) { throw new Error('The incoming JSON object does not contain a client_id field'); } if (!json.client_secret) { throw new Error('The incoming JSON object does not contain a client_secret field'); } if (!json.refresh_token) { throw new Error('The incoming JSON object does not contain a refresh_token field'); } this._clientId = json.client_id; this._clientSecret = json.client_secret; this._refreshToken = json.refresh_token; this.credentials.refresh_token = json.refresh_token; this.quotaProjectId = json.quota_project_id; this.universeDomain = json.universe_domain || this.universeDomain; } fromStream(inputStream, callback) { if (callback) { this.fromStreamAsync(inputStream).then(() => callback(), callback); } else { return this.fromStreamAsync(inputStream); } } async fromStreamAsync(inputStream) { return new Promise((resolve, reject) => { if (!inputStream) { return reject(new Error('Must pass in a stream containing the user refresh token.')); } let s = ''; inputStream .setEncoding('utf8') .on('error', reject) .on('data', chunk => (s += chunk)) .on('end', () => { try { const data = JSON.parse(s); this.fromJSON(data); return resolve(); } catch (err) { return reject(err); } }); }); } /** * Create a UserRefreshClient credentials instance using the given input * options. * @param json The input object. */ static fromJSON(json) { const client = new UserRefreshClient(); client.fromJSON(json); return client; } } exports.UserRefreshClient = UserRefreshClient; /***/ }), /***/ 121: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.StsCredentials = void 0; const gaxios_1 = __nccwpck_require__(7003); const querystring = __nccwpck_require__(3480); const transporters_1 = __nccwpck_require__(7633); const oauth2common_1 = __nccwpck_require__(6653); /** * Implements the OAuth 2.0 token exchange based on * https://tools.ietf.org/html/rfc8693 */ class StsCredentials extends oauth2common_1.OAuthClientAuthHandler { /** * Initializes an STS credentials instance. * @param tokenExchangeEndpoint The token exchange endpoint. * @param clientAuthentication The client authentication credentials if * available. */ constructor(tokenExchangeEndpoint, clientAuthentication) { super(clientAuthentication); this.tokenExchangeEndpoint = tokenExchangeEndpoint; this.transporter = new transporters_1.DefaultTransporter(); } /** * Exchanges the provided token for another type of token based on the * rfc8693 spec. * @param stsCredentialsOptions The token exchange options used to populate * the token exchange request. * @param additionalHeaders Optional additional headers to pass along the * request. * @param options Optional additional GCP-specific non-spec defined options * to send with the request. * Example: `&options=${encodeUriComponent(JSON.stringified(options))}` * @return A promise that resolves with the token exchange response containing * the requested token and its expiration time. */ async exchangeToken(stsCredentialsOptions, additionalHeaders, // eslint-disable-next-line @typescript-eslint/no-explicit-any options) { var _a, _b, _c; const values = { grant_type: stsCredentialsOptions.grantType, resource: stsCredentialsOptions.resource, audience: stsCredentialsOptions.audience, scope: (_a = stsCredentialsOptions.scope) === null || _a === void 0 ? void 0 : _a.join(' '), requested_token_type: stsCredentialsOptions.requestedTokenType, subject_token: stsCredentialsOptions.subjectToken, subject_token_type: stsCredentialsOptions.subjectTokenType, actor_token: (_b = stsCredentialsOptions.actingParty) === null || _b === void 0 ? void 0 : _b.actorToken, actor_token_type: (_c = stsCredentialsOptions.actingParty) === null || _c === void 0 ? void 0 : _c.actorTokenType, // Non-standard GCP-specific options. options: options && JSON.stringify(options), }; // Remove undefined fields. Object.keys(values).forEach(key => { // eslint-disable-next-line @typescript-eslint/no-explicit-any if (typeof values[key] === 'undefined') { // eslint-disable-next-line @typescript-eslint/no-explicit-any delete values[key]; } }); const headers = { 'Content-Type': 'application/x-www-form-urlencoded', }; // Inject additional STS headers if available. Object.assign(headers, additionalHeaders || {}); const opts = { ...StsCredentials.RETRY_CONFIG, url: this.tokenExchangeEndpoint.toString(), method: 'POST', headers, data: querystring.stringify(values), responseType: 'json', }; // Apply OAuth client authentication. this.applyClientAuthenticationOptions(opts); try { const response = await this.transporter.request(opts); // Successful response. const stsSuccessfulResponse = response.data; stsSuccessfulResponse.res = response; return stsSuccessfulResponse; } catch (error) { // Translate error to OAuthError. if (error instanceof gaxios_1.GaxiosError && error.response) { throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data, // Preserve other fields from the original error. error); } // Request could fail before the server responds. throw error; } } } exports.StsCredentials = StsCredentials; /***/ }), /***/ 4627: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright 2024 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UrlSubjectTokenSupplier = void 0; /** * Internal subject token supplier implementation used when a URL * is configured in the credential configuration used to build an {@link IdentityPoolClient} */ class UrlSubjectTokenSupplier { /** * Instantiates a URL subject token supplier. * @param opts The URL subject token supplier options to build the supplier with. */ constructor(opts) { this.url = opts.url; this.formatType = opts.formatType; this.subjectTokenFieldName = opts.subjectTokenFieldName; this.headers = opts.headers; this.additionalGaxiosOptions = opts.additionalGaxiosOptions; } /** * Sends a GET request to the URL provided in the constructor and resolves * with the returned external subject token. * @param context {@link ExternalAccountSupplierContext} from the calling * {@link IdentityPoolClient}, contains the requested audience and subject * token type for the external account identity. Not used. */ async getSubjectToken(context) { const opts = { ...this.additionalGaxiosOptions, url: this.url, method: 'GET', headers: this.headers, responseType: this.formatType, }; let subjectToken; if (this.formatType === 'text') { const response = await context.transporter.request(opts); subjectToken = response.data; } else if (this.formatType === 'json' && this.subjectTokenFieldName) { const response = await context.transporter.request(opts); subjectToken = response.data[this.subjectTokenFieldName]; } if (!subjectToken) { throw new Error('Unable to parse the subject_token from the credential_source URL'); } return subjectToken; } } exports.UrlSubjectTokenSupplier = UrlSubjectTokenSupplier; /***/ }), /***/ 3438: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* global window */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BrowserCrypto = void 0; // This file implements crypto functions we need using in-browser // SubtleCrypto interface `window.crypto.subtle`. const base64js = __nccwpck_require__(8793); const crypto_1 = __nccwpck_require__(8851); class BrowserCrypto { constructor() { if (typeof window === 'undefined' || window.crypto === undefined || window.crypto.subtle === undefined) { throw new Error("SubtleCrypto not found. Make sure it's an https:// website."); } } async sha256DigestBase64(str) { // SubtleCrypto digest() method is async, so we must make // this method async as well. // To calculate SHA256 digest using SubtleCrypto, we first // need to convert an input string to an ArrayBuffer: const inputBuffer = new TextEncoder().encode(str); // Result is ArrayBuffer as well. const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer); return base64js.fromByteArray(new Uint8Array(outputBuffer)); } randomBytesBase64(count) { const array = new Uint8Array(count); window.crypto.getRandomValues(array); return base64js.fromByteArray(array); } static padBase64(base64) { // base64js requires padding, so let's add some '=' while (base64.length % 4 !== 0) { base64 += '='; } return base64; } async verify(pubkey, data, signature) { const algo = { name: 'RSASSA-PKCS1-v1_5', hash: { name: 'SHA-256' }, }; const dataArray = new TextEncoder().encode(data); const signatureArray = base64js.toByteArray(BrowserCrypto.padBase64(signature)); const cryptoKey = await window.crypto.subtle.importKey('jwk', pubkey, algo, true, ['verify']); // SubtleCrypto's verify method is async so we must make // this method async as well. const result = await window.crypto.subtle.verify(algo, cryptoKey, signatureArray, dataArray); return result; } async sign(privateKey, data) { const algo = { name: 'RSASSA-PKCS1-v1_5', hash: { name: 'SHA-256' }, }; const dataArray = new TextEncoder().encode(data); const cryptoKey = await window.crypto.subtle.importKey('jwk', privateKey, algo, true, ['sign']); // SubtleCrypto's sign method is async so we must make // this method async as well. const result = await window.crypto.subtle.sign(algo, cryptoKey, dataArray); return base64js.fromByteArray(new Uint8Array(result)); } decodeBase64StringUtf8(base64) { const uint8array = base64js.toByteArray(BrowserCrypto.padBase64(base64)); const result = new TextDecoder().decode(uint8array); return result; } encodeBase64StringUtf8(text) { const uint8array = new TextEncoder().encode(text); const result = base64js.fromByteArray(uint8array); return result; } /** * Computes the SHA-256 hash of the provided string. * @param str The plain text string to hash. * @return A promise that resolves with the SHA-256 hash of the provided * string in hexadecimal encoding. */ async sha256DigestHex(str) { // SubtleCrypto digest() method is async, so we must make // this method async as well. // To calculate SHA256 digest using SubtleCrypto, we first // need to convert an input string to an ArrayBuffer: const inputBuffer = new TextEncoder().encode(str); // Result is ArrayBuffer as well. const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer); return (0, crypto_1.fromArrayBufferToHex)(outputBuffer); } /** * Computes the HMAC hash of a message using the provided crypto key and the * SHA-256 algorithm. * @param key The secret crypto key in utf-8 or ArrayBuffer format. * @param msg The plain text message. * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer * format. */ async signWithHmacSha256(key, msg) { // Convert key, if provided in ArrayBuffer format, to string. const rawKey = typeof key === 'string' ? key : String.fromCharCode(...new Uint16Array(key)); const enc = new TextEncoder(); const cryptoKey = await window.crypto.subtle.importKey('raw', enc.encode(rawKey), { name: 'HMAC', hash: { name: 'SHA-256', }, }, false, ['sign']); return window.crypto.subtle.sign('HMAC', cryptoKey, enc.encode(msg)); } } exports.BrowserCrypto = BrowserCrypto; /***/ }), /***/ 8851: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* global window */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createCrypto = createCrypto; exports.hasBrowserCrypto = hasBrowserCrypto; exports.fromArrayBufferToHex = fromArrayBufferToHex; const crypto_1 = __nccwpck_require__(3438); const crypto_2 = __nccwpck_require__(7388); function createCrypto() { if (hasBrowserCrypto()) { return new crypto_1.BrowserCrypto(); } return new crypto_2.NodeCrypto(); } function hasBrowserCrypto() { return (typeof window !== 'undefined' && typeof window.crypto !== 'undefined' && typeof window.crypto.subtle !== 'undefined'); } /** * Converts an ArrayBuffer to a hexadecimal string. * @param arrayBuffer The ArrayBuffer to convert to hexadecimal string. * @return The hexadecimal encoding of the ArrayBuffer. */ function fromArrayBufferToHex(arrayBuffer) { // Convert buffer to byte array. const byteArray = Array.from(new Uint8Array(arrayBuffer)); // Convert bytes to hex string. return byteArray .map(byte => { return byte.toString(16).padStart(2, '0'); }) .join(''); } /***/ }), /***/ 7388: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NodeCrypto = void 0; const crypto = __nccwpck_require__(6982); class NodeCrypto { async sha256DigestBase64(str) { return crypto.createHash('sha256').update(str).digest('base64'); } randomBytesBase64(count) { return crypto.randomBytes(count).toString('base64'); } async verify(pubkey, data, signature) { const verifier = crypto.createVerify('RSA-SHA256'); verifier.update(data); verifier.end(); return verifier.verify(pubkey, signature, 'base64'); } async sign(privateKey, data) { const signer = crypto.createSign('RSA-SHA256'); signer.update(data); signer.end(); return signer.sign(privateKey, 'base64'); } decodeBase64StringUtf8(base64) { return Buffer.from(base64, 'base64').toString('utf-8'); } encodeBase64StringUtf8(text) { return Buffer.from(text, 'utf-8').toString('base64'); } /** * Computes the SHA-256 hash of the provided string. * @param str The plain text string to hash. * @return A promise that resolves with the SHA-256 hash of the provided * string in hexadecimal encoding. */ async sha256DigestHex(str) { return crypto.createHash('sha256').update(str).digest('hex'); } /** * Computes the HMAC hash of a message using the provided crypto key and the * SHA-256 algorithm. * @param key The secret crypto key in utf-8 or ArrayBuffer format. * @param msg The plain text message. * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer * format. */ async signWithHmacSha256(key, msg) { const cryptoKey = typeof key === 'string' ? key : toBuffer(key); return toArrayBuffer(crypto.createHmac('sha256', cryptoKey).update(msg).digest()); } } exports.NodeCrypto = NodeCrypto; /** * Converts a Node.js Buffer to an ArrayBuffer. * https://stackoverflow.com/questions/8609289/convert-a-binary-nodejs-buffer-to-javascript-arraybuffer * @param buffer The Buffer input to covert. * @return The ArrayBuffer representation of the input. */ function toArrayBuffer(buffer) { return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength); } /** * Converts an ArrayBuffer to a Node.js Buffer. * @param arrayBuffer The ArrayBuffer input to covert. * @return The Buffer representation of the input. */ function toBuffer(arrayBuffer) { return Buffer.from(arrayBuffer); } /***/ }), /***/ 492: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GoogleAuth = exports.auth = exports.DefaultTransporter = exports.PassThroughClient = exports.ExecutableError = exports.PluggableAuthClient = exports.DownscopedClient = exports.BaseExternalAccountClient = exports.ExternalAccountClient = exports.IdentityPoolClient = exports.AwsRequestSigner = exports.AwsClient = exports.UserRefreshClient = exports.LoginTicket = exports.ClientAuthentication = exports.OAuth2Client = exports.CodeChallengeMethod = exports.Impersonated = exports.JWT = exports.JWTAccess = exports.IdTokenClient = exports.IAMAuth = exports.GCPEnv = exports.Compute = exports.DEFAULT_UNIVERSE = exports.AuthClient = exports.gaxios = exports.gcpMetadata = void 0; // Copyright 2017 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. const googleauth_1 = __nccwpck_require__(5934); Object.defineProperty(exports, "GoogleAuth", ({ enumerable: true, get: function () { return googleauth_1.GoogleAuth; } })); // Export common deps to ensure types/instances are the exact match. Useful // for consistently configuring the library across versions. exports.gcpMetadata = __nccwpck_require__(3046); exports.gaxios = __nccwpck_require__(7003); var authclient_1 = __nccwpck_require__(4810); Object.defineProperty(exports, "AuthClient", ({ enumerable: true, get: function () { return authclient_1.AuthClient; } })); Object.defineProperty(exports, "DEFAULT_UNIVERSE", ({ enumerable: true, get: function () { return authclient_1.DEFAULT_UNIVERSE; } })); var computeclient_1 = __nccwpck_require__(977); Object.defineProperty(exports, "Compute", ({ enumerable: true, get: function () { return computeclient_1.Compute; } })); var envDetect_1 = __nccwpck_require__(963); Object.defineProperty(exports, "GCPEnv", ({ enumerable: true, get: function () { return envDetect_1.GCPEnv; } })); var iam_1 = __nccwpck_require__(7009); Object.defineProperty(exports, "IAMAuth", ({ enumerable: true, get: function () { return iam_1.IAMAuth; } })); var idtokenclient_1 = __nccwpck_require__(2718); Object.defineProperty(exports, "IdTokenClient", ({ enumerable: true, get: function () { return idtokenclient_1.IdTokenClient; } })); var jwtaccess_1 = __nccwpck_require__(7060); Object.defineProperty(exports, "JWTAccess", ({ enumerable: true, get: function () { return jwtaccess_1.JWTAccess; } })); var jwtclient_1 = __nccwpck_require__(5277); Object.defineProperty(exports, "JWT", ({ enumerable: true, get: function () { return jwtclient_1.JWT; } })); var impersonated_1 = __nccwpck_require__(9964); Object.defineProperty(exports, "Impersonated", ({ enumerable: true, get: function () { return impersonated_1.Impersonated; } })); var oauth2client_1 = __nccwpck_require__(91); Object.defineProperty(exports, "CodeChallengeMethod", ({ enumerable: true, get: function () { return oauth2client_1.CodeChallengeMethod; } })); Object.defineProperty(exports, "OAuth2Client", ({ enumerable: true, get: function () { return oauth2client_1.OAuth2Client; } })); Object.defineProperty(exports, "ClientAuthentication", ({ enumerable: true, get: function () { return oauth2client_1.ClientAuthentication; } })); var loginticket_1 = __nccwpck_require__(3882); Object.defineProperty(exports, "LoginTicket", ({ enumerable: true, get: function () { return loginticket_1.LoginTicket; } })); var refreshclient_1 = __nccwpck_require__(9807); Object.defineProperty(exports, "UserRefreshClient", ({ enumerable: true, get: function () { return refreshclient_1.UserRefreshClient; } })); var awsclient_1 = __nccwpck_require__(1261); Object.defineProperty(exports, "AwsClient", ({ enumerable: true, get: function () { return awsclient_1.AwsClient; } })); var awsrequestsigner_1 = __nccwpck_require__(7647); Object.defineProperty(exports, "AwsRequestSigner", ({ enumerable: true, get: function () { return awsrequestsigner_1.AwsRequestSigner; } })); var identitypoolclient_1 = __nccwpck_require__(9960); Object.defineProperty(exports, "IdentityPoolClient", ({ enumerable: true, get: function () { return identitypoolclient_1.IdentityPoolClient; } })); var externalclient_1 = __nccwpck_require__(8323); Object.defineProperty(exports, "ExternalAccountClient", ({ enumerable: true, get: function () { return externalclient_1.ExternalAccountClient; } })); var baseexternalclient_1 = __nccwpck_require__(142); Object.defineProperty(exports, "BaseExternalAccountClient", ({ enumerable: true, get: function () { return baseexternalclient_1.BaseExternalAccountClient; } })); var downscopedclient_1 = __nccwpck_require__(7556); Object.defineProperty(exports, "DownscopedClient", ({ enumerable: true, get: function () { return downscopedclient_1.DownscopedClient; } })); var pluggable_auth_client_1 = __nccwpck_require__(6077); Object.defineProperty(exports, "PluggableAuthClient", ({ enumerable: true, get: function () { return pluggable_auth_client_1.PluggableAuthClient; } })); Object.defineProperty(exports, "ExecutableError", ({ enumerable: true, get: function () { return pluggable_auth_client_1.ExecutableError; } })); var passthrough_1 = __nccwpck_require__(2045); Object.defineProperty(exports, "PassThroughClient", ({ enumerable: true, get: function () { return passthrough_1.PassThroughClient; } })); var transporters_1 = __nccwpck_require__(7633); Object.defineProperty(exports, "DefaultTransporter", ({ enumerable: true, get: function () { return transporters_1.DefaultTransporter; } })); const auth = new googleauth_1.GoogleAuth(); exports.auth = auth; /***/ }), /***/ 8290: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright 2017 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.validate = validate; // Accepts an options object passed from the user to the API. In the // previous version of the API, it referred to a `Request` options object. // Now it refers to an Axiox Request Config object. This is here to help // ensure users don't pass invalid options when they upgrade from 0.x to 1.x. // eslint-disable-next-line @typescript-eslint/no-explicit-any function validate(options) { const vpairs = [ { invalid: 'uri', expected: 'url' }, { invalid: 'json', expected: 'data' }, { invalid: 'qs', expected: 'params' }, ]; for (const pair of vpairs) { if (options[pair.invalid]) { const e = `'${pair.invalid}' is not a valid configuration option. Please use '${pair.expected}' instead. This library is using Axios for requests. Please see https://github.com/axios/axios to learn more about the valid request options.`; throw new Error(e); } } } /***/ }), /***/ 7633: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DefaultTransporter = void 0; const gaxios_1 = __nccwpck_require__(7003); const options_1 = __nccwpck_require__(8290); // eslint-disable-next-line @typescript-eslint/no-var-requires const pkg = __nccwpck_require__(6066); const PRODUCT_NAME = 'google-api-nodejs-client'; class DefaultTransporter { constructor() { /** * A configurable, replacable `Gaxios` instance. */ this.instance = new gaxios_1.Gaxios(); } /** * Configures request options before making a request. * @param opts GaxiosOptions options. * @return Configured options. */ configure(opts = {}) { opts.headers = opts.headers || {}; if (typeof window === 'undefined') { // set transporter user agent if not in browser const uaValue = opts.headers['User-Agent']; if (!uaValue) { opts.headers['User-Agent'] = DefaultTransporter.USER_AGENT; } else if (!uaValue.includes(`${PRODUCT_NAME}/`)) { opts.headers['User-Agent'] = `${uaValue} ${DefaultTransporter.USER_AGENT}`; } // track google-auth-library-nodejs version: if (!opts.headers['x-goog-api-client']) { const nodeVersion = process.version.replace(/^v/, ''); opts.headers['x-goog-api-client'] = `gl-node/${nodeVersion}`; } } return opts; } /** * Makes a request using Gaxios with given options. * @param opts GaxiosOptions options. * @param callback optional callback that contains GaxiosResponse object. * @return GaxiosPromise, assuming no callback is passed. */ request(opts) { // ensure the user isn't passing in request-style options opts = this.configure(opts); (0, options_1.validate)(opts); return this.instance.request(opts).catch(e => { throw this.processError(e); }); } get defaults() { return this.instance.defaults; } set defaults(opts) { this.instance.defaults = opts; } /** * Changes the error to include details from the body. */ processError(e) { const res = e.response; const err = e; const body = res ? res.data : null; if (res && body && body.error && res.status !== 200) { if (typeof body.error === 'string') { err.message = body.error; err.status = res.status; } else if (Array.isArray(body.error.errors)) { err.message = body.error.errors .map((err2) => err2.message) .join('\n'); err.code = body.error.code; err.errors = body.error.errors; } else { err.message = body.error.message; err.code = body.error.code; } } else if (res && res.status >= 400) { // Consider all 4xx and 5xx responses errors. err.message = body; err.status = res.status; } return err; } } exports.DefaultTransporter = DefaultTransporter; /** * Default user agent. */ DefaultTransporter.USER_AGENT = `${PRODUCT_NAME}/${pkg.version}`; /***/ }), /***/ 7870: /***/ (function(__unused_webpack_module, exports) { "use strict"; // Copyright 2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. var __classPrivateFieldGet = (this && this.__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); }; var _LRUCache_instances, _LRUCache_cache, _LRUCache_moveToEnd, _LRUCache_evict; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LRUCache = void 0; exports.snakeToCamel = snakeToCamel; exports.originalOrCamelOptions = originalOrCamelOptions; /** * Returns the camel case of a provided string. * * @remarks * * Match any `_` and not `_` pair, then return the uppercase of the not `_` * character. * * @internal * * @param str the string to convert * @returns the camelCase'd string */ function snakeToCamel(str) { return str.replace(/([_][^_])/g, match => match.slice(1).toUpperCase()); } /** * Get the value of `obj[key]` or `obj[camelCaseKey]`, with a preference * for original, non-camelCase key. * * @param obj object to lookup a value in * @returns a `get` function for getting `obj[key || snakeKey]`, if available */ function originalOrCamelOptions(obj) { /** * * @param key an index of object, preferably snake_case * @returns the value `obj[key || snakeKey]`, if available */ function get(key) { var _a; const o = (obj || {}); return (_a = o[key]) !== null && _a !== void 0 ? _a : o[snakeToCamel(key)]; } return { get }; } /** * A simple LRU cache utility. * Not meant for external usage. * * @experimental * @internal */ class LRUCache { constructor(options) { _LRUCache_instances.add(this); /** * Maps are in order. Thus, the older item is the first item. * * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map} */ _LRUCache_cache.set(this, new Map()); this.capacity = options.capacity; this.maxAge = options.maxAge; } /** * Add an item to the cache. * * @param key the key to upsert * @param value the value of the key */ set(key, value) { __classPrivateFieldGet(this, _LRUCache_instances, "m", _LRUCache_moveToEnd).call(this, key, value); __classPrivateFieldGet(this, _LRUCache_instances, "m", _LRUCache_evict).call(this); } /** * Get an item from the cache. * * @param key the key to retrieve */ get(key) { const item = __classPrivateFieldGet(this, _LRUCache_cache, "f").get(key); if (!item) return; __classPrivateFieldGet(this, _LRUCache_instances, "m", _LRUCache_moveToEnd).call(this, key, item.value); __classPrivateFieldGet(this, _LRUCache_instances, "m", _LRUCache_evict).call(this); return item.value; } } exports.LRUCache = LRUCache; _LRUCache_cache = new WeakMap(), _LRUCache_instances = new WeakSet(), _LRUCache_moveToEnd = function _LRUCache_moveToEnd(key, value) { __classPrivateFieldGet(this, _LRUCache_cache, "f").delete(key); __classPrivateFieldGet(this, _LRUCache_cache, "f").set(key, { value, lastAccessed: Date.now(), }); }, _LRUCache_evict = function _LRUCache_evict() { const cutoffDate = this.maxAge ? Date.now() - this.maxAge : 0; /** * Because we know Maps are in order, this item is both the * last item in the list (capacity) and oldest (maxAge). */ let oldestItem = __classPrivateFieldGet(this, _LRUCache_cache, "f").entries().next(); while (!oldestItem.done && (__classPrivateFieldGet(this, _LRUCache_cache, "f").size > this.capacity || // too many oldestItem.value[1].lastAccessed < cutoffDate) // too old ) { __classPrivateFieldGet(this, _LRUCache_cache, "f").delete(oldestItem.value[0]); oldestItem = __classPrivateFieldGet(this, _LRUCache_cache, "f").entries().next(); } }; /***/ }), /***/ 1628: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright 2024 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Colours = void 0; /** * Handles figuring out if we can use ANSI colours and handing out the escape codes. * * This is for package-internal use only, and may change at any time. * * @private * @internal */ class Colours { /** * @param stream The stream (e.g. process.stderr) * @returns true if the stream should have colourization enabled */ static isEnabled(stream) { return (stream.isTTY && (typeof stream.getColorDepth === 'function' ? stream.getColorDepth() > 2 : true)); } static refresh() { Colours.enabled = Colours.isEnabled(process.stderr); if (!this.enabled) { Colours.reset = ''; Colours.bright = ''; Colours.dim = ''; Colours.red = ''; Colours.green = ''; Colours.yellow = ''; Colours.blue = ''; Colours.magenta = ''; Colours.cyan = ''; Colours.white = ''; Colours.grey = ''; } else { Colours.reset = '\u001b[0m'; Colours.bright = '\u001b[1m'; Colours.dim = '\u001b[2m'; Colours.red = '\u001b[31m'; Colours.green = '\u001b[32m'; Colours.yellow = '\u001b[33m'; Colours.blue = '\u001b[34m'; Colours.magenta = '\u001b[35m'; Colours.cyan = '\u001b[36m'; Colours.white = '\u001b[37m'; Colours.grey = '\u001b[90m'; } } } exports.Colours = Colours; Colours.enabled = false; Colours.reset = ''; Colours.bright = ''; Colours.dim = ''; Colours.red = ''; Colours.green = ''; Colours.yellow = ''; Colours.blue = ''; Colours.magenta = ''; Colours.cyan = ''; Colours.white = ''; Colours.grey = ''; Colours.refresh(); //# sourceMappingURL=colours.js.map /***/ }), /***/ 1577: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright 2024 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); __exportStar(__nccwpck_require__(4788), exports); //# sourceMappingURL=index.js.map /***/ }), /***/ 4788: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright 2021-2024 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 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.env = exports.DebugLogBackendBase = exports.placeholder = exports.AdhocDebugLogger = exports.LogSeverity = void 0; exports.getNodeBackend = getNodeBackend; exports.getDebugBackend = getDebugBackend; exports.getStructuredBackend = getStructuredBackend; exports.setBackend = setBackend; exports.log = log; const node_events_1 = __nccwpck_require__(8474); const process = __importStar(__nccwpck_require__(1708)); const util = __importStar(__nccwpck_require__(7975)); const colours_1 = __nccwpck_require__(1628); // Some functions (as noted) are based on the Node standard library, from // the following file: // // https://github.com/nodejs/node/blob/main/lib/internal/util/debuglog.js /** * This module defines an ad-hoc debug logger for Google Cloud Platform * client libraries in Node. An ad-hoc debug logger is a tool which lets * users use an external, unified interface (in this case, environment * variables) to determine what logging they want to see at runtime. This * isn't necessarily fed into the console, but is meant to be under the * control of the user. The kind of logging that will be produced by this * is more like "call retry happened", not "event you'd want to record * in Cloud Logger". * * More for Googlers implementing libraries with it: * go/cloud-client-logging-design */ /** * Possible log levels. These are a subset of Cloud Observability levels. * https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogSeverity */ var LogSeverity; (function (LogSeverity) { LogSeverity["DEFAULT"] = "DEFAULT"; LogSeverity["DEBUG"] = "DEBUG"; LogSeverity["INFO"] = "INFO"; LogSeverity["WARNING"] = "WARNING"; LogSeverity["ERROR"] = "ERROR"; })(LogSeverity || (exports.LogSeverity = LogSeverity = {})); /** * Our logger instance. This actually contains the meat of dealing * with log lines, including EventEmitter. This contains the function * that will be passed back to users of the package. */ class AdhocDebugLogger extends node_events_1.EventEmitter { /** * @param upstream The backend will pass a function that will be * called whenever our logger function is invoked. */ constructor(namespace, upstream) { super(); this.namespace = namespace; this.upstream = upstream; this.func = Object.assign(this.invoke.bind(this), { // Also add an instance pointer back to us. instance: this, // And pull over the EventEmitter functionality. on: (event, listener) => this.on(event, listener), }); // Convenience methods for log levels. this.func.debug = (...args) => this.invokeSeverity(LogSeverity.DEBUG, ...args); this.func.info = (...args) => this.invokeSeverity(LogSeverity.INFO, ...args); this.func.warn = (...args) => this.invokeSeverity(LogSeverity.WARNING, ...args); this.func.error = (...args) => this.invokeSeverity(LogSeverity.ERROR, ...args); this.func.sublog = (namespace) => log(namespace, this.func); } invoke(fields, ...args) { // Push out any upstream logger first. if (this.upstream) { this.upstream(fields, ...args); } // Emit sink events. this.emit('log', fields, args); } invokeSeverity(severity, ...args) { this.invoke({ severity }, ...args); } } exports.AdhocDebugLogger = AdhocDebugLogger; /** * This can be used in place of a real logger while waiting for Promises or disabling logging. */ exports.placeholder = new AdhocDebugLogger('', () => { }).func; /** * The base class for debug logging backends. It's possible to use this, but the * same non-guarantees above still apply (unstable interface, etc). * * @private * @internal */ class DebugLogBackendBase { constructor() { var _a; this.cached = new Map(); this.filters = []; this.filtersSet = false; // Look for the Node config variable for what systems to enable. We'll store // these for the log method below, which will call setFilters() once. let nodeFlag = (_a = process.env[exports.env.nodeEnables]) !== null && _a !== void 0 ? _a : '*'; if (nodeFlag === 'all') { nodeFlag = '*'; } this.filters = nodeFlag.split(','); } log(namespace, fields, ...args) { try { if (!this.filtersSet) { this.setFilters(); this.filtersSet = true; } let logger = this.cached.get(namespace); if (!logger) { logger = this.makeLogger(namespace); this.cached.set(namespace, logger); } logger(fields, ...args); } catch (e) { // Silently ignore all errors; we don't want them to interfere with // the user's running app. // e; console.error(e); } } } exports.DebugLogBackendBase = DebugLogBackendBase; // The basic backend. This one definitely works, but it's less feature-filled. // // Rather than using util.debuglog, this implements the same basic logic directly. // The reason for this decision is that debuglog checks the value of the // NODE_DEBUG environment variable before any user code runs; we therefore // can't pipe our own enables into it (and util.debuglog will never print unless // the user duplicates it into NODE_DEBUG, which isn't reasonable). // class NodeBackend extends DebugLogBackendBase { constructor() { super(...arguments); // Default to allowing all systems, since we gate earlier based on whether the // variable is empty. this.enabledRegexp = /.*/g; } isEnabled(namespace) { return this.enabledRegexp.test(namespace); } makeLogger(namespace) { if (!this.enabledRegexp.test(namespace)) { return () => { }; } return (fields, ...args) => { var _a; // TODO: `fields` needs to be turned into a string here, one way or another. const nscolour = `${colours_1.Colours.green}${namespace}${colours_1.Colours.reset}`; const pid = `${colours_1.Colours.yellow}${process.pid}${colours_1.Colours.reset}`; let level; switch (fields.severity) { case LogSeverity.ERROR: level = `${colours_1.Colours.red}${fields.severity}${colours_1.Colours.reset}`; break; case LogSeverity.INFO: level = `${colours_1.Colours.magenta}${fields.severity}${colours_1.Colours.reset}`; break; case LogSeverity.WARNING: level = `${colours_1.Colours.yellow}${fields.severity}${colours_1.Colours.reset}`; break; default: level = (_a = fields.severity) !== null && _a !== void 0 ? _a : LogSeverity.DEFAULT; break; } const msg = util.formatWithOptions({ colors: colours_1.Colours.enabled }, ...args); const filteredFields = Object.assign({}, fields); delete filteredFields.severity; const fieldsJson = Object.getOwnPropertyNames(filteredFields).length ? JSON.stringify(filteredFields) : ''; const fieldsColour = fieldsJson ? `${colours_1.Colours.grey}${fieldsJson}${colours_1.Colours.reset}` : ''; console.error('%s [%s|%s] %s%s', pid, nscolour, level, msg, fieldsJson ? ` ${fieldsColour}` : ''); }; } // Regexp patterns below are from here: // https://github.com/nodejs/node/blob/c0aebed4b3395bd65d54b18d1fd00f071002ac20/lib/internal/util/debuglog.js#L36 setFilters() { const totalFilters = this.filters.join(','); const regexp = totalFilters .replace(/[|\\{}()[\]^$+?.]/g, '\\$&') .replace(/\*/g, '.*') .replace(/,/g, '$|^'); this.enabledRegexp = new RegExp(`^${regexp}$`, 'i'); } } /** * @returns A backend based on Node util.debuglog; this is the default. */ function getNodeBackend() { return new NodeBackend(); } class DebugBackend extends DebugLogBackendBase { constructor(pkg) { super(); this.debugPkg = pkg; } makeLogger(namespace) { const debugLogger = this.debugPkg(namespace); return (fields, ...args) => { // TODO: `fields` needs to be turned into a string here. debugLogger(args[0], ...args.slice(1)); }; } setFilters() { var _a; const existingFilters = (_a = process.env['NODE_DEBUG']) !== null && _a !== void 0 ? _a : ''; process.env['NODE_DEBUG'] = `${existingFilters}${existingFilters ? ',' : ''}${this.filters.join(',')}`; } } /** * Creates a "debug" package backend. The user must call require('debug') and pass * the resulting object to this function. * * ``` * setBackend(getDebugBackend(require('debug'))) * ``` * * https://www.npmjs.com/package/debug * * Note: Google does not explicitly endorse or recommend this package; it's just * being provided as an option. * * @returns A backend based on the npm "debug" package. */ function getDebugBackend(debugPkg) { return new DebugBackend(debugPkg); } /** * This pretty much works like the Node logger, but it outputs structured * logging JSON matching Google Cloud's ingestion specs. Rather than handling * its own output, it wraps another backend. The passed backend must be a subclass * of `DebugLogBackendBase` (any of the backends exposed by this package will work). */ class StructuredBackend extends DebugLogBackendBase { constructor(upstream) { var _a; super(); this.upstream = (_a = upstream) !== null && _a !== void 0 ? _a : new NodeBackend(); } makeLogger(namespace) { const debugLogger = this.upstream.makeLogger(namespace); return (fields, ...args) => { var _a; const severity = (_a = fields.severity) !== null && _a !== void 0 ? _a : LogSeverity.INFO; const json = Object.assign({ severity, message: util.format(...args), }, fields); const jsonString = JSON.stringify(json); debugLogger(fields, jsonString); }; } setFilters() { this.upstream.setFilters(); } } /** * Creates a "structured logging" backend. This pretty much works like the * Node logger, but it outputs structured logging JSON matching Google * Cloud's ingestion specs instead of plain text. * * ``` * setBackend(getStructuredBackend()) * ``` * * @param upstream If you want to use something besides the Node backend to * write the actual log lines into, pass that here. * @returns A backend based on Google Cloud structured logging. */ function getStructuredBackend(upstream) { return new StructuredBackend(upstream); } /** * The environment variables that we standardized on, for all ad-hoc logging. */ exports.env = { /** * Filter wildcards specific to the Node syntax, and similar to the built-in * utils.debuglog() environment variable. If missing, disables logging. */ nodeEnables: 'GOOGLE_SDK_NODE_LOGGING', }; // Keep a copy of all namespaced loggers so users can reliably .on() them. // Note that these cached functions will need to deal with changes in the backend. const loggerCache = new Map(); // Our current global backend. This might be: let cachedBackend = undefined; /** * Set the backend to use for our log output. * - A backend object * - null to disable logging * - undefined for "nothing yet", defaults to the Node backend * * @param backend Results from one of the get*Backend() functions. */ function setBackend(backend) { cachedBackend = backend; loggerCache.clear(); } /** * Creates a logging function. Multiple calls to this with the same namespace * will produce the same logger, with the same event emitter hooks. * * Namespaces can be a simple string ("system" name), or a qualified string * (system:subsystem), which can be used for filtering, or for "system:*". * * @param namespace The namespace, a descriptive text string. * @returns A function you can call that works similar to console.log(). */ function log(namespace, parent) { // If the enable flag isn't set, do nothing. const enablesFlag = process.env[exports.env.nodeEnables]; if (!enablesFlag) { return exports.placeholder; } // This might happen mostly if the typings are dropped in a user's code, // or if they're calling from JavaScript. if (!namespace) { return exports.placeholder; } // Handle sub-loggers. if (parent) { namespace = `${parent.instance.namespace}:${namespace}`; } // Reuse loggers so things like event sinks are persistent. const existing = loggerCache.get(namespace); if (existing) { return existing.func; } // Do we have a backend yet? if (cachedBackend === null) { // Explicitly disabled. return exports.placeholder; } else if (cachedBackend === undefined) { // One hasn't been made yet, so default to Node. cachedBackend = getNodeBackend(); } // The logger is further wrapped so we can handle the backend changing out. const logger = (() => { let previousBackend = undefined; const newLogger = new AdhocDebugLogger(namespace, (fields, ...args) => { if (previousBackend !== cachedBackend) { // Did the user pass a custom backend? if (cachedBackend === null) { // Explicitly disabled. return; } else if (cachedBackend === undefined) { // One hasn't been made yet, so default to Node. cachedBackend = getNodeBackend(); } previousBackend = cachedBackend; } cachedBackend === null || cachedBackend === void 0 ? void 0 : cachedBackend.log(namespace, fields, ...args); }); return newLogger; })(); loggerCache.set(namespace, logger); return logger.func; } //# sourceMappingURL=logging-utils.js.map /***/ }), /***/ 8568: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; /** * Copyright 2018 Google LLC * * Distributed under MIT license. * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT */ var __classPrivateFieldGet = (this && this.__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); }; var __classPrivateFieldSet = (this && this.__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; }; var _GoogleToken_instances, _GoogleToken_inFlightRequest, _GoogleToken_getTokenAsync, _GoogleToken_getTokenAsyncInner, _GoogleToken_ensureEmail, _GoogleToken_revokeTokenAsync, _GoogleToken_configure, _GoogleToken_requestToken; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GoogleToken = void 0; const fs = __nccwpck_require__(9896); const gaxios_1 = __nccwpck_require__(7003); const jws = __nccwpck_require__(3324); const path = __nccwpck_require__(6928); const util_1 = __nccwpck_require__(9023); const readFile = fs.readFile ? (0, util_1.promisify)(fs.readFile) : async () => { // if running in the web-browser, fs.readFile may not have been shimmed. throw new ErrorWithCode('use key rather than keyFile.', 'MISSING_CREDENTIALS'); }; const GOOGLE_TOKEN_URL = 'https://www.googleapis.com/oauth2/v4/token'; const GOOGLE_REVOKE_TOKEN_URL = 'https://accounts.google.com/o/oauth2/revoke?token='; class ErrorWithCode extends Error { constructor(message, code) { super(message); this.code = code; } } class GoogleToken { get accessToken() { return this.rawToken ? this.rawToken.access_token : undefined; } get idToken() { return this.rawToken ? this.rawToken.id_token : undefined; } get tokenType() { return this.rawToken ? this.rawToken.token_type : undefined; } get refreshToken() { return this.rawToken ? this.rawToken.refresh_token : undefined; } /** * Create a GoogleToken. * * @param options Configuration object. */ constructor(options) { _GoogleToken_instances.add(this); this.transporter = { request: opts => (0, gaxios_1.request)(opts), }; _GoogleToken_inFlightRequest.set(this, void 0); __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_configure).call(this, options); } /** * Returns whether the token has expired. * * @return true if the token has expired, false otherwise. */ hasExpired() { const now = new Date().getTime(); if (this.rawToken && this.expiresAt) { return now >= this.expiresAt; } else { return true; } } /** * Returns whether the token will expire within eagerRefreshThresholdMillis * * @return true if the token will be expired within eagerRefreshThresholdMillis, false otherwise. */ isTokenExpiring() { var _a; const now = new Date().getTime(); const eagerRefreshThresholdMillis = (_a = this.eagerRefreshThresholdMillis) !== null && _a !== void 0 ? _a : 0; if (this.rawToken && this.expiresAt) { return this.expiresAt <= now + eagerRefreshThresholdMillis; } else { return true; } } getToken(callback, opts = {}) { if (typeof callback === 'object') { opts = callback; callback = undefined; } opts = Object.assign({ forceRefresh: false, }, opts); if (callback) { const cb = callback; __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_getTokenAsync).call(this, opts).then(t => cb(null, t), callback); return; } return __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_getTokenAsync).call(this, opts); } /** * Given a keyFile, extract the key and client email if available * @param keyFile Path to a json, pem, or p12 file that contains the key. * @returns an object with privateKey and clientEmail properties */ async getCredentials(keyFile) { const ext = path.extname(keyFile); switch (ext) { case '.json': { const key = await readFile(keyFile, 'utf8'); const body = JSON.parse(key); const privateKey = body.private_key; const clientEmail = body.client_email; if (!privateKey || !clientEmail) { throw new ErrorWithCode('private_key and client_email are required.', 'MISSING_CREDENTIALS'); } return { privateKey, clientEmail }; } case '.der': case '.crt': case '.pem': { const privateKey = await readFile(keyFile, 'utf8'); return { privateKey }; } case '.p12': case '.pfx': { throw new ErrorWithCode('*.p12 certificates are not supported after v6.1.2. ' + 'Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.', 'UNKNOWN_CERTIFICATE_TYPE'); } default: throw new ErrorWithCode('Unknown certificate type. Type is determined based on file extension. ' + 'Current supported extensions are *.json, and *.pem.', 'UNKNOWN_CERTIFICATE_TYPE'); } } revokeToken(callback) { if (callback) { __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_revokeTokenAsync).call(this).then(() => callback(), callback); return; } return __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_revokeTokenAsync).call(this); } } exports.GoogleToken = GoogleToken; _GoogleToken_inFlightRequest = new WeakMap(), _GoogleToken_instances = new WeakSet(), _GoogleToken_getTokenAsync = async function _GoogleToken_getTokenAsync(opts) { if (__classPrivateFieldGet(this, _GoogleToken_inFlightRequest, "f") && !opts.forceRefresh) { return __classPrivateFieldGet(this, _GoogleToken_inFlightRequest, "f"); } try { return await (__classPrivateFieldSet(this, _GoogleToken_inFlightRequest, __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_getTokenAsyncInner).call(this, opts), "f")); } finally { __classPrivateFieldSet(this, _GoogleToken_inFlightRequest, undefined, "f"); } }, _GoogleToken_getTokenAsyncInner = async function _GoogleToken_getTokenAsyncInner(opts) { if (this.isTokenExpiring() === false && opts.forceRefresh === false) { return Promise.resolve(this.rawToken); } if (!this.key && !this.keyFile) { throw new Error('No key or keyFile set.'); } if (!this.key && this.keyFile) { const creds = await this.getCredentials(this.keyFile); this.key = creds.privateKey; this.iss = creds.clientEmail || this.iss; if (!creds.clientEmail) { __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_ensureEmail).call(this); } } return __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_requestToken).call(this); }, _GoogleToken_ensureEmail = function _GoogleToken_ensureEmail() { if (!this.iss) { throw new ErrorWithCode('email is required.', 'MISSING_CREDENTIALS'); } }, _GoogleToken_revokeTokenAsync = async function _GoogleToken_revokeTokenAsync() { if (!this.accessToken) { throw new Error('No token to revoke.'); } const url = GOOGLE_REVOKE_TOKEN_URL + this.accessToken; await this.transporter.request({ url, retry: true, }); __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_configure).call(this, { email: this.iss, sub: this.sub, key: this.key, keyFile: this.keyFile, scope: this.scope, additionalClaims: this.additionalClaims, }); }, _GoogleToken_configure = function _GoogleToken_configure(options = {}) { this.keyFile = options.keyFile; this.key = options.key; this.rawToken = undefined; this.iss = options.email || options.iss; this.sub = options.sub; this.additionalClaims = options.additionalClaims; if (typeof options.scope === 'object') { this.scope = options.scope.join(' '); } else { this.scope = options.scope; } this.eagerRefreshThresholdMillis = options.eagerRefreshThresholdMillis; if (options.transporter) { this.transporter = options.transporter; } }, _GoogleToken_requestToken = /** * Request the token from Google. */ async function _GoogleToken_requestToken() { var _a, _b; const iat = Math.floor(new Date().getTime() / 1000); const additionalClaims = this.additionalClaims || {}; const payload = Object.assign({ iss: this.iss, scope: this.scope, aud: GOOGLE_TOKEN_URL, exp: iat + 3600, iat, sub: this.sub, }, additionalClaims); const signedJWT = jws.sign({ header: { alg: 'RS256' }, payload, secret: this.key, }); try { const r = await this.transporter.request({ method: 'POST', url: GOOGLE_TOKEN_URL, data: { grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', assertion: signedJWT, }, headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, responseType: 'json', retryConfig: { httpMethodsToRetry: ['POST'], }, }); this.rawToken = r.data; this.expiresAt = r.data.expires_in === null || r.data.expires_in === undefined ? undefined : (iat + r.data.expires_in) * 1000; return this.rawToken; } catch (e) { this.rawToken = undefined; this.tokenExpires = undefined; const body = e.response && ((_a = e.response) === null || _a === void 0 ? void 0 : _a.data) ? (_b = e.response) === null || _b === void 0 ? void 0 : _b.data : {}; if (body.error) { const desc = body.error_description ? `: ${body.error_description}` : ''; e.message = `${body.error}${desc}`; } throw e; } }; //# sourceMappingURL=index.js.map /***/ }), /***/ 3813: /***/ ((module) => { "use strict"; module.exports = (flag, argv = process.argv) => { const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); const position = argv.indexOf(prefix + flag); const terminatorPosition = argv.indexOf('--'); return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); }; /***/ }), /***/ 7847: /***/ (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 __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); const net_1 = __importDefault(__nccwpck_require__(9278)); const tls_1 = __importDefault(__nccwpck_require__(4756)); const url_1 = __importDefault(__nccwpck_require__(7016)); const debug_1 = __importDefault(__nccwpck_require__(2830)); const once_1 = __importDefault(__nccwpck_require__(8662)); const agent_base_1 = __nccwpck_require__(2960); const debug = (0, debug_1.default)('http-proxy-agent'); function isHTTPS(protocol) { return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false; } /** * The `HttpProxyAgent` implements an HTTP Agent subclass that connects * to the specified "HTTP proxy server" in order to proxy HTTP requests. * * @api public */ class HttpProxyAgent extends agent_base_1.Agent { constructor(_opts) { let opts; if (typeof _opts === 'string') { opts = url_1.default.parse(_opts); } else { opts = _opts; } if (!opts) { throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!'); } debug('Creating new HttpProxyAgent instance: %o', opts); super(opts); const proxy = Object.assign({}, opts); // If `true`, then connect to the proxy server over TLS. // Defaults to `false`. this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol); // Prefer `hostname` over `host`, and set the `port` if needed. proxy.host = proxy.hostname || proxy.host; if (typeof proxy.port === 'string') { proxy.port = parseInt(proxy.port, 10); } if (!proxy.port && proxy.host) { proxy.port = this.secureProxy ? 443 : 80; } if (proxy.host && proxy.path) { // If both a `host` and `path` are specified then it's most likely // the result of a `url.parse()` call... we need to remove the // `path` portion so that `net.connect()` doesn't attempt to open // that as a Unix socket file. delete proxy.path; delete proxy.pathname; } this.proxy = proxy; } /** * Called when the node-core HTTP client library is creating a * new HTTP request. * * @api protected */ callback(req, opts) { return __awaiter(this, void 0, void 0, function* () { const { proxy, secureProxy } = this; const parsed = url_1.default.parse(req.path); if (!parsed.protocol) { parsed.protocol = 'http:'; } if (!parsed.hostname) { parsed.hostname = opts.hostname || opts.host || null; } if (parsed.port == null && typeof opts.port) { parsed.port = String(opts.port); } if (parsed.port === '80') { // if port is 80, then we can remove the port so that the // ":80" portion is not on the produced URL parsed.port = ''; } // Change the `http.ClientRequest` instance's "path" field // to the absolute path of the URL that will be requested. req.path = url_1.default.format(parsed); // Inject the `Proxy-Authorization` header if necessary. if (proxy.auth) { req.setHeader('Proxy-Authorization', `Basic ${Buffer.from(proxy.auth).toString('base64')}`); } // Create a socket connection to the proxy server. let socket; if (secureProxy) { debug('Creating `tls.Socket`: %o', proxy); socket = tls_1.default.connect(proxy); } else { debug('Creating `net.Socket`: %o', proxy); socket = net_1.default.connect(proxy); } // At this point, the http ClientRequest's internal `_header` field // might have already been set. If this is the case then we'll need // to re-generate the string since we just changed the `req.path`. if (req._header) { let first; let endOfHeaders; debug('Regenerating stored HTTP header string for request'); req._header = null; req._implicitHeader(); if (req.output && req.output.length > 0) { // Node < 12 debug('Patching connection write() output buffer with updated header'); first = req.output[0]; endOfHeaders = first.indexOf('\r\n\r\n') + 4; req.output[0] = req._header + first.substring(endOfHeaders); debug('Output buffer: %o', req.output); } else if (req.outputData && req.outputData.length > 0) { // Node >= 12 debug('Patching connection write() output buffer with updated header'); first = req.outputData[0].data; endOfHeaders = first.indexOf('\r\n\r\n') + 4; req.outputData[0].data = req._header + first.substring(endOfHeaders); debug('Output buffer: %o', req.outputData[0].data); } } // Wait for the socket's `connect` event, so that this `callback()` // function throws instead of the `http` request machinery. This is // important for i.e. `PacProxyAgent` which determines a failed proxy // connection via the `callback()` function throwing. yield (0, once_1.default)(socket, 'connect'); return socket; }); } } exports["default"] = HttpProxyAgent; //# sourceMappingURL=agent.js.map /***/ }), /***/ 1970: /***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; const agent_1 = __importDefault(__nccwpck_require__(7847)); function createHttpProxyAgent(opts) { return new agent_1.default(opts); } (function (createHttpProxyAgent) { createHttpProxyAgent.HttpProxyAgent = agent_1.default; createHttpProxyAgent.prototype = agent_1.default.prototype; })(createHttpProxyAgent || (createHttpProxyAgent = {})); module.exports = createHttpProxyAgent; //# sourceMappingURL=index.js.map /***/ }), /***/ 2960: /***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; const events_1 = __nccwpck_require__(4434); const debug_1 = __importDefault(__nccwpck_require__(2830)); const promisify_1 = __importDefault(__nccwpck_require__(2600)); const debug = debug_1.default('agent-base'); function isAgent(v) { return Boolean(v) && typeof v.addRequest === 'function'; } function isSecureEndpoint() { const { stack } = new Error(); if (typeof stack !== 'string') return false; return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1); } function createAgent(callback, opts) { return new createAgent.Agent(callback, opts); } (function (createAgent) { /** * Base `http.Agent` implementation. * No pooling/keep-alive is implemented by default. * * @param {Function} callback * @api public */ class Agent extends events_1.EventEmitter { constructor(callback, _opts) { super(); let opts = _opts; if (typeof callback === 'function') { this.callback = callback; } else if (callback) { opts = callback; } // Timeout for the socket to be returned from the callback this.timeout = null; if (opts && typeof opts.timeout === 'number') { this.timeout = opts.timeout; } // These aren't actually used by `agent-base`, but are required // for the TypeScript definition files in `@types/node` :/ this.maxFreeSockets = 1; this.maxSockets = 1; this.maxTotalSockets = Infinity; this.sockets = {}; this.freeSockets = {}; this.requests = {}; this.options = {}; } get defaultPort() { if (typeof this.explicitDefaultPort === 'number') { return this.explicitDefaultPort; } return isSecureEndpoint() ? 443 : 80; } set defaultPort(v) { this.explicitDefaultPort = v; } get protocol() { if (typeof this.explicitProtocol === 'string') { return this.explicitProtocol; } return isSecureEndpoint() ? 'https:' : 'http:'; } set protocol(v) { this.explicitProtocol = v; } callback(req, opts, fn) { throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`'); } /** * Called by node-core's "_http_client.js" module when creating * a new HTTP request with this Agent instance. * * @api public */ addRequest(req, _opts) { const opts = Object.assign({}, _opts); if (typeof opts.secureEndpoint !== 'boolean') { opts.secureEndpoint = isSecureEndpoint(); } if (opts.host == null) { opts.host = 'localhost'; } if (opts.port == null) { opts.port = opts.secureEndpoint ? 443 : 80; } if (opts.protocol == null) { opts.protocol = opts.secureEndpoint ? 'https:' : 'http:'; } if (opts.host && opts.path) { // If both a `host` and `path` are specified then it's most // likely the result of a `url.parse()` call... we need to // remove the `path` portion so that `net.connect()` doesn't // attempt to open that as a unix socket file. delete opts.path; } delete opts.agent; delete opts.hostname; delete opts._defaultAgent; delete opts.defaultPort; delete opts.createConnection; // Hint to use "Connection: close" // XXX: non-documented `http` module API :( req._last = true; req.shouldKeepAlive = false; let timedOut = false; let timeoutId = null; const timeoutMs = opts.timeout || this.timeout; const onerror = (err) => { if (req._hadError) return; req.emit('error', err); // For Safety. Some additional errors might fire later on // and we need to make sure we don't double-fire the error event. req._hadError = true; }; const ontimeout = () => { timeoutId = null; timedOut = true; const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`); err.code = 'ETIMEOUT'; onerror(err); }; const callbackError = (err) => { if (timedOut) return; if (timeoutId !== null) { clearTimeout(timeoutId); timeoutId = null; } onerror(err); }; const onsocket = (socket) => { if (timedOut) return; if (timeoutId != null) { clearTimeout(timeoutId); timeoutId = null; } if (isAgent(socket)) { // `socket` is actually an `http.Agent` instance, so // relinquish responsibility for this `req` to the Agent // from here on debug('Callback returned another Agent instance %o', socket.constructor.name); socket.addRequest(req, opts); return; } if (socket) { socket.once('free', () => { this.freeSocket(socket, opts); }); req.onSocket(socket); return; } const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``); onerror(err); }; if (typeof this.callback !== 'function') { onerror(new Error('`callback` is not defined')); return; } if (!this.promisifiedCallback) { if (this.callback.length >= 3) { debug('Converting legacy callback function to promise'); this.promisifiedCallback = promisify_1.default(this.callback); } else { this.promisifiedCallback = this.callback; } } if (typeof timeoutMs === 'number' && timeoutMs > 0) { timeoutId = setTimeout(ontimeout, timeoutMs); } if ('port' in opts && typeof opts.port !== 'number') { opts.port = Number(opts.port); } try { debug('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`); Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError); } catch (err) { Promise.reject(err).catch(callbackError); } } freeSocket(socket, opts) { debug('Freeing socket %o %o', socket.constructor.name, opts); socket.destroy(); } destroy() { debug('Destroying agent %o', this.constructor.name); } } createAgent.Agent = Agent; // So that `instanceof` works correctly createAgent.prototype = createAgent.Agent.prototype; })(createAgent || (createAgent = {})); module.exports = createAgent; //# sourceMappingURL=index.js.map /***/ }), /***/ 2600: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); function promisify(fn) { return function (req, opts) { return new Promise((resolve, reject) => { fn.call(this, req, opts, (err, rtn) => { if (err) { reject(err); } else { resolve(rtn); } }); }); }; } exports["default"] = promisify; //# sourceMappingURL=promisify.js.map /***/ }), /***/ 3669: /***/ (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.HttpsProxyAgent = void 0; const net = __importStar(__nccwpck_require__(9278)); const tls = __importStar(__nccwpck_require__(4756)); const assert_1 = __importDefault(__nccwpck_require__(2613)); const debug_1 = __importDefault(__nccwpck_require__(2830)); const agent_base_1 = __nccwpck_require__(8894); const url_1 = __nccwpck_require__(7016); const parse_proxy_response_1 = __nccwpck_require__(7943); const debug = (0, debug_1.default)('https-proxy-agent'); const setServernameFromNonIpHost = (options) => { if (options.servername === undefined && options.host && !net.isIP(options.host)) { return { ...options, servername: options.host, }; } return options; }; /** * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. * * Outgoing HTTP requests are first tunneled through the proxy server using the * `CONNECT` HTTP request method to establish a connection to the proxy server, * and then the proxy server connects to the destination target and issues the * HTTP request from the proxy server. * * `https:` requests have their socket connection upgraded to TLS once * the connection to the proxy server has been established. */ class HttpsProxyAgent extends agent_base_1.Agent { constructor(proxy, opts) { super(opts); this.options = { path: undefined }; this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy; this.proxyHeaders = opts?.headers ?? {}; debug('Creating new HttpsProxyAgent instance: %o', this.proxy.href); // Trim off the brackets from IPv6 addresses const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ''); const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === 'https:' ? 443 : 80; this.connectOpts = { // Attempt to negotiate http/1.1 for proxy servers that support http/2 ALPNProtocols: ['http/1.1'], ...(opts ? omit(opts, 'headers') : null), host, port, }; } /** * Called when the node-core HTTP client library is creating a * new HTTP request. */ async connect(req, opts) { const { proxy } = this; if (!opts.host) { throw new TypeError('No "host" provided'); } // Create a socket connection to the proxy server. let socket; if (proxy.protocol === 'https:') { debug('Creating `tls.Socket`: %o', this.connectOpts); socket = tls.connect(setServernameFromNonIpHost(this.connectOpts)); } else { debug('Creating `net.Socket`: %o', this.connectOpts); socket = net.connect(this.connectOpts); } const headers = typeof this.proxyHeaders === 'function' ? this.proxyHeaders() : { ...this.proxyHeaders }; const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`; // Inject the `Proxy-Authorization` header if necessary. if (proxy.username || proxy.password) { const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`; } headers.Host = `${host}:${opts.port}`; if (!headers['Proxy-Connection']) { headers['Proxy-Connection'] = this.keepAlive ? 'Keep-Alive' : 'close'; } for (const name of Object.keys(headers)) { payload += `${name}: ${headers[name]}\r\n`; } const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket); socket.write(`${payload}\r\n`); const { connect, buffered } = await proxyResponsePromise; req.emit('proxyConnect', connect); this.emit('proxyConnect', connect, req); if (connect.statusCode === 200) { req.once('socket', resume); if (opts.secureEndpoint) { // The proxy is connecting to a TLS server, so upgrade // this socket connection to a TLS connection. debug('Upgrading socket connection to TLS'); return tls.connect({ ...omit(setServernameFromNonIpHost(opts), 'host', 'path', 'port'), socket, }); } return socket; } // Some other status code that's not 200... need to re-play the HTTP // header "data" events onto the socket once the HTTP machinery is // attached so that the node core `http` can parse and handle the // error status code. // Close the original socket, and a new "fake" socket is returned // instead, so that the proxy doesn't get the HTTP request // written to it (which may contain `Authorization` headers or other // sensitive data). // // See: https://hackerone.com/reports/541502 socket.destroy(); const fakeSocket = new net.Socket({ writable: false }); fakeSocket.readable = true; // Need to wait for the "socket" event to re-play the "data" events. req.once('socket', (s) => { debug('Replaying proxy buffer for failed request'); (0, assert_1.default)(s.listenerCount('data') > 0); // Replay the "buffered" Buffer onto the fake `socket`, since at // this point the HTTP module machinery has been hooked up for // the user. s.push(buffered); s.push(null); }); return fakeSocket; } } HttpsProxyAgent.protocols = ['http', 'https']; exports.HttpsProxyAgent = HttpsProxyAgent; function resume(socket) { socket.resume(); } function omit(obj, ...keys) { const ret = {}; let key; for (key in obj) { if (!keys.includes(key)) { ret[key] = obj[key]; } } return ret; } //# sourceMappingURL=index.js.map /***/ }), /***/ 7943: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseProxyResponse = void 0; const debug_1 = __importDefault(__nccwpck_require__(2830)); const debug = (0, debug_1.default)('https-proxy-agent:parse-proxy-response'); function parseProxyResponse(socket) { return new Promise((resolve, reject) => { // we need to buffer any HTTP traffic that happens with the proxy before we get // the CONNECT response, so that if the response is anything other than an "200" // response code, then we can re-play the "data" events on the socket once the // HTTP parser is hooked up... let buffersLength = 0; const buffers = []; function read() { const b = socket.read(); if (b) ondata(b); else socket.once('readable', read); } function cleanup() { socket.removeListener('end', onend); socket.removeListener('error', onerror); socket.removeListener('readable', read); } function onend() { cleanup(); debug('onend'); reject(new Error('Proxy connection ended before receiving CONNECT response')); } function onerror(err) { cleanup(); debug('onerror %o', err); reject(err); } function ondata(b) { buffers.push(b); buffersLength += b.length; const buffered = Buffer.concat(buffers, buffersLength); const endOfHeaders = buffered.indexOf('\r\n\r\n'); if (endOfHeaders === -1) { // keep buffering debug('have not received end of HTTP headers yet...'); read(); return; } const headerParts = buffered .slice(0, endOfHeaders) .toString('ascii') .split('\r\n'); const firstLine = headerParts.shift(); if (!firstLine) { socket.destroy(); return reject(new Error('No header received from proxy CONNECT response')); } const firstLineParts = firstLine.split(' '); const statusCode = +firstLineParts[1]; const statusText = firstLineParts.slice(2).join(' '); const headers = {}; for (const header of headerParts) { if (!header) continue; const firstColon = header.indexOf(':'); if (firstColon === -1) { socket.destroy(); return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); } const key = header.slice(0, firstColon).toLowerCase(); const value = header.slice(firstColon + 1).trimStart(); const current = headers[key]; if (typeof current === 'string') { headers[key] = [current, value]; } else if (Array.isArray(current)) { current.push(value); } else { headers[key] = value; } } debug('got proxy server response: %o %o', firstLine, headers); cleanup(); resolve({ connect: { statusCode, statusText, headers, }, buffered, }); } socket.on('error', onerror); socket.on('end', onend); read(); }); } exports.parseProxyResponse = parseProxyResponse; //# sourceMappingURL=parse-proxy-response.js.map /***/ }), /***/ 9598: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { try { var util = __nccwpck_require__(9023); /* istanbul ignore next */ if (typeof util.inherits !== 'function') throw ''; module.exports = util.inherits; } catch (e) { /* istanbul ignore next */ module.exports = __nccwpck_require__(6589); } /***/ }), /***/ 6589: /***/ ((module) => { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }) } }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } } /***/ }), /***/ 6543: /***/ ((module) => { "use strict"; const isStream = stream => stream !== null && typeof stream === 'object' && typeof stream.pipe === 'function'; isStream.writable = stream => isStream(stream) && stream.writable !== false && typeof stream._write === 'function' && typeof stream._writableState === 'object'; isStream.readable = stream => isStream(stream) && stream.readable !== false && typeof stream._read === 'function' && typeof stream._readableState === 'object'; isStream.duplex = stream => isStream.writable(stream) && isStream.readable(stream); isStream.transform = stream => isStream.duplex(stream) && typeof stream._transform === 'function'; module.exports = isStream; /***/ }), /***/ 4826: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var json_stringify = (__nccwpck_require__(3651).stringify); var json_parse = __nccwpck_require__(3197); module.exports = function(options) { return { parse: json_parse(options), stringify: json_stringify } }; //create the default method members with no options applied for backwards compatibility module.exports.parse = json_parse(); module.exports.stringify = json_stringify; /***/ }), /***/ 3197: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var BigNumber = null; // regexpxs extracted from // (c) BSD-3-Clause // https://github.com/fastify/secure-json-parse/graphs/contributors and https://github.com/hapijs/bourne/graphs/contributors const suspectProtoRx = /(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/; const suspectConstructorRx = /(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/; /* json_parse.js 2012-06-20 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. This file creates a json_parse function. During create you can (optionally) specify some behavioural switches require('json-bigint')(options) The optional options parameter holds switches that drive certain aspects of the parsing process: * options.strict = true will warn about duplicate-key usage in the json. The default (strict = false) will silently ignore those and overwrite values for keys that are in duplicate use. The resulting function follows this signature: json_parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = json_parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. */ /*members "", "\"", "\/", "\\", at, b, call, charAt, f, fromCharCode, hasOwnProperty, message, n, name, prototype, push, r, t, text */ var json_parse = function (options) { 'use strict'; // This is a function that can parse a JSON text, producing a JavaScript // data structure. It is a simple, recursive descent parser. It does not use // eval or regular expressions, so it can be used as a model for implementing // a JSON parser in other languages. // We are defining the function inside of another function to avoid creating // global variables. // Default options one can override by passing options to the parse() var _options = { strict: false, // not being strict means do not generate syntax errors for "duplicate key" storeAsString: false, // toggles whether the values should be stored as BigNumber (default) or a string alwaysParseAsBig: false, // toggles whether all numbers should be Big useNativeBigInt: false, // toggles whether to use native BigInt instead of bignumber.js protoAction: 'error', constructorAction: 'error', }; // If there are options, then use them to override the default _options if (options !== undefined && options !== null) { if (options.strict === true) { _options.strict = true; } if (options.storeAsString === true) { _options.storeAsString = true; } _options.alwaysParseAsBig = options.alwaysParseAsBig === true ? options.alwaysParseAsBig : false; _options.useNativeBigInt = options.useNativeBigInt === true ? options.useNativeBigInt : false; if (typeof options.constructorAction !== 'undefined') { if ( options.constructorAction === 'error' || options.constructorAction === 'ignore' || options.constructorAction === 'preserve' ) { _options.constructorAction = options.constructorAction; } else { throw new Error( `Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${options.constructorAction}` ); } } if (typeof options.protoAction !== 'undefined') { if ( options.protoAction === 'error' || options.protoAction === 'ignore' || options.protoAction === 'preserve' ) { _options.protoAction = options.protoAction; } else { throw new Error( `Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${options.protoAction}` ); } } } var at, // The index of the current character ch, // The current character escapee = { '"': '"', '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t', }, text, error = function (m) { // Call error when something is wrong. throw { name: 'SyntaxError', message: m, at: at, text: text, }; }, next = function (c) { // If a c parameter is provided, verify that it matches the current character. if (c && c !== ch) { error("Expected '" + c + "' instead of '" + ch + "'"); } // Get the next character. When there are no more characters, // return the empty string. ch = text.charAt(at); at += 1; return ch; }, number = function () { // Parse a number value. var number, string = ''; if (ch === '-') { string = '-'; next('-'); } while (ch >= '0' && ch <= '9') { string += ch; next(); } if (ch === '.') { string += '.'; while (next() && ch >= '0' && ch <= '9') { string += ch; } } if (ch === 'e' || ch === 'E') { string += ch; next(); if (ch === '-' || ch === '+') { string += ch; next(); } while (ch >= '0' && ch <= '9') { string += ch; next(); } } number = +string; if (!isFinite(number)) { error('Bad number'); } else { if (BigNumber == null) BigNumber = __nccwpck_require__(1259); //if (number > 9007199254740992 || number < -9007199254740992) // Bignumber has stricter check: everything with length > 15 digits disallowed if (string.length > 15) return _options.storeAsString ? string : _options.useNativeBigInt ? BigInt(string) : new BigNumber(string); else return !_options.alwaysParseAsBig ? number : _options.useNativeBigInt ? BigInt(number) : new BigNumber(number); } }, string = function () { // Parse a string value. var hex, i, string = '', uffff; // When parsing for string values, we must look for " and \ characters. if (ch === '"') { var startAt = at; while (next()) { if (ch === '"') { if (at - 1 > startAt) string += text.substring(startAt, at - 1); next(); return string; } if (ch === '\\') { if (at - 1 > startAt) string += text.substring(startAt, at - 1); next(); if (ch === 'u') { uffff = 0; for (i = 0; i < 4; i += 1) { hex = parseInt(next(), 16); if (!isFinite(hex)) { break; } uffff = uffff * 16 + hex; } string += String.fromCharCode(uffff); } else if (typeof escapee[ch] === 'string') { string += escapee[ch]; } else { break; } startAt = at; } } } error('Bad string'); }, white = function () { // Skip whitespace. while (ch && ch <= ' ') { next(); } }, word = function () { // true, false, or null. switch (ch) { case 't': next('t'); next('r'); next('u'); next('e'); return true; case 'f': next('f'); next('a'); next('l'); next('s'); next('e'); return false; case 'n': next('n'); next('u'); next('l'); next('l'); return null; } error("Unexpected '" + ch + "'"); }, value, // Place holder for the value function. array = function () { // Parse an array value. var array = []; if (ch === '[') { next('['); white(); if (ch === ']') { next(']'); return array; // empty array } while (ch) { array.push(value()); white(); if (ch === ']') { next(']'); return array; } next(','); white(); } } error('Bad array'); }, object = function () { // Parse an object value. var key, object = Object.create(null); if (ch === '{') { next('{'); white(); if (ch === '}') { next('}'); return object; // empty object } while (ch) { key = string(); white(); next(':'); if ( _options.strict === true && Object.hasOwnProperty.call(object, key) ) { error('Duplicate key "' + key + '"'); } if (suspectProtoRx.test(key) === true) { if (_options.protoAction === 'error') { error('Object contains forbidden prototype property'); } else if (_options.protoAction === 'ignore') { value(); } else { object[key] = value(); } } else if (suspectConstructorRx.test(key) === true) { if (_options.constructorAction === 'error') { error('Object contains forbidden constructor property'); } else if (_options.constructorAction === 'ignore') { value(); } else { object[key] = value(); } } else { object[key] = value(); } white(); if (ch === '}') { next('}'); return object; } next(','); white(); } } error('Bad object'); }; value = function () { // Parse a JSON value. It could be an object, an array, a string, a number, // or a word. white(); switch (ch) { case '{': return object(); case '[': return array(); case '"': return string(); case '-': return number(); default: return ch >= '0' && ch <= '9' ? number() : word(); } }; // Return the json_parse function. It will have access to all of the above // functions and variables. return function (source, reviver) { var result; text = source + ''; at = 0; ch = ' '; result = value(); white(); if (ch) { error('Syntax error'); } // If there is a reviver function, we recursively walk the new structure, // passing each name/value pair to the reviver function for possible // transformation, starting with a temporary root object that holds the result // in an empty key. If there is not a reviver function, we simply return the // result. return typeof reviver === 'function' ? (function walk(holder, key) { var k, v, value = holder[key]; if (value && typeof value === 'object') { Object.keys(value).forEach(function (k) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } }); } return reviver.call(holder, key, value); })({ '': result }, '') : result; }; }; module.exports = json_parse; /***/ }), /***/ 3651: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var BigNumber = __nccwpck_require__(1259); /* json2.js 2013-05-26 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or ' '), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, regexp: true */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. var JSON = module.exports; (function () { 'use strict'; function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key], isBigNumber = value != null && (value instanceof BigNumber || BigNumber.isBigNumber(value)); // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': if (isBigNumber) { return value; } else { return quote(value); } case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': case 'bigint': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === 'string') { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. Object.keys(value).forEach(function(k) { var v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } }); } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } }()); /***/ }), /***/ 8622: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var bufferEqual = __nccwpck_require__(9732); var Buffer = (__nccwpck_require__(3058).Buffer); var crypto = __nccwpck_require__(6982); var formatEcdsa = __nccwpck_require__(325); var util = __nccwpck_require__(9023); var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".' var MSG_INVALID_SECRET = 'secret must be a string or buffer'; var MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer'; var MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object'; var supportsKeyObjects = typeof crypto.createPublicKey === 'function'; if (supportsKeyObjects) { MSG_INVALID_VERIFIER_KEY += ' or a KeyObject'; MSG_INVALID_SECRET += 'or a KeyObject'; } function checkIsPublicKey(key) { if (Buffer.isBuffer(key)) { return; } if (typeof key === 'string') { return; } if (!supportsKeyObjects) { throw typeError(MSG_INVALID_VERIFIER_KEY); } if (typeof key !== 'object') { throw typeError(MSG_INVALID_VERIFIER_KEY); } if (typeof key.type !== 'string') { throw typeError(MSG_INVALID_VERIFIER_KEY); } if (typeof key.asymmetricKeyType !== 'string') { throw typeError(MSG_INVALID_VERIFIER_KEY); } if (typeof key.export !== 'function') { throw typeError(MSG_INVALID_VERIFIER_KEY); } }; function checkIsPrivateKey(key) { if (Buffer.isBuffer(key)) { return; } if (typeof key === 'string') { return; } if (typeof key === 'object') { return; } throw typeError(MSG_INVALID_SIGNER_KEY); }; function checkIsSecretKey(key) { if (Buffer.isBuffer(key)) { return; } if (typeof key === 'string') { return key; } if (!supportsKeyObjects) { throw typeError(MSG_INVALID_SECRET); } if (typeof key !== 'object') { throw typeError(MSG_INVALID_SECRET); } if (key.type !== 'secret') { throw typeError(MSG_INVALID_SECRET); } if (typeof key.export !== 'function') { throw typeError(MSG_INVALID_SECRET); } } function fromBase64(base64) { return base64 .replace(/=/g, '') .replace(/\+/g, '-') .replace(/\//g, '_'); } function toBase64(base64url) { base64url = base64url.toString(); var padding = 4 - base64url.length % 4; if (padding !== 4) { for (var i = 0; i < padding; ++i) { base64url += '='; } } return base64url .replace(/\-/g, '+') .replace(/_/g, '/'); } function typeError(template) { var args = [].slice.call(arguments, 1); var errMsg = util.format.bind(util, template).apply(null, args); return new TypeError(errMsg); } function bufferOrString(obj) { return Buffer.isBuffer(obj) || typeof obj === 'string'; } function normalizeInput(thing) { if (!bufferOrString(thing)) thing = JSON.stringify(thing); return thing; } function createHmacSigner(bits) { return function sign(thing, secret) { checkIsSecretKey(secret); thing = normalizeInput(thing); var hmac = crypto.createHmac('sha' + bits, secret); var sig = (hmac.update(thing), hmac.digest('base64')) return fromBase64(sig); } } function createHmacVerifier(bits) { return function verify(thing, signature, secret) { var computedSig = createHmacSigner(bits)(thing, secret); return bufferEqual(Buffer.from(signature), Buffer.from(computedSig)); } } function createKeySigner(bits) { return function sign(thing, privateKey) { checkIsPrivateKey(privateKey); thing = normalizeInput(thing); // Even though we are specifying "RSA" here, this works with ECDSA // keys as well. var signer = crypto.createSign('RSA-SHA' + bits); var sig = (signer.update(thing), signer.sign(privateKey, 'base64')); return fromBase64(sig); } } function createKeyVerifier(bits) { return function verify(thing, signature, publicKey) { checkIsPublicKey(publicKey); thing = normalizeInput(thing); signature = toBase64(signature); var verifier = crypto.createVerify('RSA-SHA' + bits); verifier.update(thing); return verifier.verify(publicKey, signature, 'base64'); } } function createPSSKeySigner(bits) { return function sign(thing, privateKey) { checkIsPrivateKey(privateKey); thing = normalizeInput(thing); var signer = crypto.createSign('RSA-SHA' + bits); var sig = (signer.update(thing), signer.sign({ key: privateKey, padding: crypto.constants.RSA_PKCS1_PSS_PADDING, saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST }, 'base64')); return fromBase64(sig); } } function createPSSKeyVerifier(bits) { return function verify(thing, signature, publicKey) { checkIsPublicKey(publicKey); thing = normalizeInput(thing); signature = toBase64(signature); var verifier = crypto.createVerify('RSA-SHA' + bits); verifier.update(thing); return verifier.verify({ key: publicKey, padding: crypto.constants.RSA_PKCS1_PSS_PADDING, saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST }, signature, 'base64'); } } function createECDSASigner(bits) { var inner = createKeySigner(bits); return function sign() { var signature = inner.apply(null, arguments); signature = formatEcdsa.derToJose(signature, 'ES' + bits); return signature; }; } function createECDSAVerifer(bits) { var inner = createKeyVerifier(bits); return function verify(thing, signature, publicKey) { signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64'); var result = inner(thing, signature, publicKey); return result; }; } function createNoneSigner() { return function sign() { return ''; } } function createNoneVerifier() { return function verify(thing, signature) { return signature === ''; } } module.exports = function jwa(algorithm) { var signerFactories = { hs: createHmacSigner, rs: createKeySigner, ps: createPSSKeySigner, es: createECDSASigner, none: createNoneSigner, } var verifierFactories = { hs: createHmacVerifier, rs: createKeyVerifier, ps: createPSSKeyVerifier, es: createECDSAVerifer, none: createNoneVerifier, } var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/); if (!match) throw typeError(MSG_INVALID_ALGORITHM, algorithm); var algo = (match[1] || match[3]).toLowerCase(); var bits = match[2]; return { sign: signerFactories[algo](bits), verify: verifierFactories[algo](bits), } }; /***/ }), /***/ 3324: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { /*global exports*/ var SignStream = __nccwpck_require__(8600); var VerifyStream = __nccwpck_require__(4368); var ALGORITHMS = [ 'HS256', 'HS384', 'HS512', 'RS256', 'RS384', 'RS512', 'PS256', 'PS384', 'PS512', 'ES256', 'ES384', 'ES512' ]; exports.ALGORITHMS = ALGORITHMS; exports.sign = SignStream.sign; exports.verify = VerifyStream.verify; exports.decode = VerifyStream.decode; exports.isValid = VerifyStream.isValid; exports.createSign = function createSign(opts) { return new SignStream(opts); }; exports.createVerify = function createVerify(opts) { return new VerifyStream(opts); }; /***/ }), /***/ 1831: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /*global module, process*/ var Buffer = (__nccwpck_require__(3058).Buffer); var Stream = __nccwpck_require__(2203); var util = __nccwpck_require__(9023); function DataStream(data) { this.buffer = null; this.writable = true; this.readable = true; // No input if (!data) { this.buffer = Buffer.alloc(0); return this; } // Stream if (typeof data.pipe === 'function') { this.buffer = Buffer.alloc(0); data.pipe(this); return this; } // Buffer or String // or Object (assumedly a passworded key) if (data.length || typeof data === 'object') { this.buffer = data; this.writable = false; process.nextTick(function () { this.emit('end', data); this.readable = false; this.emit('close'); }.bind(this)); return this; } throw new TypeError('Unexpected data type ('+ typeof data + ')'); } util.inherits(DataStream, Stream); DataStream.prototype.write = function write(data) { this.buffer = Buffer.concat([this.buffer, Buffer.from(data)]); this.emit('data', data); }; DataStream.prototype.end = function end(data) { if (data) this.write(data); this.emit('end', data); this.emit('close'); this.writable = false; this.readable = false; }; module.exports = DataStream; /***/ }), /***/ 8600: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /*global module*/ var Buffer = (__nccwpck_require__(3058).Buffer); var DataStream = __nccwpck_require__(1831); var jwa = __nccwpck_require__(8622); var Stream = __nccwpck_require__(2203); var toString = __nccwpck_require__(5126); var util = __nccwpck_require__(9023); function base64url(string, encoding) { return Buffer .from(string, encoding) .toString('base64') .replace(/=/g, '') .replace(/\+/g, '-') .replace(/\//g, '_'); } function jwsSecuredInput(header, payload, encoding) { encoding = encoding || 'utf8'; var encodedHeader = base64url(toString(header), 'binary'); var encodedPayload = base64url(toString(payload), encoding); return util.format('%s.%s', encodedHeader, encodedPayload); } function jwsSign(opts) { var header = opts.header; var payload = opts.payload; var secretOrKey = opts.secret || opts.privateKey; var encoding = opts.encoding; var algo = jwa(header.alg); var securedInput = jwsSecuredInput(header, payload, encoding); var signature = algo.sign(securedInput, secretOrKey); return util.format('%s.%s', securedInput, signature); } function SignStream(opts) { var secret = opts.secret||opts.privateKey||opts.key; var secretStream = new DataStream(secret); this.readable = true; this.header = opts.header; this.encoding = opts.encoding; this.secret = this.privateKey = this.key = secretStream; this.payload = new DataStream(opts.payload); this.secret.once('close', function () { if (!this.payload.writable && this.readable) this.sign(); }.bind(this)); this.payload.once('close', function () { if (!this.secret.writable && this.readable) this.sign(); }.bind(this)); } util.inherits(SignStream, Stream); SignStream.prototype.sign = function sign() { try { var signature = jwsSign({ header: this.header, payload: this.payload.buffer, secret: this.secret.buffer, encoding: this.encoding }); this.emit('done', signature); this.emit('data', signature); this.emit('end'); this.readable = false; return signature; } catch (e) { this.readable = false; this.emit('error', e); this.emit('close'); } }; SignStream.sign = jwsSign; module.exports = SignStream; /***/ }), /***/ 5126: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /*global module*/ var Buffer = (__nccwpck_require__(181).Buffer); module.exports = function toString(obj) { if (typeof obj === 'string') return obj; if (typeof obj === 'number' || Buffer.isBuffer(obj)) return obj.toString(); return JSON.stringify(obj); }; /***/ }), /***/ 4368: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /*global module*/ var Buffer = (__nccwpck_require__(3058).Buffer); var DataStream = __nccwpck_require__(1831); var jwa = __nccwpck_require__(8622); var Stream = __nccwpck_require__(2203); var toString = __nccwpck_require__(5126); var util = __nccwpck_require__(9023); var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/; function isObject(thing) { return Object.prototype.toString.call(thing) === '[object Object]'; } function safeJsonParse(thing) { if (isObject(thing)) return thing; try { return JSON.parse(thing); } catch (e) { return undefined; } } function headerFromJWS(jwsSig) { var encodedHeader = jwsSig.split('.', 1)[0]; return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary')); } function securedInputFromJWS(jwsSig) { return jwsSig.split('.', 2).join('.'); } function signatureFromJWS(jwsSig) { return jwsSig.split('.')[2]; } function payloadFromJWS(jwsSig, encoding) { encoding = encoding || 'utf8'; var payload = jwsSig.split('.')[1]; return Buffer.from(payload, 'base64').toString(encoding); } function isValidJws(string) { return JWS_REGEX.test(string) && !!headerFromJWS(string); } function jwsVerify(jwsSig, algorithm, secretOrKey) { if (!algorithm) { var err = new Error("Missing algorithm parameter for jws.verify"); err.code = "MISSING_ALGORITHM"; throw err; } jwsSig = toString(jwsSig); var signature = signatureFromJWS(jwsSig); var securedInput = securedInputFromJWS(jwsSig); var algo = jwa(algorithm); return algo.verify(securedInput, signature, secretOrKey); } function jwsDecode(jwsSig, opts) { opts = opts || {}; jwsSig = toString(jwsSig); if (!isValidJws(jwsSig)) return null; var header = headerFromJWS(jwsSig); if (!header) return null; var payload = payloadFromJWS(jwsSig); if (header.typ === 'JWT' || opts.json) payload = JSON.parse(payload, opts.encoding); return { header: header, payload: payload, signature: signatureFromJWS(jwsSig) }; } function VerifyStream(opts) { opts = opts || {}; var secretOrKey = opts.secret||opts.publicKey||opts.key; var secretStream = new DataStream(secretOrKey); this.readable = true; this.algorithm = opts.algorithm; this.encoding = opts.encoding; this.secret = this.publicKey = this.key = secretStream; this.signature = new DataStream(opts.signature); this.secret.once('close', function () { if (!this.signature.writable && this.readable) this.verify(); }.bind(this)); this.signature.once('close', function () { if (!this.secret.writable && this.readable) this.verify(); }.bind(this)); } util.inherits(VerifyStream, Stream); VerifyStream.prototype.verify = function verify() { try { var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer); var obj = jwsDecode(this.signature.buffer, this.encoding); this.emit('done', valid, obj); this.emit('data', valid); this.emit('end'); this.readable = false; return valid; } catch (e) { this.readable = false; this.emit('error', e); this.emit('close'); } }; VerifyStream.decode = jwsDecode; VerifyStream.isValid = isValidJws; VerifyStream.verify = jwsVerify; module.exports = VerifyStream; /***/ }), /***/ 9829: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /*! * mime-db * Copyright(c) 2014 Jonathan Ong * MIT Licensed */ /** * Module exports. */ module.exports = __nccwpck_require__(1813) /***/ }), /***/ 4096: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /*! * mime-types * Copyright(c) 2014 Jonathan Ong * Copyright(c) 2015 Douglas Christopher Wilson * MIT Licensed */ /** * Module dependencies. * @private */ var db = __nccwpck_require__(9829) var extname = (__nccwpck_require__(6928).extname) /** * Module variables. * @private */ var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ var TEXT_TYPE_REGEXP = /^text\//i /** * Module exports. * @public */ exports.charset = charset exports.charsets = { lookup: charset } exports.contentType = contentType exports.extension = extension exports.extensions = Object.create(null) exports.lookup = lookup exports.types = Object.create(null) // Populate the extensions/types maps populateMaps(exports.extensions, exports.types) /** * Get the default charset for a MIME type. * * @param {string} type * @return {boolean|string} */ function charset (type) { if (!type || typeof type !== 'string') { return false } // TODO: use media-typer var match = EXTRACT_TYPE_REGEXP.exec(type) var mime = match && db[match[1].toLowerCase()] if (mime && mime.charset) { return mime.charset } // default text/* to utf-8 if (match && TEXT_TYPE_REGEXP.test(match[1])) { return 'UTF-8' } return false } /** * Create a full Content-Type header given a MIME type or extension. * * @param {string} str * @return {boolean|string} */ function contentType (str) { // TODO: should this even be in this module? if (!str || typeof str !== 'string') { return false } var mime = str.indexOf('/') === -1 ? exports.lookup(str) : str if (!mime) { return false } // TODO: use content-type or other module if (mime.indexOf('charset') === -1) { var charset = exports.charset(mime) if (charset) mime += '; charset=' + charset.toLowerCase() } return mime } /** * Get the default extension for a MIME type. * * @param {string} type * @return {boolean|string} */ function extension (type) { if (!type || typeof type !== 'string') { return false } // TODO: use media-typer var match = EXTRACT_TYPE_REGEXP.exec(type) // get extensions var exts = match && exports.extensions[match[1].toLowerCase()] if (!exts || !exts.length) { return false } return exts[0] } /** * Lookup the MIME type for a file path/extension. * * @param {string} path * @return {boolean|string} */ function lookup (path) { if (!path || typeof path !== 'string') { return false } // get the extension ("ext" or ".ext" or full path) var extension = extname('x.' + path) .toLowerCase() .substr(1) if (!extension) { return false } return exports.types[extension] || false } /** * Populate the extensions and types maps. * @private */ function populateMaps (extensions, types) { // source preference (least -> most) var preference = ['nginx', 'apache', undefined, 'iana'] Object.keys(db).forEach(function forEachMimeType (type) { var mime = db[type] var exts = mime.extensions if (!exts || !exts.length) { return } // mime -> extensions extensions[type] = exts // extension -> mime for (var i = 0; i < exts.length; i++) { var extension = exts[i] if (types[extension]) { var from = preference.indexOf(db[types[extension]].source) var to = preference.indexOf(mime.source) if (types[extension] !== 'application/octet-stream' && (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { // skip the remapping continue } } // set the extension -> mime types[extension] = type } }) } /***/ }), /***/ 4402: /***/ ((module) => { "use strict"; /** * @param typeMap [Object] Map of MIME type -> Array[extensions] * @param ... */ function Mime() { this._types = Object.create(null); this._extensions = Object.create(null); for (let i = 0; i < arguments.length; i++) { this.define(arguments[i]); } this.define = this.define.bind(this); this.getType = this.getType.bind(this); this.getExtension = this.getExtension.bind(this); } /** * Define mimetype -> extension mappings. Each key is a mime-type that maps * to an array of extensions associated with the type. The first extension is * used as the default extension for the type. * * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); * * If a type declares an extension that has already been defined, an error will * be thrown. To suppress this error and force the extension to be associated * with the new type, pass `force`=true. Alternatively, you may prefix the * extension with "*" to map the type to extension, without mapping the * extension to the type. * * e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']}); * * * @param map (Object) type definitions * @param force (Boolean) if true, force overriding of existing definitions */ Mime.prototype.define = function(typeMap, force) { for (let type in typeMap) { let extensions = typeMap[type].map(function(t) { return t.toLowerCase(); }); type = type.toLowerCase(); for (let i = 0; i < extensions.length; i++) { const ext = extensions[i]; // '*' prefix = not the preferred type for this extension. So fixup the // extension, and skip it. if (ext[0] === '*') { continue; } if (!force && (ext in this._types)) { throw new Error( 'Attempt to change mapping for "' + ext + '" extension from "' + this._types[ext] + '" to "' + type + '". Pass `force=true` to allow this, otherwise remove "' + ext + '" from the list of extensions for "' + type + '".' ); } this._types[ext] = type; } // Use first extension as default if (force || !this._extensions[type]) { const ext = extensions[0]; this._extensions[type] = (ext[0] !== '*') ? ext : ext.substr(1); } } }; /** * Lookup a mime type based on extension */ Mime.prototype.getType = function(path) { path = String(path); let last = path.replace(/^.*[/\\]/, '').toLowerCase(); let ext = last.replace(/^.*\./, '').toLowerCase(); let hasPath = last.length < path.length; let hasDot = ext.length < last.length - 1; return (hasDot || !hasPath) && this._types[ext] || null; }; /** * Return file extension associated with a mime type */ Mime.prototype.getExtension = function(type) { type = /^\s*([^;\s]*)/.test(type) && RegExp.$1; return type && this._extensions[type.toLowerCase()] || null; }; module.exports = Mime; /***/ }), /***/ 4900: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; let Mime = __nccwpck_require__(4402); module.exports = new Mime(__nccwpck_require__(3725), __nccwpck_require__(8548)); /***/ }), /***/ 8548: /***/ ((module) => { module.exports = {"application/prs.cww":["cww"],"application/vnd.1000minds.decision-model+xml":["1km"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"application/vnd.3gpp2.tcap":["tcap"],"application/vnd.3m.post-it-notes":["pwn"],"application/vnd.accpac.simply.aso":["aso"],"application/vnd.accpac.simply.imp":["imp"],"application/vnd.acucobol":["acu"],"application/vnd.acucorp":["atc","acutc"],"application/vnd.adobe.air-application-installer-package+zip":["air"],"application/vnd.adobe.formscentral.fcdt":["fcdt"],"application/vnd.adobe.fxp":["fxp","fxpl"],"application/vnd.adobe.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["xfdf"],"application/vnd.ahead.space":["ahead"],"application/vnd.airzip.filesecure.azf":["azf"],"application/vnd.airzip.filesecure.azs":["azs"],"application/vnd.amazon.ebook":["azw"],"application/vnd.americandynamics.acc":["acc"],"application/vnd.amiga.ami":["ami"],"application/vnd.android.package-archive":["apk"],"application/vnd.anser-web-certificate-issue-initiation":["cii"],"application/vnd.anser-web-funds-transfer-initiation":["fti"],"application/vnd.antix.game-component":["atx"],"application/vnd.apple.installer+xml":["mpkg"],"application/vnd.apple.keynote":["key"],"application/vnd.apple.mpegurl":["m3u8"],"application/vnd.apple.numbers":["numbers"],"application/vnd.apple.pages":["pages"],"application/vnd.apple.pkpass":["pkpass"],"application/vnd.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.balsamiq.bmml+xml":["bmml"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"application/vnd.citationstyles.style+xml":["csl"],"application/vnd.claymore":["cla"],"application/vnd.cloanto.rp9":["rp9"],"application/vnd.clonk.c4group":["c4g","c4d","c4f","c4p","c4u"],"application/vnd.cluetrust.cartomobile-config":["c11amc"],"application/vnd.cluetrust.cartomobile-config-pkg":["c11amz"],"application/vnd.commonspace":["csp"],"application/vnd.contact.cmsg":["cdbcmsg"],"application/vnd.cosmocaller":["cmc"],"application/vnd.crick.clicker":["clkx"],"application/vnd.crick.clicker.keyboard":["clkk"],"application/vnd.crick.clicker.palette":["clkp"],"application/vnd.crick.clicker.template":["clkt"],"application/vnd.crick.clicker.wordbank":["clkw"],"application/vnd.criticaltools.wbs+xml":["wbs"],"application/vnd.ctc-posml":["pml"],"application/vnd.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"application/vnd.dart":["dart"],"application/vnd.data-vision.rdz":["rdz"],"application/vnd.dbf":["dbf"],"application/vnd.dece.data":["uvf","uvvf","uvd","uvvd"],"application/vnd.dece.ttml+xml":["uvt","uvvt"],"application/vnd.dece.unspecified":["uvx","uvvx"],"application/vnd.dece.zip":["uvz","uvvz"],"application/vnd.denovo.fcselayout-link":["fe_launch"],"application/vnd.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"application/vnd.epson.esf":["esf"],"application/vnd.epson.msf":["msf"],"application/vnd.epson.quickanime":["qam"],"application/vnd.epson.salt":["slt"],"application/vnd.epson.ssf":["ssf"],"application/vnd.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"application/vnd.framemaker":["fm","frame","maker","book"],"application/vnd.frogans.fnc":["fnc"],"application/vnd.frogans.ltf":["ltf"],"application/vnd.fsc.weblaunch":["fsc"],"application/vnd.fujitsu.oasys":["oas"],"application/vnd.fujitsu.oasys2":["oa2"],"application/vnd.fujitsu.oasys3":["oa3"],"application/vnd.fujitsu.oasysgp":["fg5"],"application/vnd.fujitsu.oasysprs":["bh2"],"application/vnd.fujixerox.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"application/vnd.geogebra.file":["ggb"],"application/vnd.geogebra.tool":["ggt"],"application/vnd.geometry-explorer":["gex","gre"],"application/vnd.geonext":["gxt"],"application/vnd.geoplan":["g2w"],"application/vnd.geospace":["g3w"],"application/vnd.gmx":["gmx"],"application/vnd.google-apps.document":["gdoc"],"application/vnd.google-apps.presentation":["gslides"],"application/vnd.google-apps.spreadsheet":["gsheet"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"application/vnd.groove-account":["gac"],"application/vnd.groove-help":["ghf"],"application/vnd.groove-identity-message":["gim"],"application/vnd.groove-injector":["grv"],"application/vnd.groove-tool-message":["gtm"],"application/vnd.groove-tool-template":["tpl"],"application/vnd.groove-vcard":["vcg"],"application/vnd.hal+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"application/vnd.hhe.lesson-player":["les"],"application/vnd.hp-hpgl":["hpgl"],"application/vnd.hp-hpid":["hpid"],"application/vnd.hp-hps":["hps"],"application/vnd.hp-jlyt":["jlt"],"application/vnd.hp-pcl":["pcl"],"application/vnd.hp-pclxl":["pclxl"],"application/vnd.hydrostatix.sof-data":["sfd-hdstx"],"application/vnd.ibm.minipay":["mpy"],"application/vnd.ibm.modcap":["afp","listafp","list3820"],"application/vnd.ibm.rights-management":["irm"],"application/vnd.ibm.secure-container":["sc"],"application/vnd.iccprofile":["icc","icm"],"application/vnd.igloader":["igl"],"application/vnd.immervision-ivp":["ivp"],"application/vnd.immervision-ivu":["ivu"],"application/vnd.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"application/vnd.ipunplugged.rcprofile":["rcprofile"],"application/vnd.irepository.package+xml":["irp"],"application/vnd.is-xpr":["xpr"],"application/vnd.isac.fcs":["fcs"],"application/vnd.jam":["jam"],"application/vnd.jcp.javame.midlet-rms":["rms"],"application/vnd.jisp":["jisp"],"application/vnd.joost.joda-archive":["joda"],"application/vnd.kahootz":["ktz","ktr"],"application/vnd.kde.karbon":["karbon"],"application/vnd.kde.kchart":["chrt"],"application/vnd.kde.kformula":["kfo"],"application/vnd.kde.kivio":["flw"],"application/vnd.kde.kontour":["kon"],"application/vnd.kde.kpresenter":["kpr","kpt"],"application/vnd.kde.kspread":["ksp"],"application/vnd.kde.kword":["kwd","kwt"],"application/vnd.kenameaapp":["htke"],"application/vnd.kidspiration":["kia"],"application/vnd.kinar":["kne","knp"],"application/vnd.koan":["skp","skd","skt","skm"],"application/vnd.kodak-descriptor":["sse"],"application/vnd.las.las+xml":["lasxml"],"application/vnd.llamagraphics.life-balance.desktop":["lbd"],"application/vnd.llamagraphics.life-balance.exchange+xml":["lbe"],"application/vnd.lotus-1-2-3":["123"],"application/vnd.lotus-approach":["apr"],"application/vnd.lotus-freelance":["pre"],"application/vnd.lotus-notes":["nsf"],"application/vnd.lotus-organizer":["org"],"application/vnd.lotus-screencam":["scm"],"application/vnd.lotus-wordpro":["lwp"],"application/vnd.macports.portpkg":["portpkg"],"application/vnd.mapbox-vector-tile":["mvt"],"application/vnd.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"application/vnd.mobius.daf":["daf"],"application/vnd.mobius.dis":["dis"],"application/vnd.mobius.mbk":["mbk"],"application/vnd.mobius.mqy":["mqy"],"application/vnd.mobius.msl":["msl"],"application/vnd.mobius.plc":["plc"],"application/vnd.mobius.txf":["txf"],"application/vnd.mophun.application":["mpn"],"application/vnd.mophun.certificate":["mpc"],"application/vnd.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"application/vnd.ms-excel":["xls","xlm","xla","xlc","xlt","xlw"],"application/vnd.ms-excel.addin.macroenabled.12":["xlam"],"application/vnd.ms-excel.sheet.binary.macroenabled.12":["xlsb"],"application/vnd.ms-excel.sheet.macroenabled.12":["xlsm"],"application/vnd.ms-excel.template.macroenabled.12":["xltm"],"application/vnd.ms-fontobject":["eot"],"application/vnd.ms-htmlhelp":["chm"],"application/vnd.ms-ims":["ims"],"application/vnd.ms-lrm":["lrm"],"application/vnd.ms-officetheme":["thmx"],"application/vnd.ms-outlook":["msg"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["*stl"],"application/vnd.ms-powerpoint":["ppt","pps","pot"],"application/vnd.ms-powerpoint.addin.macroenabled.12":["ppam"],"application/vnd.ms-powerpoint.presentation.macroenabled.12":["pptm"],"application/vnd.ms-powerpoint.slide.macroenabled.12":["sldm"],"application/vnd.ms-powerpoint.slideshow.macroenabled.12":["ppsm"],"application/vnd.ms-powerpoint.template.macroenabled.12":["potm"],"application/vnd.ms-project":["mpp","mpt"],"application/vnd.ms-word.document.macroenabled.12":["docm"],"application/vnd.ms-word.template.macroenabled.12":["dotm"],"application/vnd.ms-works":["wps","wks","wcm","wdb"],"application/vnd.ms-wpl":["wpl"],"application/vnd.ms-xpsdocument":["xps"],"application/vnd.mseq":["mseq"],"application/vnd.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"application/vnd.neurolanguage.nlu":["nlu"],"application/vnd.nitf":["ntf","nitf"],"application/vnd.noblenet-directory":["nnd"],"application/vnd.noblenet-sealer":["nns"],"application/vnd.noblenet-web":["nnw"],"application/vnd.nokia.n-gage.ac+xml":["*ac"],"application/vnd.nokia.n-gage.data":["ngdat"],"application/vnd.nokia.n-gage.symbian.install":["n-gage"],"application/vnd.nokia.radio-preset":["rpst"],"application/vnd.nokia.radio-presets":["rpss"],"application/vnd.novadigm.edm":["edm"],"application/vnd.novadigm.edx":["edx"],"application/vnd.novadigm.ext":["ext"],"application/vnd.oasis.opendocument.chart":["odc"],"application/vnd.oasis.opendocument.chart-template":["otc"],"application/vnd.oasis.opendocument.database":["odb"],"application/vnd.oasis.opendocument.formula":["odf"],"application/vnd.oasis.opendocument.formula-template":["odft"],"application/vnd.oasis.opendocument.graphics":["odg"],"application/vnd.oasis.opendocument.graphics-template":["otg"],"application/vnd.oasis.opendocument.image":["odi"],"application/vnd.oasis.opendocument.image-template":["oti"],"application/vnd.oasis.opendocument.presentation":["odp"],"application/vnd.oasis.opendocument.presentation-template":["otp"],"application/vnd.oasis.opendocument.spreadsheet":["ods"],"application/vnd.oasis.opendocument.spreadsheet-template":["ots"],"application/vnd.oasis.opendocument.text":["odt"],"application/vnd.oasis.opendocument.text-master":["odm"],"application/vnd.oasis.opendocument.text-template":["ott"],"application/vnd.oasis.opendocument.text-web":["oth"],"application/vnd.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openblox.game+xml":["obgx"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openstreetmap.data+xml":["osm"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.rar":["rar"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"application/vnd.rig.cryptonote":["cryptonote"],"application/vnd.rim.cod":["cod"],"application/vnd.rn-realmedia":["rm"],"application/vnd.rn-realmedia-vbr":["rmvb"],"application/vnd.route66.link66+xml":["link66"],"application/vnd.sailingtracker.track":["st"],"application/vnd.seemail":["see"],"application/vnd.sema":["sema"],"application/vnd.semd":["semd"],"application/vnd.semf":["semf"],"application/vnd.shana.informed.formdata":["ifm"],"application/vnd.shana.informed.formtemplate":["itp"],"application/vnd.shana.informed.interchange":["iif"],"application/vnd.shana.informed.package":["ipk"],"application/vnd.simtech-mindmapper":["twd","twds"],"application/vnd.smaf":["mmf"],"application/vnd.smart.teacher":["teacher"],"application/vnd.software602.filler.form+xml":["fo"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"application/vnd.stardivision.calc":["sdc"],"application/vnd.stardivision.draw":["sda"],"application/vnd.stardivision.impress":["sdd"],"application/vnd.stardivision.math":["smf"],"application/vnd.stardivision.writer":["sdw","vor"],"application/vnd.stardivision.writer-global":["sgl"],"application/vnd.stepmania.package":["smzip"],"application/vnd.stepmania.stepchart":["sm"],"application/vnd.sun.wadl+xml":["wadl"],"application/vnd.sun.xml.calc":["sxc"],"application/vnd.sun.xml.calc.template":["stc"],"application/vnd.sun.xml.draw":["sxd"],"application/vnd.sun.xml.draw.template":["std"],"application/vnd.sun.xml.impress":["sxi"],"application/vnd.sun.xml.impress.template":["sti"],"application/vnd.sun.xml.math":["sxm"],"application/vnd.sun.xml.writer":["sxw"],"application/vnd.sun.xml.writer.global":["sxg"],"application/vnd.sun.xml.writer.template":["stw"],"application/vnd.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"application/vnd.symbian.install":["sis","sisx"],"application/vnd.syncml+xml":["xsm"],"application/vnd.syncml.dm+wbxml":["bdm"],"application/vnd.syncml.dm+xml":["xdm"],"application/vnd.syncml.dmddf+xml":["ddf"],"application/vnd.tao.intent-module-archive":["tao"],"application/vnd.tcpdump.pcap":["pcap","cap","dmp"],"application/vnd.tmobile-livetv":["tmo"],"application/vnd.trid.tpt":["tpt"],"application/vnd.triscape.mxs":["mxs"],"application/vnd.trueapp":["tra"],"application/vnd.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"application/vnd.yamaha.hv-dic":["hvd"],"application/vnd.yamaha.hv-script":["hvs"],"application/vnd.yamaha.hv-voice":["hvp"],"application/vnd.yamaha.openscoreformat":["osf"],"application/vnd.yamaha.openscoreformat.osfpvg+xml":["osfpvg"],"application/vnd.yamaha.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"application/x-apple-diskimage":["*dmg"],"application/x-arj":["arj"],"application/x-authorware-bin":["aab","x32","u32","vox"],"application/x-authorware-map":["aam"],"application/x-authorware-seg":["aas"],"application/x-bcpio":["bcpio"],"application/x-bdoc":["*bdoc"],"application/x-bittorrent":["torrent"],"application/x-blorb":["blb","blorb"],"application/x-bzip":["bz"],"application/x-bzip2":["bz2","boz"],"application/x-cbr":["cbr","cba","cbt","cbz","cb7"],"application/x-cdlink":["vcd"],"application/x-cfs-compressed":["cfs"],"application/x-chat":["chat"],"application/x-chess-pgn":["pgn"],"application/x-chrome-extension":["crx"],"application/x-cocoa":["cco"],"application/x-conference":["nsc"],"application/x-cpio":["cpio"],"application/x-csh":["csh"],"application/x-debian-package":["*deb","udeb"],"application/x-dgc-compressed":["dgc"],"application/x-director":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"],"application/x-doom":["wad"],"application/x-dtbncx+xml":["ncx"],"application/x-dtbook+xml":["dtb"],"application/x-dtbresource+xml":["res"],"application/x-dvi":["dvi"],"application/x-envoy":["evy"],"application/x-eva":["eva"],"application/x-font-bdf":["bdf"],"application/x-font-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"application/x-freearc":["arc"],"application/x-futuresplash":["spl"],"application/x-gca-compressed":["gca"],"application/x-glulx":["ulx"],"application/x-gnumeric":["gnumeric"],"application/x-gramps-xml":["gramps"],"application/x-gtar":["gtar"],"application/x-hdf":["hdf"],"application/x-httpd-php":["php"],"application/x-install-instructions":["install"],"application/x-iso9660-image":["*iso"],"application/x-iwork-keynote-sffkey":["*key"],"application/x-iwork-numbers-sffnumbers":["*numbers"],"application/x-iwork-pages-sffpages":["*pages"],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-keepass2":["kdbx"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"application/x-lzh-compressed":["lzh","lha"],"application/x-makeself":["run"],"application/x-mie":["mie"],"application/x-mobipocket-ebook":["prc","mobi"],"application/x-ms-application":["application"],"application/x-ms-shortcut":["lnk"],"application/x-ms-wmd":["wmd"],"application/x-ms-wmz":["wmz"],"application/x-ms-xbap":["xbap"],"application/x-msaccess":["mdb"],"application/x-msbinder":["obd"],"application/x-mscardfile":["crd"],"application/x-msclip":["clp"],"application/x-msdos-program":["*exe"],"application/x-msdownload":["*exe","*dll","com","bat","*msi"],"application/x-msmediaview":["mvb","m13","m14"],"application/x-msmetafile":["*wmf","*wmz","*emf","emz"],"application/x-msmoney":["mny"],"application/x-mspublisher":["pub"],"application/x-msschedule":["scd"],"application/x-msterminal":["trm"],"application/x-mswrite":["wri"],"application/x-netcdf":["nc","cdf"],"application/x-ns-proxy-autoconfig":["pac"],"application/x-nzb":["nzb"],"application/x-perl":["pl","pm"],"application/x-pilot":["*prc","*pdb"],"application/x-pkcs12":["p12","pfx"],"application/x-pkcs7-certificates":["p7b","spc"],"application/x-pkcs7-certreqresp":["p7r"],"application/x-rar-compressed":["*rar"],"application/x-redhat-package-manager":["rpm"],"application/x-research-info-systems":["ris"],"application/x-sea":["sea"],"application/x-sh":["sh"],"application/x-shar":["shar"],"application/x-shockwave-flash":["swf"],"application/x-silverlight-app":["xap"],"application/x-sql":["sql"],"application/x-stuffit":["sit"],"application/x-stuffitx":["sitx"],"application/x-subrip":["srt"],"application/x-sv4cpio":["sv4cpio"],"application/x-sv4crc":["sv4crc"],"application/x-t3vm-image":["t3"],"application/x-tads":["gam"],"application/x-tar":["tar"],"application/x-tcl":["tcl","tk"],"application/x-tex":["tex"],"application/x-tex-tfm":["tfm"],"application/x-texinfo":["texinfo","texi"],"application/x-tgif":["*obj"],"application/x-ustar":["ustar"],"application/x-virtualbox-hdd":["hdd"],"application/x-virtualbox-ova":["ova"],"application/x-virtualbox-ovf":["ovf"],"application/x-virtualbox-vbox":["vbox"],"application/x-virtualbox-vbox-extpack":["vbox-extpack"],"application/x-virtualbox-vdi":["vdi"],"application/x-virtualbox-vhd":["vhd"],"application/x-virtualbox-vmdk":["vmdk"],"application/x-wais-source":["src"],"application/x-web-app-manifest+json":["webapp"],"application/x-x509-ca-cert":["der","crt","pem"],"application/x-xfig":["fig"],"application/x-xliff+xml":["*xlf"],"application/x-xpinstall":["xpi"],"application/x-xz":["xz"],"application/x-zmachine":["z1","z2","z3","z4","z5","z6","z7","z8"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"audio/x-aac":["aac"],"audio/x-aiff":["aif","aiff","aifc"],"audio/x-caf":["caf"],"audio/x-flac":["flac"],"audio/x-m4a":["*m4a"],"audio/x-matroska":["mka"],"audio/x-mpegurl":["m3u"],"audio/x-ms-wax":["wax"],"audio/x-ms-wma":["wma"],"audio/x-pn-realaudio":["ram","ra"],"audio/x-pn-realaudio-plugin":["rmp"],"audio/x-realaudio":["*ra"],"audio/x-wav":["*wav"],"chemical/x-cdx":["cdx"],"chemical/x-cif":["cif"],"chemical/x-cmdf":["cmdf"],"chemical/x-cml":["cml"],"chemical/x-csml":["csml"],"chemical/x-xyz":["xyz"],"image/prs.btif":["btif"],"image/prs.pti":["pti"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.airzip.accelerator.azv":["azv"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":["*sub"],"image/vnd.dwg":["dwg"],"image/vnd.dxf":["dxf"],"image/vnd.fastbidsheet":["fbs"],"image/vnd.fpx":["fpx"],"image/vnd.fst":["fst"],"image/vnd.fujixerox.edmics-mmr":["mmr"],"image/vnd.fujixerox.edmics-rlc":["rlc"],"image/vnd.microsoft.icon":["ico"],"image/vnd.ms-dds":["dds"],"image/vnd.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"image/vnd.pco.b16":["b16"],"image/vnd.tencent.tap":["tap"],"image/vnd.valve.source.texture":["vtf"],"image/vnd.wap.wbmp":["wbmp"],"image/vnd.xiff":["xif"],"image/vnd.zbrush.pcx":["pcx"],"image/x-3ds":["3ds"],"image/x-cmu-raster":["ras"],"image/x-cmx":["cmx"],"image/x-freehand":["fh","fhc","fh4","fh5","fh7"],"image/x-icon":["*ico"],"image/x-jng":["jng"],"image/x-mrsid-image":["sid"],"image/x-ms-bmp":["*bmp"],"image/x-pcx":["*pcx"],"image/x-pict":["pic","pct"],"image/x-portable-anymap":["pnm"],"image/x-portable-bitmap":["pbm"],"image/x-portable-graymap":["pgm"],"image/x-portable-pixmap":["ppm"],"image/x-rgb":["rgb"],"image/x-tga":["tga"],"image/x-xbitmap":["xbm"],"image/x-xpixmap":["xpm"],"image/x-xwindowdump":["xwd"],"message/vnd.wfa.wsc":["wsc"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.opengex":["ogex"],"model/vnd.parasolid.transmit.binary":["x_b"],"model/vnd.parasolid.transmit.text":["x_t"],"model/vnd.sap.vds":["vds"],"model/vnd.usdz+zip":["usdz"],"model/vnd.valve.source.compiled-map":["bsp"],"model/vnd.vtu":["vtu"],"text/prs.lines.tag":["dsc"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"text/vnd.fly":["fly"],"text/vnd.fmi.flexstor":["flx"],"text/vnd.graphviz":["gv"],"text/vnd.in3d.3dml":["3dml"],"text/vnd.in3d.spot":["spot"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-org":["*org"],"text/x-pascal":["p","pas"],"text/x-processing":["pde"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-suse-ymp":["ymp"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"video/vnd.uvvu.mp4":["uvu","uvvu"],"video/vnd.vivo":["viv"],"video/x-f4v":["f4v"],"video/x-fli":["fli"],"video/x-flv":["flv"],"video/x-m4v":["m4v"],"video/x-matroska":["mkv","mk3d","mks"],"video/x-mng":["mng"],"video/x-ms-asf":["asf","asx"],"video/x-ms-vob":["vob"],"video/x-ms-wm":["wm"],"video/x-ms-wmv":["wmv"],"video/x-ms-wmx":["wmx"],"video/x-ms-wvx":["wvx"],"video/x-msvideo":["avi"],"video/x-sgi-movie":["movie"],"video/x-smv":["smv"],"x-conference/x-cooltalk":["ice"]}; /***/ }), /***/ 3725: /***/ ((module) => { module.exports = {"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["es","ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avif":["avif"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]}; /***/ }), /***/ 3772: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = minimatch minimatch.Minimatch = Minimatch var path = (function () { try { return __nccwpck_require__(6928) } catch (e) {}}()) || { sep: '/' } minimatch.sep = path.sep var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} var expand = __nccwpck_require__(4691) var plTypes = { '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, '?': { open: '(?:', close: ')?' }, '+': { open: '(?:', close: ')+' }, '*': { open: '(?:', close: ')*' }, '@': { open: '(?:', close: ')' } } // any single thing other than / // don't need to escape / when using new RegExp() var qmark = '[^/]' // * => any number of characters var star = qmark + '*?' // ** 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})($|\\\/)).)*?' // not a ^ or / followed by a dot, // followed by anything, any number of times. var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' // characters that need to be escaped in RegExp. var reSpecials = charSet('().*{}+?[]^$\\!') // "abc" -> { a:true, b:true, c:true } function charSet (s) { return s.split('').reduce(function (set, c) { set[c] = true return set }, {}) } // normalizes slashes. var slashSplit = /\/+/ minimatch.filter = filter function filter (pattern, options) { options = options || {} return function (p, i, list) { return minimatch(p, pattern, options) } } function ext (a, b) { b = b || {} var t = {} Object.keys(a).forEach(function (k) { t[k] = a[k] }) Object.keys(b).forEach(function (k) { t[k] = b[k] }) return t } minimatch.defaults = function (def) { if (!def || typeof def !== 'object' || !Object.keys(def).length) { return minimatch } var orig = minimatch var m = function minimatch (p, pattern, options) { return orig(p, pattern, ext(def, options)) } m.Minimatch = function Minimatch (pattern, options) { return new orig.Minimatch(pattern, ext(def, options)) } m.Minimatch.defaults = function defaults (options) { return orig.defaults(ext(def, options)).Minimatch } m.filter = function filter (pattern, options) { return orig.filter(pattern, ext(def, options)) } m.defaults = function defaults (options) { return orig.defaults(ext(def, options)) } m.makeRe = function makeRe (pattern, options) { return orig.makeRe(pattern, ext(def, options)) } m.braceExpand = function braceExpand (pattern, options) { return orig.braceExpand(pattern, ext(def, options)) } 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 } function minimatch (p, pattern, options) { assertValidPattern(pattern) if (!options) options = {} // shortcut: comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') { return false } return new Minimatch(pattern, options).match(p) } function Minimatch (pattern, options) { if (!(this instanceof Minimatch)) { return new Minimatch(pattern, options) } assertValidPattern(pattern) if (!options) options = {} pattern = pattern.trim() // windows support: need to use /, not \ if (!options.allowWindowsEscape && path.sep !== '/') { pattern = pattern.split(path.sep).join('/') } this.options = options this.set = [] this.pattern = pattern this.regexp = null this.negate = false this.comment = false this.empty = false this.partial = !!options.partial // make the set of regexps etc. this.make() } Minimatch.prototype.debug = function () {} Minimatch.prototype.make = make function make () { var pattern = this.pattern var options = this.options // empty patterns and comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') { this.comment = true return } if (!pattern) { this.empty = true return } // step 1: figure out negation, etc. this.parseNegate() // step 2: expand braces var set = this.globSet = this.braceExpand() if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) } this.debug(this.pattern, set) // 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) }) this.debug(this.pattern, set) // glob --> regexps set = set.map(function (s, si, set) { return s.map(this.parse, this) }, this) this.debug(this.pattern, set) // 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 } Minimatch.prototype.parseNegate = parseNegate function parseNegate () { var pattern = this.pattern var negate = false var options = this.options var negateOffset = 0 if (options.nonegate) return for (var i = 0, l = pattern.length ; i < l && pattern.charAt(i) === '!' ; i++) { negate = !negate negateOffset++ } if (negateOffset) this.pattern = pattern.substr(negateOffset) this.negate = negate } // 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) } Minimatch.prototype.braceExpand = braceExpand function braceExpand (pattern, options) { if (!options) { if (this instanceof Minimatch) { options = this.options } else { options = {} } } pattern = typeof pattern === 'undefined' ? this.pattern : pattern assertValidPattern(pattern) // Thanks to Yeting Li for // improving this regexp to avoid a ReDOS vulnerability. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { // shortcut. no need to expand. return [pattern] } return expand(pattern) } var MAX_PATTERN_LENGTH = 1024 * 64 var assertValidPattern = function (pattern) { if (typeof pattern !== 'string') { throw new TypeError('invalid pattern') } if (pattern.length > MAX_PATTERN_LENGTH) { throw new TypeError('pattern is too long') } } // 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 '' 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 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 } } 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) // skip over any that are escaped. if (escaping && reSpecials[c]) { re += '\\' + c escaping = false continue } switch (c) { /* istanbul ignore next */ case '/': { // completely not allowed, even escaped. // Should already be path-split by now. return false } case '\\': clearStateChar() escaping = true continue // 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) // 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 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 case '(': if (inClass) { re += '(' continue } if (!stateChar) { re += '\\(' continue } 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 case ')': if (inClass || !patternListStack.length) { re += '\\)' continue } 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 case '|': if (inClass || !patternListStack.length || escaping) { re += '\\|' escaping = false continue } clearStateChar() re += '|' continue // these are mostly the same in regexp and glob case '[': // swallow any state-tracking char before the [ clearStateChar() if (inClass) { re += '\\' + c continue } inClass = true classStart = i reClassStart = re.length re += c continue case ']': // a right bracket shall lose its special // meaning and represent itself in // a bracket expression if it occurs // first in the list. -- POSIX.2 2.8.3.2 if (i === classStart + 1 || !inClass) { re += '\\' + c escaping = false continue } // 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 } // finish up the class. hasMagic = true inClass = false re += c continue default: // swallow any state char that wasn't consumed clearStateChar() if (escaping) { // no need escaping = false } else if (reSpecials[c] && !(c === '^' && inClass)) { re += '\\' } re += c } // switch } // for // 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] } // 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 = '\\' } // 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 + '|' }) this.debug('tail=%j\n %s', tail, tail, pl, re) var t = pl.type === '*' ? star : pl.type === '?' ? qmark : '\\' + pl.type hasMagic = true re = re.slice(0, pl.reStart) + t + '\\(' + tail } // handle trailing things that only matter at the very end. clearStateChar() if (escaping) { // trailing \\ re += '\\\\' } // 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 } // 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] 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) nlLast += nlAfter // 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 var dollar = '' if (nlAfter === '' && isSub !== SUBPARSE) { dollar = '$' } var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast re = newRe } // if the re is not "" at this point, then we need to make sure // it doesn't match against an empty path part. // Otherwise a/* will match a/, which it should not. if (re !== '' && hasMagic) { re = '(?=.)' + re } if (addPatternStart) { re = patternStart + re } // parsing just a piece of a larger pattern. if (isSub === SUBPARSE) { return [re, hasMagic] } // 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 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('$.') } regExp._glob = pattern regExp._src = re return regExp } minimatch.makeRe = function (pattern, options) { return new Minimatch(pattern, options || {}).makeRe() } Minimatch.prototype.makeRe = makeRe function makeRe () { if (this.regexp || this.regexp === false) return this.regexp // at this point, this.set is a 2d array of partial // pattern strings, or "**". // // It's better to use .match(). This function shouldn't // be used, really, but it's pretty convenient sometimes, // when you just want to work with a regex. var set = this.set if (!set.length) { this.regexp = false return this.regexp } var options = this.options var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot var flags = options.nocase ? 'i' : '' 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 + ')$' // can match anything, as long as it's not this. if (this.negate) re = '^(?!' + re + ').*$' try { this.regexp = new RegExp(re, flags) } catch (ex) /* istanbul ignore next - should be impossible */ { this.regexp = false } return this.regexp } 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 === '' if (f === '/' && partial) return true var options = this.options // windows: need to use /, not \ if (path.sep !== '/') { f = f.split(path.sep).join('/') } // treat the test path as a set of pathparts. f = f.split(slashSplit) this.debug(this.pattern, 'split', f) // 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. var set = this.set this.debug(this.pattern, 'set', set) // Find the basename of the path by looking for the last non-empty segment var filename var i for (i = f.length - 1; i >= 0; i--) { filename = f[i] if (filename) break } 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 } } // didn't get any hits. this is success if it's a negative // pattern, failure otherwise. if (options.flipNegate) return false return this.negate } // set partial to true to test if, for example, // "/a/b" matches the start of "/*/b/*/d" // Partial means, if you run out of file before you run // out of pattern, then that's fine, as long as all // the parts match. Minimatch.prototype.matchOne = function (file, pattern, partial) { var options = this.options this.debug('matchOne', { 'this': this, file: file, pattern: pattern }) this.debug('matchOne', file.length, pattern.length) for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length ; (fi < fl) && (pi < pl) ; fi++, pi++) { this.debug('matchOne loop') var p = pattern[pi] var f = file[fi] this.debug(pattern, p, f) // should be impossible. // some invalid regexp stuff in the set. /* istanbul ignore if */ if (p === false) return false if (p === GLOBSTAR) { this.debug('GLOBSTAR', [pattern, p, f]) // "**" // a/**/b/**/c would match the following: // a/b/x/y/z/c // a/x/y/z/b/c // a/b/x/b/x/c // a/b/c // To do this, take the rest of the pattern after // the **, and see if it would match the file remainder. // If so, return success. // If not, the ** "swallows" a segment, and try again. // This is recursively awful. // // a/**/b/**/c matching a/b/x/y/z/c // - a matches a // - doublestar // - matchOne(b/x/y/z/c, b/**/c) // - b matches b // - doublestar // - matchOne(x/y/z/c, c) -> no // - matchOne(y/z/c, c) -> no // - matchOne(z/c, c) -> no // - matchOne(c, c) yes, hit var fr = fi var pr = pi + 1 if (pr === pl) { this.debug('** at the end') // a ** at the end will just swallow the rest. // We have found a match. // however, it will not swallow /.x, unless // options.dot is set. // . and .. are *never* matched by **, for explosively // exponential reasons. for (; fi < fl; fi++) { if (file[fi] === '.' || file[fi] === '..' || (!options.dot && file[fi].charAt(0) === '.')) return false } return true } // ok, let's see if we can swallow whatever we can. while (fr < fl) { var swallowee = file[fr] this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) // 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 } // ** swallows a segment, and continue. this.debug('globstar swallow a segment, and continue') fr++ } } // 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 } // 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) } if (!hit) return false } // 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/* // now either we fell off the end of the pattern, or we're done. if (fi === fl && pi === pl) { // ran out of pattern and filename at the same time. // an exact hit! return true } else if (fi === fl) { // ran out of file, but still had pattern left. // this is ok if we're doing the match as part of // a glob fs traversal. return partial } else /* istanbul ignore else */ if (pi === pl) { // ran out of pattern, still have file left. // this is only acceptable if we're on the very last // empty segment of a file with a trailing slash. // a/* should match a/b/ return (fi === fl - 1) && (file[fi] === '') } // should be unreachable. /* istanbul ignore next */ throw new Error('wtf?') } // replace stuff like \* with * function globUnescape (s) { return s.replace(/\\(.)/g, '$1') } function regExpEscape (s) { return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') } /***/ }), /***/ 744: /***/ ((module) => { /** * Helpers. */ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var w = d * 7; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} [options] * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ module.exports = function(val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse(val); } else if (type === 'number' && isFinite(val)) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( 'val is not a non-empty string or a valid number. val=' + JSON.stringify(val) ); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str); if (str.length > 100) { return; } var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'weeks': case 'week': case 'w': return n * w; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; default: return undefined; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return Math.round(ms / d) + 'd'; } if (msAbs >= h) { return Math.round(ms / h) + 'h'; } if (msAbs >= m) { return Math.round(ms / m) + 'm'; } if (msAbs >= s) { return Math.round(ms / s) + 's'; } return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return plural(ms, msAbs, d, 'day'); } if (msAbs >= h) { return plural(ms, msAbs, h, 'hour'); } if (msAbs >= m) { return plural(ms, msAbs, m, 'minute'); } if (msAbs >= s) { return plural(ms, msAbs, s, 'second'); } return ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, msAbs, n, name) { var isPlural = msAbs >= n * 1.5; return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); } /***/ }), /***/ 6705: /***/ ((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 Stream = _interopDefault(__nccwpck_require__(2203)); var http = _interopDefault(__nccwpck_require__(8611)); var Url = _interopDefault(__nccwpck_require__(7016)); var whatwgUrl = _interopDefault(__nccwpck_require__(5973)); var https = _interopDefault(__nccwpck_require__(5692)); var zlib = _interopDefault(__nccwpck_require__(3106)); // Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js // fix for "Readable" isn't a named export issue const Readable = Stream.Readable; const BUFFER = Symbol('buffer'); const TYPE = Symbol('type'); class Blob { constructor() { this[TYPE] = ''; const blobParts = arguments[0]; const options = arguments[1]; const buffers = []; let size = 0; 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; } } 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 }); /** * fetch-error.js * * FetchError interface for operational errors */ /** * 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); this.message = message; this.type = type; // when err.type is `system`, err.code contains system error code if (systemError) { this.code = this.errno = systemError.code; } // hide custom error implementation details from end-users Error.captureStackTrace(this, this.constructor); } FetchError.prototype = Object.create(Error.prototype); FetchError.prototype.constructor = FetchError; FetchError.prototype.name = 'FetchError'; let convert; try { convert = (__nccwpck_require__(2078).convert); } catch (e) {} const INTERNALS = Symbol('Body internals'); // fix an issue where "PassThrough" isn't a named export for node <10 const PassThrough = Stream.PassThrough; /** * 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; var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref$size = _ref.size; let size = _ref$size === undefined ? 0 : _ref$size; var _ref$timeout = _ref.timeout; let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; if (body == null) { // body is undefined or null body = null; } else if (isURLSearchParams(body)) { // body is a URLSearchParams body = Buffer.from(body.toString()); } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { // body is ArrayBuffer body = Buffer.from(body); } else if (ArrayBuffer.isView(body)) { // body is ArrayBufferView body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); } else if (body instanceof Stream) ; else { // none of the above // coerce to string then buffer body = Buffer.from(String(body)); } this[INTERNALS] = { body, disturbed: false, error: null }; this.size = size; this.timeout = timeout; if (body instanceof Stream) { body.on('error', function (err) { const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); _this[INTERNALS].error = error; }); } } Body.prototype = { get body() { return this[INTERNALS].body; }, get bodyUsed() { return this[INTERNALS].disturbed; }, /** * Decode response as ArrayBuffer * * @return Promise */ arrayBuffer() { return consumeBody.call(this).then(function (buf) { return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); }); }, /** * 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 }); }); }, /** * Decode response as json * * @return Promise */ json() { var _this2 = this; return consumeBody.call(this).then(function (buffer) { try { return JSON.parse(buffer.toString()); } catch (err) { return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); } }); }, /** * Decode response as text * * @return Promise */ text() { return consumeBody.call(this).then(function (buffer) { return buffer.toString(); }); }, /** * Decode response as buffer (non-spec api) * * @return Promise */ buffer() { return consumeBody.call(this); }, /** * Decode response as text, while automatically detecting the encoding and * trying to decode to UTF-8 (non-spec api) * * @return Promise */ textConverted() { var _this3 = this; return consumeBody.call(this).then(function (buffer) { return convertBody(buffer, _this3.headers); }); } }; // In browsers, all properties are enumerable. Object.defineProperties(Body.prototype, { body: { enumerable: true }, bodyUsed: { enumerable: true }, arrayBuffer: { enumerable: true }, blob: { enumerable: true }, json: { enumerable: true }, text: { enumerable: true } }); Body.mixIn = function (proto) { for (const name of Object.getOwnPropertyNames(Body.prototype)) { // istanbul ignore else: future proof if (!(name in proto)) { const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); Object.defineProperty(proto, name, desc); } } }; /** * 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; if (this[INTERNALS].disturbed) { return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); } this[INTERNALS].disturbed = true; if (this[INTERNALS].error) { return Body.Promise.reject(this[INTERNALS].error); } let body = this.body; // body is null if (body === null) { return Body.Promise.resolve(Buffer.alloc(0)); } // body is blob if (isBlob(body)) { body = body.stream(); } // body is buffer if (Buffer.isBuffer(body)) { return Body.Promise.resolve(body); } // istanbul ignore if: should never happen if (!(body instanceof Stream)) { return Body.Promise.resolve(Buffer.alloc(0)); } // body is stream // get ready to actually consume the body let accum = []; let accumBytes = 0; let abort = false; return new Body.Promise(function (resolve, reject) { let resTimeout; // 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); } // handle stream errors body.on('error', function (err) { if (err.name === 'AbortError') { // if the request was aborted, reject with this Error abort = true; reject(err); } else { // other errors, such as incorrect content-encoding reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); } }); body.on('data', function (chunk) { if (abort || chunk === null) { return; } 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; } accumBytes += chunk.length; accum.push(chunk); }); body.on('end', function () { if (abort) { return; } clearTimeout(resTimeout); 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)); } }); }); } /** * 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'); } const ct = headers.get('content-type'); let charset = 'utf-8'; let res, str; // header if (ct) { res = /charset=([^;]*)/i.exec(ct); } // no charset in content type, peek at response body for at most 1024 bytes str = buffer.slice(0, 1024).toString(); // html5 if (!res && str) { res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; this[MAP] = Object.create(null); if (init instanceof Headers) { const rawHeaders = init.raw(); const headerNames = Object.keys(rawHeaders); for (const headerName of headerNames) { for (const value of rawHeaders[headerName]) { this.append(headerName, value); } } return; } // 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'); } // 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)); } for (const pair of pairs) { if (pair.length !== 2) { throw new TypeError('Each header pair must be a name/value tuple'); } this.append(pair[0], pair[1]); } } else { // record for (const key of Object.keys(init)) { const value = init[key]; this.append(key, value); } } } else { throw new TypeError('Provided initializer must be an object'); } } /** * Return combined header value given name * * @param String name Header name * @return Mixed */ get(name) { name = `${name}`; validateName(name); const key = find(this[MAP], name); if (key === undefined) { return null; } return this[MAP][key].join(', '); } /** * Iterate over all headers * * @param Function callback Executed for each item with parameters (value, name, thisArg) * @param Boolean thisArg `this` context for callback function * @return Void */ forEach(callback) { let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; 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++; } } /** * 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]; } /** * 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]; } } /** * Return raw headers (non-spec api) * * @return Object */ raw() { return this[MAP]; } /** * Get an iterator on keys. * * @return Iterator */ keys() { return createHeadersIterator(this, 'key'); } /** * Get an iterator on values. * * @return Iterator */ values() { return createHeadersIterator(this, 'value'); } /** * Get an iterator on entries. * * This is the default iterator of the Headers object. * * @return Iterator */ [Symbol.iterator]() { return createHeadersIterator(this, 'key+value'); } } Headers.prototype.entries = Headers.prototype[Symbol.iterator]; 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'; const keys = Object.keys(headers[MAP]).sort(); return keys.map(kind === 'key' ? function (k) { return k.toLowerCase(); } : kind === 'value' ? function (k) { return headers[MAP][k].join(', '); } : function (k) { return [k.toLowerCase(), headers[MAP][k].join(', ')]; }); } const INTERNAL = Symbol('internal'); function createHeadersIterator(target, kind) { const iterator = Object.create(HeadersIteratorPrototype); iterator[INTERNAL] = { target, kind, index: 0 }; return iterator; } const HeadersIteratorPrototype = Object.setPrototypeOf({ next() { // istanbul ignore if if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { throw new TypeError('Value of `this` is not a HeadersIterator'); } var _INTERNAL = this[INTERNAL]; const target = _INTERNAL.target, kind = _INTERNAL.kind, index = _INTERNAL.index; 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]()))); Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { value: 'HeadersIterator', writable: false, enumerable: false, configurable: true }); /** * Export the Headers object in a form that Node.js can consume. * * @param Headers headers * @return Object */ function exportNodeCompatibleHeaders(headers) { const obj = Object.assign({ __proto__: null }, headers[MAP]); // 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]; } return obj; } /** * 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; /** * Response class * * @param Stream body Readable stream * @param Object opts Response options * @return Void */ class Response { constructor() { let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 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 }; } get url() { return this[INTERNALS$1].url || ''; } get status() { return this[INTERNALS$1].status; } /** * Convenience property representing if the request ended normally */ get ok() { return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; } get redirected() { return this[INTERNALS$1].counter > 0; } get statusText() { return this[INTERNALS$1].statusText; } get headers() { return this[INTERNALS$1].headers; } /** * Clone this response * * @return Response */ clone() { return new Response(clone(this), { url: this.url, status: this.status, statusText: this.statusText, headers: this.headers, ok: this.ok, redirected: this.redirected }); } } Body.mixIn(Response.prototype); Object.defineProperties(Response.prototype, { url: { enumerable: true }, status: { enumerable: true }, ok: { enumerable: true }, redirected: { enumerable: true }, statusText: { enumerable: true }, headers: { enumerable: true }, clone: { enumerable: true } }); Object.defineProperty(Response.prototype, Symbol.toStringTag, { value: 'Response', writable: false, enumerable: false, configurable: true }); const INTERNALS$2 = Symbol('Request internals'); const URL = Url.URL || whatwgUrl.URL; // fix an issue where "format", "parse" aren't a named export for node <10 const parse_url = Url.parse; const format_url = Url.format; /** * Wrapper around `new URL` to handle arbitrary URLs * * @param {string} urlStr * @return {void} */ function parseURL(urlStr) { /* Check whether the URL is absolute or not Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 */ if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { urlStr = new URL(urlStr).toString(); } // Fallback to old implementation for arbitrary URLs return parse_url(urlStr); } const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; /** * Check if a value is an instance of Request. * * @param Mixed input * @return Boolean */ function isRequest(input) { return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; } function isAbortSignal(signal) { const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); return !!(proto && proto.constructor.name === 'AbortSignal'); } /** * Request class * * @param Mixed input Url or Request instance * @param Object init Custom options * @return Void */ class Request { constructor(input) { let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; let parsedURL; // normalize input if (!isRequest(input)) { if (input && input.href) { // in order to support Node.js' Url objects; though WHATWG's URL objects // will fall into this branch also (since their `toString()` will return // `href` property anyway) parsedURL = parseURL(input.href); } else { // coerce input to a string before attempting to parse parsedURL = parseURL(`${input}`); } input = {}; } else { parsedURL = parseURL(input.url); } let method = init.method || input.method || 'GET'; method = method.toUpperCase(); if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { throw new TypeError('Request with GET/HEAD method cannot have body'); } let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; Body.call(this, inputBody, { timeout: init.timeout || input.timeout || 0, size: init.size || input.size || 0 }); const headers = new Headers(init.headers || input.headers || {}); if (inputBody != null && !headers.has('Content-Type')) { const contentType = extractContentType(inputBody); if (contentType) { headers.append('Content-Type', contentType); } } let signal = isRequest(input) ? input.signal : null; if ('signal' in init) signal = init.signal; if (signal != null && !isAbortSignal(signal)) { throw new TypeError('Expected signal to be an instanceof AbortSignal'); } this[INTERNALS$2] = { method, redirect: init.redirect || input.redirect || 'follow', headers, parsedURL, signal }; // node-fetch-only options this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; this.counter = init.counter || input.counter || 0; this.agent = init.agent || input.agent; } get method() { return this[INTERNALS$2].method; } get url() { return format_url(this[INTERNALS$2].parsedURL); } get headers() { return this[INTERNALS$2].headers; } get redirect() { return this[INTERNALS$2].redirect; } get signal() { return this[INTERNALS$2].signal; } /** * Clone this request * * @return Request */ clone() { return new Request(this); } } Body.mixIn(Request.prototype); Object.defineProperty(Request.prototype, Symbol.toStringTag, { value: 'Request', writable: false, enumerable: false, configurable: true }); Object.defineProperties(Request.prototype, { method: { enumerable: true }, url: { enumerable: true }, headers: { enumerable: true }, redirect: { enumerable: true }, clone: { enumerable: true }, signal: { enumerable: true } }); /** * Convert a Request to Node.js http request options. * * @param Request A Request instance * @return Object The options object to be passed to http.request */ function getNodeRequestOptions(request) { const parsedURL = request[INTERNALS$2].parsedURL; const headers = new Headers(request[INTERNALS$2].headers); // fetch step 1.3 if (!headers.has('Accept')) { headers.set('Accept', '*/*'); } // Basic fetch if (!parsedURL.protocol || !parsedURL.hostname) { throw new TypeError('Only absolute URLs are supported'); } if (!/^https?:$/.test(parsedURL.protocol)) { throw new TypeError('Only HTTP(S) protocols are supported'); } if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); } // HTTP-network-or-cache fetch steps 2.4-2.7 let contentLengthValue = null; if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { contentLengthValue = '0'; } if (request.body != null) { const totalBytes = getTotalBytes(request); if (typeof totalBytes === 'number') { contentLengthValue = String(totalBytes); } } if (contentLengthValue) { headers.set('Content-Length', contentLengthValue); } // HTTP-network-or-cache fetch step 2.11 if (!headers.has('User-Agent')) { headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); } // HTTP-network-or-cache fetch step 2.15 if (request.compress && !headers.has('Accept-Encoding')) { headers.set('Accept-Encoding', 'gzip,deflate'); } let agent = request.agent; if (typeof agent === 'function') { agent = agent(parsedURL); } // HTTP-network fetch step 4.2 // chunked encoding is handled by Node.js return Object.assign({}, parsedURL, { method: request.method, headers: exportNodeCompatibleHeaders(headers), agent }); } /** * abort-error.js * * AbortError interface for cancelled requests */ /** * Create AbortError instance * * @param String message Error message for human * @return AbortError */ function AbortError(message) { Error.call(this, message); this.type = 'aborted'; this.message = message; // hide custom error implementation details from end-users Error.captureStackTrace(this, this.constructor); } AbortError.prototype = Object.create(Error.prototype); AbortError.prototype.constructor = AbortError; AbortError.prototype.name = 'AbortError'; const URL$1 = Url.URL || whatwgUrl.URL; // fix an issue where "PassThrough", "resolve" aren't a named export for node <10 const PassThrough$1 = Stream.PassThrough; const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { const orig = new URL$1(original).hostname; const dest = new URL$1(destination).hostname; return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); }; /** * isSameProtocol reports whether the two provided URLs use the same protocol. * * Both domains must already be in canonical form. * @param {string|URL} original * @param {string|URL} destination */ const isSameProtocol = function isSameProtocol(destination, original) { const orig = new URL$1(original).protocol; const dest = new URL$1(destination).protocol; return orig === dest; }; /** * Fetch function * * @param Mixed url Absolute url or Request instance * @param Object opts Fetch options * @return Promise */ function fetch(url, opts) { // allow custom promise if (!fetch.Promise) { throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); } Body.Promise = fetch.Promise; // wrap http.request into fetch return new fetch.Promise(function (resolve, reject) { // build request object const request = new Request(url, opts); const options = getNodeRequestOptions(request); const send = (options.protocol === 'https:' ? https : http).request; const signal = request.signal; let response = null; const abort = function abort() { let error = new AbortError('The user aborted a request.'); reject(error); if (request.body && request.body instanceof Stream.Readable) { destroyStream(request.body, error); } if (!response || !response.body) return; response.body.emit('error', error); }; if (signal && signal.aborted) { abort(); return; } const abortAndFinalize = function abortAndFinalize() { abort(); finalize(); }; // send request const req = send(options); let reqTimeout; if (signal) { signal.addEventListener('abort', abortAndFinalize); } function finalize() { req.abort(); if (signal) signal.removeEventListener('abort', abortAndFinalize); clearTimeout(reqTimeout); } if (request.timeout) { req.once('socket', function (socket) { reqTimeout = setTimeout(function () { reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); finalize(); }, request.timeout); }); } req.on('error', function (err) { reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); if (response && response.body) { destroyStream(response.body, err); } finalize(); }); fixResponseChunkedTransferBadEnding(req, function (err) { if (signal && signal.aborted) { return; } if (response && response.body) { destroyStream(response.body, err); } }); /* c8 ignore next 18 */ if (parseInt(process.version.substring(1)) < 14) { // Before Node.js 14, pipeline() does not fully support async iterators and does not always // properly handle when the socket close/end events are out of order. req.on('socket', function (s) { s.addListener('close', function (hadError) { // if a data listener is still present we didn't end cleanly const hasDataListener = s.listenerCount('data') > 0; // if end happened before close but the socket didn't emit an error, do it now if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { const err = new Error('Premature close'); err.code = 'ERR_STREAM_PREMATURE_CLOSE'; response.body.emit('error', err); } }); }); } req.on('response', function (res) { clearTimeout(reqTimeout); const headers = createHeadersLenient(res.headers); // HTTP fetch step 5 if (fetch.isRedirect(res.statusCode)) { // HTTP fetch step 5.2 const location = headers.get('Location'); // HTTP fetch step 5.3 let locationURL = null; try { locationURL = location === null ? null : new URL$1(location, request.url).toString(); } catch (err) { // error here can only be invalid URL in Location: header // do not throw when options.redirect == manual // let the user extract the errorneous redirect URL if (request.redirect !== 'manual') { reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); finalize(); return; } } // HTTP fetch step 5.5 switch (request.redirect) { case 'error': reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); finalize(); return; case 'manual': // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. if (locationURL !== null) { // handle corrupted header try { headers.set('Location', locationURL); } catch (err) { // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request reject(err); } } break; case 'follow': // HTTP-redirect fetch step 2 if (locationURL === null) { break; } // HTTP-redirect fetch step 5 if (request.counter >= request.follow) { reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); finalize(); return; } // HTTP-redirect fetch step 6 (counter increment) // Create a new Request object. const requestOpts = { headers: new Headers(request.headers), follow: request.follow, counter: request.counter + 1, agent: request.agent, compress: request.compress, method: request.method, body: request.body, signal: request.signal, timeout: request.timeout, size: request.size }; if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { requestOpts.headers.delete(name); } } // HTTP-redirect fetch step 9 if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); finalize(); return; } // 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'); } // HTTP-redirect fetch step 15 resolve(fetch(new Request(locationURL, requestOpts))); finalize(); return; } } // prepare response res.once('end', function () { if (signal) signal.removeEventListener('abort', abortAndFinalize); }); let body = res.pipe(new PassThrough$1()); 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 // 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; } // 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 }; // for gzip if (codings == 'gzip' || codings == 'x-gzip') { body = body.pipe(zlib.createGunzip(zlibOptions)); response = new Response(body, response_options); resolve(response); return; } // for deflate if (codings == 'deflate' || codings == 'x-deflate') { // handle the infamous raw deflate response from old servers // a hack for old IIS and Apache servers const raw = res.pipe(new PassThrough$1()); raw.once('data', function (chunk) { // see http://stackoverflow.com/questions/37519828 if ((chunk[0] & 0x0F) === 0x08) { body = body.pipe(zlib.createInflate()); } else { body = body.pipe(zlib.createInflateRaw()); } response = new Response(body, response_options); resolve(response); }); raw.on('end', function () { // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. if (!response) { response = new Response(body, response_options); resolve(response); } }); return; } // for br if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { body = body.pipe(zlib.createBrotliDecompress()); response = new Response(body, response_options); resolve(response); return; } // otherwise, use response as-is response = new Response(body, response_options); resolve(response); }); writeToStream(req, request); }); } function fixResponseChunkedTransferBadEnding(request, errorCallback) { let socket; request.on('socket', function (s) { socket = s; }); request.on('response', function (response) { const headers = response.headers; if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { response.once('close', function (hadError) { // tests for socket presence, as in some situations the // the 'socket' event is not triggered for the request // (happens in deno), avoids `TypeError` // if a data listener is still present we didn't end cleanly const hasDataListener = socket && socket.listenerCount('data') > 0; if (hasDataListener && !hadError) { const err = new Error('Premature close'); err.code = 'ERR_STREAM_PREMATURE_CLOSE'; errorCallback(err); } }); } }); } function destroyStream(stream, err) { if (stream.destroy) { stream.destroy(err); } else { // node < 8 stream.emit('error', err); stream.end(); } } /** * Redirect code matching * * @param Number code Status code * @return Boolean */ fetch.isRedirect = function (code) { return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; }; // expose Promise fetch.Promise = global.Promise; module.exports = exports = fetch; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = exports; exports.Headers = Headers; exports.Request = Request; exports.Response = Response; exports.FetchError = FetchError; exports.AbortError = AbortError; /***/ }), /***/ 1733: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var punycode = __nccwpck_require__(4876); var mappingTable = __nccwpck_require__(7963); var PROCESSING_OPTIONS = { TRANSITIONAL: 0, NONTRANSITIONAL: 1 }; function normalize(str) { // fix bug in v8 return str.split('\u0000').map(function (s) { return s.normalize('NFC'); }).join('\u0000'); } function findStatus(val) { var start = 0; var end = mappingTable.length - 1; while (start <= end) { var mid = Math.floor((start + end) / 2); var target = mappingTable[mid]; if (target[0][0] <= val && target[0][1] >= val) { return target; } else if (target[0][0] > val) { end = mid - 1; } else { start = mid + 1; } } return null; } var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; function countSymbols(string) { return string // replace every surrogate pair with a BMP symbol .replace(regexAstralSymbols, '_') // then get the length .length; } function mapChars(domain_name, useSTD3, processing_option) { var hasError = false; var processed = ""; var len = countSymbols(domain_name); for (var i = 0; i < len; ++i) { var codePoint = domain_name.codePointAt(i); var status = findStatus(codePoint); switch (status[1]) { case "disallowed": hasError = true; processed += String.fromCodePoint(codePoint); break; case "ignored": break; case "mapped": processed += String.fromCodePoint.apply(String, status[2]); break; case "deviation": if (processing_option === PROCESSING_OPTIONS.TRANSITIONAL) { processed += String.fromCodePoint.apply(String, status[2]); } else { processed += String.fromCodePoint(codePoint); } break; case "valid": processed += String.fromCodePoint(codePoint); break; case "disallowed_STD3_mapped": if (useSTD3) { hasError = true; processed += String.fromCodePoint(codePoint); } else { processed += String.fromCodePoint.apply(String, status[2]); } break; case "disallowed_STD3_valid": if (useSTD3) { hasError = true; } processed += String.fromCodePoint(codePoint); break; } } return { string: processed, error: hasError }; } var combiningMarksRegex = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E4-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2D]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC7F-\uDC82\uDCB0-\uDCBA\uDD00-\uDD02\uDD27-\uDD34\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDE2C-\uDE37\uDEDF-\uDEEA\uDF01-\uDF03\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDCB0-\uDCC3\uDDAF-\uDDB5\uDDB8-\uDDC0\uDE30-\uDE40\uDEAB-\uDEB7]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD82F[\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD83A[\uDCD0-\uDCD6]|\uDB40[\uDD00-\uDDEF]/; function validateLabel(label, processing_option) { if (label.substr(0, 4) === "xn--") { label = punycode.toUnicode(label); processing_option = PROCESSING_OPTIONS.NONTRANSITIONAL; } var error = false; if (normalize(label) !== label || (label[3] === "-" && label[4] === "-") || label[0] === "-" || label[label.length - 1] === "-" || label.indexOf(".") !== -1 || label.search(combiningMarksRegex) === 0) { error = true; } var len = countSymbols(label); for (var i = 0; i < len; ++i) { var status = findStatus(label.codePointAt(i)); if ((processing === PROCESSING_OPTIONS.TRANSITIONAL && status[1] !== "valid") || (processing === PROCESSING_OPTIONS.NONTRANSITIONAL && status[1] !== "valid" && status[1] !== "deviation")) { error = true; break; } } return { label: label, error: error }; } function processing(domain_name, useSTD3, processing_option) { var result = mapChars(domain_name, useSTD3, processing_option); result.string = normalize(result.string); var labels = result.string.split("."); for (var i = 0; i < labels.length; ++i) { try { var validation = validateLabel(labels[i]); labels[i] = validation.label; result.error = result.error || validation.error; } catch(e) { result.error = true; } } return { string: labels.join("."), error: result.error }; } module.exports.toASCII = function(domain_name, useSTD3, processing_option, verifyDnsLength) { var result = processing(domain_name, useSTD3, processing_option); var labels = result.string.split("."); labels = labels.map(function(l) { try { return punycode.toASCII(l); } catch(e) { result.error = true; return l; } }); if (verifyDnsLength) { var total = labels.slice(0, labels.length - 1).join(".").length; if (total.length > 253 || total.length === 0) { result.error = true; } for (var i=0; i < labels.length; ++i) { if (labels.length > 63 || labels.length === 0) { result.error = true; break; } } } if (result.error) return null; return labels.join("."); }; module.exports.toUnicode = function(domain_name, useSTD3) { var result = processing(domain_name, useSTD3, PROCESSING_OPTIONS.NONTRANSITIONAL); return { domain: result.string, error: result.error }; }; module.exports.PROCESSING_OPTIONS = PROCESSING_OPTIONS; /***/ }), /***/ 1364: /***/ ((module) => { "use strict"; var conversions = {}; module.exports = conversions; function sign(x) { return x < 0 ? -1 : 1; } function evenRound(x) { // Round x to the nearest integer, choosing the even integer if it lies halfway between two. if ((x % 1) === 0.5 && (x & 1) === 0) { // [even number].5; round down (i.e. floor) return Math.floor(x); } else { return Math.round(x); } } function createNumberConversion(bitLength, typeOpts) { if (!typeOpts.unsigned) { --bitLength; } const lowerBound = typeOpts.unsigned ? 0 : -Math.pow(2, bitLength); const upperBound = Math.pow(2, bitLength) - 1; const moduloVal = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength) : Math.pow(2, bitLength); const moduloBound = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength - 1) : Math.pow(2, bitLength - 1); return function(V, opts) { if (!opts) opts = {}; let x = +V; if (opts.enforceRange) { if (!Number.isFinite(x)) { throw new TypeError("Argument is not a finite number"); } x = sign(x) * Math.floor(Math.abs(x)); if (x < lowerBound || x > upperBound) { throw new TypeError("Argument is not in byte range"); } return x; } if (!isNaN(x) && opts.clamp) { x = evenRound(x); if (x < lowerBound) x = lowerBound; if (x > upperBound) x = upperBound; return x; } if (!Number.isFinite(x) || x === 0) { return 0; } x = sign(x) * Math.floor(Math.abs(x)); x = x % moduloVal; if (!typeOpts.unsigned && x >= moduloBound) { return x - moduloVal; } else if (typeOpts.unsigned) { if (x < 0) { x += moduloVal; } else if (x === -0) { // don't return negative zero return 0; } } return x; } } conversions["void"] = function () { return undefined; }; conversions["boolean"] = function (val) { return !!val; }; conversions["byte"] = createNumberConversion(8, { unsigned: false }); conversions["octet"] = createNumberConversion(8, { unsigned: true }); conversions["short"] = createNumberConversion(16, { unsigned: false }); conversions["unsigned short"] = createNumberConversion(16, { unsigned: true }); conversions["long"] = createNumberConversion(32, { unsigned: false }); conversions["unsigned long"] = createNumberConversion(32, { unsigned: true }); conversions["long long"] = createNumberConversion(32, { unsigned: false, moduloBitLength: 64 }); conversions["unsigned long long"] = createNumberConversion(32, { unsigned: true, moduloBitLength: 64 }); conversions["double"] = function (V) { const x = +V; if (!Number.isFinite(x)) { throw new TypeError("Argument is not a finite floating-point value"); } return x; }; conversions["unrestricted double"] = function (V) { const x = +V; if (isNaN(x)) { throw new TypeError("Argument is NaN"); } return x; }; // not quite valid, but good enough for JS conversions["float"] = conversions["double"]; conversions["unrestricted float"] = conversions["unrestricted double"]; conversions["DOMString"] = function (V, opts) { if (!opts) opts = {}; if (opts.treatNullAsEmptyString && V === null) { return ""; } return String(V); }; conversions["ByteString"] = function (V, opts) { const x = String(V); let c = undefined; for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) { if (c > 255) { throw new TypeError("Argument is not a valid bytestring"); } } return x; }; conversions["USVString"] = function (V) { const S = String(V); const n = S.length; const U = []; for (let i = 0; i < n; ++i) { const c = S.charCodeAt(i); if (c < 0xD800 || c > 0xDFFF) { U.push(String.fromCodePoint(c)); } else if (0xDC00 <= c && c <= 0xDFFF) { U.push(String.fromCodePoint(0xFFFD)); } else { if (i === n - 1) { U.push(String.fromCodePoint(0xFFFD)); } else { const d = S.charCodeAt(i + 1); if (0xDC00 <= d && d <= 0xDFFF) { const a = c & 0x3FF; const b = d & 0x3FF; U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b)); ++i; } else { U.push(String.fromCodePoint(0xFFFD)); } } } } return U.join(''); }; conversions["Date"] = function (V, opts) { if (!(V instanceof Date)) { throw new TypeError("Argument is not a Date object"); } if (isNaN(V)) { return undefined; } return V; }; conversions["RegExp"] = function (V, opts) { if (!(V instanceof RegExp)) { V = new RegExp(V); } return V; }; /***/ }), /***/ 291: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; const usm = __nccwpck_require__(7704); exports.implementation = class URLImpl { constructor(constructorArgs) { const url = constructorArgs[0]; const base = constructorArgs[1]; let parsedBase = null; if (base !== undefined) { parsedBase = usm.basicURLParse(base); if (parsedBase === "failure") { throw new TypeError("Invalid base URL"); } } const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase }); if (parsedURL === "failure") { throw new TypeError("Invalid URL"); } this._url = parsedURL; // TODO: query stuff } get href() { return usm.serializeURL(this._url); } set href(v) { const parsedURL = usm.basicURLParse(v); if (parsedURL === "failure") { throw new TypeError("Invalid URL"); } this._url = parsedURL; } get origin() { return usm.serializeURLOrigin(this._url); } get protocol() { return this._url.scheme + ":"; } set protocol(v) { usm.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" }); } get username() { return this._url.username; } set username(v) { if (usm.cannotHaveAUsernamePasswordPort(this._url)) { return; } usm.setTheUsername(this._url, v); } get password() { return this._url.password; } set password(v) { if (usm.cannotHaveAUsernamePasswordPort(this._url)) { return; } usm.setThePassword(this._url, v); } get host() { const url = this._url; if (url.host === null) { return ""; } if (url.port === null) { return usm.serializeHost(url.host); } return usm.serializeHost(url.host) + ":" + usm.serializeInteger(url.port); } set host(v) { if (this._url.cannotBeABaseURL) { return; } usm.basicURLParse(v, { url: this._url, stateOverride: "host" }); } get hostname() { if (this._url.host === null) { return ""; } return usm.serializeHost(this._url.host); } set hostname(v) { if (this._url.cannotBeABaseURL) { return; } usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" }); } get port() { if (this._url.port === null) { return ""; } return usm.serializeInteger(this._url.port); } set port(v) { if (usm.cannotHaveAUsernamePasswordPort(this._url)) { return; } if (v === "") { this._url.port = null; } else { usm.basicURLParse(v, { url: this._url, stateOverride: "port" }); } } get pathname() { if (this._url.cannotBeABaseURL) { return this._url.path[0]; } if (this._url.path.length === 0) { return ""; } return "/" + this._url.path.join("/"); } set pathname(v) { if (this._url.cannotBeABaseURL) { return; } this._url.path = []; usm.basicURLParse(v, { url: this._url, stateOverride: "path start" }); } get search() { if (this._url.query === null || this._url.query === "") { return ""; } return "?" + this._url.query; } set search(v) { // TODO: query stuff const url = this._url; if (v === "") { url.query = null; return; } const input = v[0] === "?" ? v.substring(1) : v; url.query = ""; usm.basicURLParse(input, { url, stateOverride: "query" }); } get hash() { if (this._url.fragment === null || this._url.fragment === "") { return ""; } return "#" + this._url.fragment; } set hash(v) { if (v === "") { this._url.fragment = null; return; } const input = v[0] === "#" ? v.substring(1) : v; this._url.fragment = ""; usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" }); } toJSON() { return this.href; } }; /***/ }), /***/ 1860: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const conversions = __nccwpck_require__(1364); const utils = __nccwpck_require__(6880); const Impl = __nccwpck_require__(291); const impl = utils.implSymbol; function URL(url) { if (!this || this[impl] || !(this instanceof URL)) { throw new TypeError("Failed to construct 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function."); } if (arguments.length < 1) { throw new TypeError("Failed to construct 'URL': 1 argument required, but only " + arguments.length + " present."); } const args = []; for (let i = 0; i < arguments.length && i < 2; ++i) { args[i] = arguments[i]; } args[0] = conversions["USVString"](args[0]); if (args[1] !== undefined) { args[1] = conversions["USVString"](args[1]); } module.exports.setup(this, args); } URL.prototype.toJSON = function toJSON() { if (!this || !module.exports.is(this)) { throw new TypeError("Illegal invocation"); } const args = []; for (let i = 0; i < arguments.length && i < 0; ++i) { args[i] = arguments[i]; } return this[impl].toJSON.apply(this[impl], args); }; Object.defineProperty(URL.prototype, "href", { get() { return this[impl].href; }, set(V) { V = conversions["USVString"](V); this[impl].href = V; }, enumerable: true, configurable: true }); URL.prototype.toString = function () { if (!this || !module.exports.is(this)) { throw new TypeError("Illegal invocation"); } return this.href; }; Object.defineProperty(URL.prototype, "origin", { get() { return this[impl].origin; }, enumerable: true, configurable: true }); Object.defineProperty(URL.prototype, "protocol", { get() { return this[impl].protocol; }, set(V) { V = conversions["USVString"](V); this[impl].protocol = V; }, enumerable: true, configurable: true }); Object.defineProperty(URL.prototype, "username", { get() { return this[impl].username; }, set(V) { V = conversions["USVString"](V); this[impl].username = V; }, enumerable: true, configurable: true }); Object.defineProperty(URL.prototype, "password", { get() { return this[impl].password; }, set(V) { V = conversions["USVString"](V); this[impl].password = V; }, enumerable: true, configurable: true }); Object.defineProperty(URL.prototype, "host", { get() { return this[impl].host; }, set(V) { V = conversions["USVString"](V); this[impl].host = V; }, enumerable: true, configurable: true }); Object.defineProperty(URL.prototype, "hostname", { get() { return this[impl].hostname; }, set(V) { V = conversions["USVString"](V); this[impl].hostname = V; }, enumerable: true, configurable: true }); Object.defineProperty(URL.prototype, "port", { get() { return this[impl].port; }, set(V) { V = conversions["USVString"](V); this[impl].port = V; }, enumerable: true, configurable: true }); Object.defineProperty(URL.prototype, "pathname", { get() { return this[impl].pathname; }, set(V) { V = conversions["USVString"](V); this[impl].pathname = V; }, enumerable: true, configurable: true }); Object.defineProperty(URL.prototype, "search", { get() { return this[impl].search; }, set(V) { V = conversions["USVString"](V); this[impl].search = V; }, enumerable: true, configurable: true }); Object.defineProperty(URL.prototype, "hash", { get() { return this[impl].hash; }, set(V) { V = conversions["USVString"](V); this[impl].hash = V; }, enumerable: true, configurable: true }); module.exports = { is(obj) { return !!obj && obj[impl] instanceof Impl.implementation; }, create(constructorArgs, privateData) { let obj = Object.create(URL.prototype); this.setup(obj, constructorArgs, privateData); return obj; }, setup(obj, constructorArgs, privateData) { if (!privateData) privateData = {}; privateData.wrapper = obj; obj[impl] = new Impl.implementation(constructorArgs, privateData); obj[impl][utils.wrapperSymbol] = obj; }, interface: URL, expose: { Window: { URL: URL }, Worker: { URL: URL } } }; /***/ }), /***/ 5973: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; exports.URL = __nccwpck_require__(1860)["interface"]; exports.serializeURL = __nccwpck_require__(7704).serializeURL; exports.serializeURLOrigin = __nccwpck_require__(7704).serializeURLOrigin; exports.basicURLParse = __nccwpck_require__(7704).basicURLParse; exports.setTheUsername = __nccwpck_require__(7704).setTheUsername; exports.setThePassword = __nccwpck_require__(7704).setThePassword; exports.serializeHost = __nccwpck_require__(7704).serializeHost; exports.serializeInteger = __nccwpck_require__(7704).serializeInteger; exports.parseURL = __nccwpck_require__(7704).parseURL; /***/ }), /***/ 7704: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const punycode = __nccwpck_require__(4876); const tr46 = __nccwpck_require__(1733); const specialSchemes = { ftp: 21, file: null, gopher: 70, http: 80, https: 443, ws: 80, wss: 443 }; const failure = Symbol("failure"); function countSymbols(str) { return punycode.ucs2.decode(str).length; } function at(input, idx) { const c = input[idx]; return isNaN(c) ? undefined : String.fromCodePoint(c); } function isASCIIDigit(c) { return c >= 0x30 && c <= 0x39; } function isASCIIAlpha(c) { return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A); } function isASCIIAlphanumeric(c) { return isASCIIAlpha(c) || isASCIIDigit(c); } function isASCIIHex(c) { return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66); } function isSingleDot(buffer) { return buffer === "." || buffer.toLowerCase() === "%2e"; } function isDoubleDot(buffer) { buffer = buffer.toLowerCase(); return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; } function isWindowsDriveLetterCodePoints(cp1, cp2) { return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124); } function isWindowsDriveLetterString(string) { return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); } function isNormalizedWindowsDriveLetterString(string) { return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; } function containsForbiddenHostCodePoint(string) { return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1; } function containsForbiddenHostCodePointExcludingPercent(string) { return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1; } function isSpecialScheme(scheme) { return specialSchemes[scheme] !== undefined; } function isSpecial(url) { return isSpecialScheme(url.scheme); } function defaultPort(scheme) { return specialSchemes[scheme]; } function percentEncode(c) { let hex = c.toString(16).toUpperCase(); if (hex.length === 1) { hex = "0" + hex; } return "%" + hex; } function utf8PercentEncode(c) { const buf = new Buffer(c); let str = ""; for (let i = 0; i < buf.length; ++i) { str += percentEncode(buf[i]); } return str; } function utf8PercentDecode(str) { const input = new Buffer(str); const output = []; for (let i = 0; i < input.length; ++i) { if (input[i] !== 37) { output.push(input[i]); } else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) { output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16)); i += 2; } else { output.push(input[i]); } } return new Buffer(output).toString(); } function isC0ControlPercentEncode(c) { return c <= 0x1F || c > 0x7E; } const extraPathPercentEncodeSet = new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]); function isPathPercentEncode(c) { return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c); } const extraUserinfoPercentEncodeSet = new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]); function isUserinfoPercentEncode(c) { return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); } function percentEncodeChar(c, encodeSetPredicate) { const cStr = String.fromCodePoint(c); if (encodeSetPredicate(c)) { return utf8PercentEncode(cStr); } return cStr; } function parseIPv4Number(input) { let R = 10; if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { input = input.substring(2); R = 16; } else if (input.length >= 2 && input.charAt(0) === "0") { input = input.substring(1); R = 8; } if (input === "") { return 0; } const regex = R === 10 ? /[^0-9]/ : (R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/); if (regex.test(input)) { return failure; } return parseInt(input, R); } function parseIPv4(input) { const parts = input.split("."); if (parts[parts.length - 1] === "") { if (parts.length > 1) { parts.pop(); } } if (parts.length > 4) { return input; } const numbers = []; for (const part of parts) { if (part === "") { return input; } const n = parseIPv4Number(part); if (n === failure) { return input; } numbers.push(n); } for (let i = 0; i < numbers.length - 1; ++i) { if (numbers[i] > 255) { return failure; } } if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) { return failure; } let ipv4 = numbers.pop(); let counter = 0; for (const n of numbers) { ipv4 += n * Math.pow(256, 3 - counter); ++counter; } return ipv4; } function serializeIPv4(address) { let output = ""; let n = address; for (let i = 1; i <= 4; ++i) { output = String(n % 256) + output; if (i !== 4) { output = "." + output; } n = Math.floor(n / 256); } return output; } function parseIPv6(input) { const address = [0, 0, 0, 0, 0, 0, 0, 0]; let pieceIndex = 0; let compress = null; let pointer = 0; input = punycode.ucs2.decode(input); if (input[pointer] === 58) { if (input[pointer + 1] !== 58) { return failure; } pointer += 2; ++pieceIndex; compress = pieceIndex; } while (pointer < input.length) { if (pieceIndex === 8) { return failure; } if (input[pointer] === 58) { if (compress !== null) { return failure; } ++pointer; ++pieceIndex; compress = pieceIndex; continue; } let value = 0; let length = 0; while (length < 4 && isASCIIHex(input[pointer])) { value = value * 0x10 + parseInt(at(input, pointer), 16); ++pointer; ++length; } if (input[pointer] === 46) { if (length === 0) { return failure; } pointer -= length; if (pieceIndex > 6) { return failure; } let numbersSeen = 0; while (input[pointer] !== undefined) { let ipv4Piece = null; if (numbersSeen > 0) { if (input[pointer] === 46 && numbersSeen < 4) { ++pointer; } else { return failure; } } if (!isASCIIDigit(input[pointer])) { return failure; } while (isASCIIDigit(input[pointer])) { const number = parseInt(at(input, pointer)); if (ipv4Piece === null) { ipv4Piece = number; } else if (ipv4Piece === 0) { return failure; } else { ipv4Piece = ipv4Piece * 10 + number; } if (ipv4Piece > 255) { return failure; } ++pointer; } address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece; ++numbersSeen; if (numbersSeen === 2 || numbersSeen === 4) { ++pieceIndex; } } if (numbersSeen !== 4) { return failure; } break; } else if (input[pointer] === 58) { ++pointer; if (input[pointer] === undefined) { return failure; } } else if (input[pointer] !== undefined) { return failure; } address[pieceIndex] = value; ++pieceIndex; } if (compress !== null) { let swaps = pieceIndex - compress; pieceIndex = 7; while (pieceIndex !== 0 && swaps > 0) { const temp = address[compress + swaps - 1]; address[compress + swaps - 1] = address[pieceIndex]; address[pieceIndex] = temp; --pieceIndex; --swaps; } } else if (compress === null && pieceIndex !== 8) { return failure; } return address; } function serializeIPv6(address) { let output = ""; const seqResult = findLongestZeroSequence(address); const compress = seqResult.idx; let ignore0 = false; for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { if (ignore0 && address[pieceIndex] === 0) { continue; } else if (ignore0) { ignore0 = false; } if (compress === pieceIndex) { const separator = pieceIndex === 0 ? "::" : ":"; output += separator; ignore0 = true; continue; } output += address[pieceIndex].toString(16); if (pieceIndex !== 7) { output += ":"; } } return output; } function parseHost(input, isSpecialArg) { if (input[0] === "[") { if (input[input.length - 1] !== "]") { return failure; } return parseIPv6(input.substring(1, input.length - 1)); } if (!isSpecialArg) { return parseOpaqueHost(input); } const domain = utf8PercentDecode(input); const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false); if (asciiDomain === null) { return failure; } if (containsForbiddenHostCodePoint(asciiDomain)) { return failure; } const ipv4Host = parseIPv4(asciiDomain); if (typeof ipv4Host === "number" || ipv4Host === failure) { return ipv4Host; } return asciiDomain; } function parseOpaqueHost(input) { if (containsForbiddenHostCodePointExcludingPercent(input)) { return failure; } let output = ""; const decoded = punycode.ucs2.decode(input); for (let i = 0; i < decoded.length; ++i) { output += percentEncodeChar(decoded[i], isC0ControlPercentEncode); } return output; } function findLongestZeroSequence(arr) { let maxIdx = null; let maxLen = 1; // only find elements > 1 let currStart = null; let currLen = 0; for (let i = 0; i < arr.length; ++i) { if (arr[i] !== 0) { if (currLen > maxLen) { maxIdx = currStart; maxLen = currLen; } currStart = null; currLen = 0; } else { if (currStart === null) { currStart = i; } ++currLen; } } // if trailing zeros if (currLen > maxLen) { maxIdx = currStart; maxLen = currLen; } return { idx: maxIdx, len: maxLen }; } function serializeHost(host) { if (typeof host === "number") { return serializeIPv4(host); } // IPv6 serializer if (host instanceof Array) { return "[" + serializeIPv6(host) + "]"; } return host; } function trimControlChars(url) { return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, ""); } function trimTabAndNewline(url) { return url.replace(/\u0009|\u000A|\u000D/g, ""); } function shortenPath(url) { const path = url.path; if (path.length === 0) { return; } if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { return; } path.pop(); } function includesCredentials(url) { return url.username !== "" || url.password !== ""; } function cannotHaveAUsernamePasswordPort(url) { return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file"; } function isNormalizedWindowsDriveLetter(string) { return /^[A-Za-z]:$/.test(string); } function URLStateMachine(input, base, encodingOverride, url, stateOverride) { this.pointer = 0; this.input = input; this.base = base || null; this.encodingOverride = encodingOverride || "utf-8"; this.stateOverride = stateOverride; this.url = url; this.failure = false; this.parseError = false; if (!this.url) { this.url = { scheme: "", username: "", password: "", host: null, port: null, path: [], query: null, fragment: null, cannotBeABaseURL: false }; const res = trimControlChars(this.input); if (res !== this.input) { this.parseError = true; } this.input = res; } const res = trimTabAndNewline(this.input); if (res !== this.input) { this.parseError = true; } this.input = res; this.state = stateOverride || "scheme start"; this.buffer = ""; this.atFlag = false; this.arrFlag = false; this.passwordTokenSeenFlag = false; this.input = punycode.ucs2.decode(this.input); for (; this.pointer <= this.input.length; ++this.pointer) { const c = this.input[this.pointer]; const cStr = isNaN(c) ? undefined : String.fromCodePoint(c); // exec state machine const ret = this["parse " + this.state](c, cStr); if (!ret) { break; // terminate algorithm } else if (ret === failure) { this.failure = true; break; } } } URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { if (isASCIIAlpha(c)) { this.buffer += cStr.toLowerCase(); this.state = "scheme"; } else if (!this.stateOverride) { this.state = "no scheme"; --this.pointer; } else { this.parseError = true; return failure; } return true; }; URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) { this.buffer += cStr.toLowerCase(); } else if (c === 58) { if (this.stateOverride) { if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { return false; } if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { return false; } if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { return false; } if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) { return false; } } this.url.scheme = this.buffer; this.buffer = ""; if (this.stateOverride) { return false; } if (this.url.scheme === "file") { if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) { this.parseError = true; } this.state = "file"; } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { this.state = "special relative or authority"; } else if (isSpecial(this.url)) { this.state = "special authority slashes"; } else if (this.input[this.pointer + 1] === 47) { this.state = "path or authority"; ++this.pointer; } else { this.url.cannotBeABaseURL = true; this.url.path.push(""); this.state = "cannot-be-a-base-URL path"; } } else if (!this.stateOverride) { this.buffer = ""; this.state = "no scheme"; this.pointer = -1; } else { this.parseError = true; return failure; } return true; }; URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) { return failure; } else if (this.base.cannotBeABaseURL && c === 35) { this.url.scheme = this.base.scheme; this.url.path = this.base.path.slice(); this.url.query = this.base.query; this.url.fragment = ""; this.url.cannotBeABaseURL = true; this.state = "fragment"; } else if (this.base.scheme === "file") { this.state = "file"; --this.pointer; } else { this.state = "relative"; --this.pointer; } return true; }; URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { if (c === 47 && this.input[this.pointer + 1] === 47) { this.state = "special authority ignore slashes"; ++this.pointer; } else { this.parseError = true; this.state = "relative"; --this.pointer; } return true; }; URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { if (c === 47) { this.state = "authority"; } else { this.state = "path"; --this.pointer; } return true; }; URLStateMachine.prototype["parse relative"] = function parseRelative(c) { this.url.scheme = this.base.scheme; if (isNaN(c)) { this.url.username = this.base.username; this.url.password = this.base.password; this.url.host = this.base.host; this.url.port = this.base.port; this.url.path = this.base.path.slice(); this.url.query = this.base.query; } else if (c === 47) { this.state = "relative slash"; } else if (c === 63) { this.url.username = this.base.username; this.url.password = this.base.password; this.url.host = this.base.host; this.url.port = this.base.port; this.url.path = this.base.path.slice(); this.url.query = ""; this.state = "query"; } else if (c === 35) { this.url.username = this.base.username; this.url.password = this.base.password; this.url.host = this.base.host; this.url.port = this.base.port; this.url.path = this.base.path.slice(); this.url.query = this.base.query; this.url.fragment = ""; this.state = "fragment"; } else if (isSpecial(this.url) && c === 92) { this.parseError = true; this.state = "relative slash"; } else { this.url.username = this.base.username; this.url.password = this.base.password; this.url.host = this.base.host; this.url.port = this.base.port; this.url.path = this.base.path.slice(0, this.base.path.length - 1); this.state = "path"; --this.pointer; } return true; }; URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { if (isSpecial(this.url) && (c === 47 || c === 92)) { if (c === 92) { this.parseError = true; } this.state = "special authority ignore slashes"; } else if (c === 47) { this.state = "authority"; } else { this.url.username = this.base.username; this.url.password = this.base.password; this.url.host = this.base.host; this.url.port = this.base.port; this.state = "path"; --this.pointer; } return true; }; URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { if (c === 47 && this.input[this.pointer + 1] === 47) { this.state = "special authority ignore slashes"; ++this.pointer; } else { this.parseError = true; this.state = "special authority ignore slashes"; --this.pointer; } return true; }; URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { if (c !== 47 && c !== 92) { this.state = "authority"; --this.pointer; } else { this.parseError = true; } return true; }; URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { if (c === 64) { this.parseError = true; if (this.atFlag) { this.buffer = "%40" + this.buffer; } this.atFlag = true; // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars const len = countSymbols(this.buffer); for (let pointer = 0; pointer < len; ++pointer) { const codePoint = this.buffer.codePointAt(pointer); if (codePoint === 58 && !this.passwordTokenSeenFlag) { this.passwordTokenSeenFlag = true; continue; } const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode); if (this.passwordTokenSeenFlag) { this.url.password += encodedCodePoints; } else { this.url.username += encodedCodePoints; } } this.buffer = ""; } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || (isSpecial(this.url) && c === 92)) { if (this.atFlag && this.buffer === "") { this.parseError = true; return failure; } this.pointer -= countSymbols(this.buffer) + 1; this.buffer = ""; this.state = "host"; } else { this.buffer += cStr; } return true; }; URLStateMachine.prototype["parse hostname"] = URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { if (this.stateOverride && this.url.scheme === "file") { --this.pointer; this.state = "file host"; } else if (c === 58 && !this.arrFlag) { if (this.buffer === "") { this.parseError = true; return failure; } const host = parseHost(this.buffer, isSpecial(this.url)); if (host === failure) { return failure; } this.url.host = host; this.buffer = ""; this.state = "port"; if (this.stateOverride === "hostname") { return false; } } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || (isSpecial(this.url) && c === 92)) { --this.pointer; if (isSpecial(this.url) && this.buffer === "") { this.parseError = true; return failure; } else if (this.stateOverride && this.buffer === "" && (includesCredentials(this.url) || this.url.port !== null)) { this.parseError = true; return false; } const host = parseHost(this.buffer, isSpecial(this.url)); if (host === failure) { return failure; } this.url.host = host; this.buffer = ""; this.state = "path start"; if (this.stateOverride) { return false; } } else { if (c === 91) { this.arrFlag = true; } else if (c === 93) { this.arrFlag = false; } this.buffer += cStr; } return true; }; URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { if (isASCIIDigit(c)) { this.buffer += cStr; } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || (isSpecial(this.url) && c === 92) || this.stateOverride) { if (this.buffer !== "") { const port = parseInt(this.buffer); if (port > Math.pow(2, 16) - 1) { this.parseError = true; return failure; } this.url.port = port === defaultPort(this.url.scheme) ? null : port; this.buffer = ""; } if (this.stateOverride) { return false; } this.state = "path start"; --this.pointer; } else { this.parseError = true; return failure; } return true; }; const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]); URLStateMachine.prototype["parse file"] = function parseFile(c) { this.url.scheme = "file"; if (c === 47 || c === 92) { if (c === 92) { this.parseError = true; } this.state = "file slash"; } else if (this.base !== null && this.base.scheme === "file") { if (isNaN(c)) { this.url.host = this.base.host; this.url.path = this.base.path.slice(); this.url.query = this.base.query; } else if (c === 63) { this.url.host = this.base.host; this.url.path = this.base.path.slice(); this.url.query = ""; this.state = "query"; } else if (c === 35) { this.url.host = this.base.host; this.url.path = this.base.path.slice(); this.url.query = this.base.query; this.url.fragment = ""; this.state = "fragment"; } else { if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points !isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) || (this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points !fileOtherwiseCodePoints.has(this.input[this.pointer + 2]))) { this.url.host = this.base.host; this.url.path = this.base.path.slice(); shortenPath(this.url); } else { this.parseError = true; } this.state = "path"; --this.pointer; } } else { this.state = "path"; --this.pointer; } return true; }; URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { if (c === 47 || c === 92) { if (c === 92) { this.parseError = true; } this.state = "file host"; } else { if (this.base !== null && this.base.scheme === "file") { if (isNormalizedWindowsDriveLetterString(this.base.path[0])) { this.url.path.push(this.base.path[0]); } else { this.url.host = this.base.host; } } this.state = "path"; --this.pointer; } return true; }; URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) { --this.pointer; if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { this.parseError = true; this.state = "path"; } else if (this.buffer === "") { this.url.host = ""; if (this.stateOverride) { return false; } this.state = "path start"; } else { let host = parseHost(this.buffer, isSpecial(this.url)); if (host === failure) { return failure; } if (host === "localhost") { host = ""; } this.url.host = host; if (this.stateOverride) { return false; } this.buffer = ""; this.state = "path start"; } } else { this.buffer += cStr; } return true; }; URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { if (isSpecial(this.url)) { if (c === 92) { this.parseError = true; } this.state = "path"; if (c !== 47 && c !== 92) { --this.pointer; } } else if (!this.stateOverride && c === 63) { this.url.query = ""; this.state = "query"; } else if (!this.stateOverride && c === 35) { this.url.fragment = ""; this.state = "fragment"; } else if (c !== undefined) { this.state = "path"; if (c !== 47) { --this.pointer; } } return true; }; URLStateMachine.prototype["parse path"] = function parsePath(c) { if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) || (!this.stateOverride && (c === 63 || c === 35))) { if (isSpecial(this.url) && c === 92) { this.parseError = true; } if (isDoubleDot(this.buffer)) { shortenPath(this.url); if (c !== 47 && !(isSpecial(this.url) && c === 92)) { this.url.path.push(""); } } else if (isSingleDot(this.buffer) && c !== 47 && !(isSpecial(this.url) && c === 92)) { this.url.path.push(""); } else if (!isSingleDot(this.buffer)) { if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { if (this.url.host !== "" && this.url.host !== null) { this.parseError = true; this.url.host = ""; } this.buffer = this.buffer[0] + ":"; } this.url.path.push(this.buffer); } this.buffer = ""; if (this.url.scheme === "file" && (c === undefined || c === 63 || c === 35)) { while (this.url.path.length > 1 && this.url.path[0] === "") { this.parseError = true; this.url.path.shift(); } } if (c === 63) { this.url.query = ""; this.state = "query"; } if (c === 35) { this.url.fragment = ""; this.state = "fragment"; } } else { // TODO: If c is not a URL code point and not "%", parse error. if (c === 37 && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) { this.parseError = true; } this.buffer += percentEncodeChar(c, isPathPercentEncode); } return true; }; URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) { if (c === 63) { this.url.query = ""; this.state = "query"; } else if (c === 35) { this.url.fragment = ""; this.state = "fragment"; } else { // TODO: Add: not a URL code point if (!isNaN(c) && c !== 37) { this.parseError = true; } if (c === 37 && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) { this.parseError = true; } if (!isNaN(c)) { this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode); } } return true; }; URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { if (isNaN(c) || (!this.stateOverride && c === 35)) { if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { this.encodingOverride = "utf-8"; } const buffer = new Buffer(this.buffer); // TODO: Use encoding override instead for (let i = 0; i < buffer.length; ++i) { if (buffer[i] < 0x21 || buffer[i] > 0x7E || buffer[i] === 0x22 || buffer[i] === 0x23 || buffer[i] === 0x3C || buffer[i] === 0x3E) { this.url.query += percentEncode(buffer[i]); } else { this.url.query += String.fromCodePoint(buffer[i]); } } this.buffer = ""; if (c === 35) { this.url.fragment = ""; this.state = "fragment"; } } else { // TODO: If c is not a URL code point and not "%", parse error. if (c === 37 && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) { this.parseError = true; } this.buffer += cStr; } return true; }; URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { if (isNaN(c)) { // do nothing } else if (c === 0x0) { this.parseError = true; } else { // TODO: If c is not a URL code point and not "%", parse error. if (c === 37 && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) { this.parseError = true; } this.url.fragment += percentEncodeChar(c, isC0ControlPercentEncode); } return true; }; function serializeURL(url, excludeFragment) { let output = url.scheme + ":"; if (url.host !== null) { output += "//"; if (url.username !== "" || url.password !== "") { output += url.username; if (url.password !== "") { output += ":" + url.password; } output += "@"; } output += serializeHost(url.host); if (url.port !== null) { output += ":" + url.port; } } else if (url.host === null && url.scheme === "file") { output += "//"; } if (url.cannotBeABaseURL) { output += url.path[0]; } else { for (const string of url.path) { output += "/" + string; } } if (url.query !== null) { output += "?" + url.query; } if (!excludeFragment && url.fragment !== null) { output += "#" + url.fragment; } return output; } function serializeOrigin(tuple) { let result = tuple.scheme + "://"; result += serializeHost(tuple.host); if (tuple.port !== null) { result += ":" + tuple.port; } return result; } module.exports.serializeURL = serializeURL; module.exports.serializeURLOrigin = function (url) { // https://url.spec.whatwg.org/#concept-url-origin switch (url.scheme) { case "blob": try { return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0])); } catch (e) { // serializing an opaque origin returns "null" return "null"; } case "ftp": case "gopher": case "http": case "https": case "ws": case "wss": return serializeOrigin({ scheme: url.scheme, host: url.host, port: url.port }); case "file": // spec says "exercise to the reader", chrome says "file://" return "file://"; default: // serializing an opaque origin returns "null" return "null"; } }; module.exports.basicURLParse = function (input, options) { if (options === undefined) { options = {}; } const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); if (usm.failure) { return "failure"; } return usm.url; }; module.exports.setTheUsername = function (url, username) { url.username = ""; const decoded = punycode.ucs2.decode(username); for (let i = 0; i < decoded.length; ++i) { url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode); } }; module.exports.setThePassword = function (url, password) { url.password = ""; const decoded = punycode.ucs2.decode(password); for (let i = 0; i < decoded.length; ++i) { url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode); } }; module.exports.serializeHost = serializeHost; module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; module.exports.serializeInteger = function (integer) { return String(integer); }; module.exports.parseURL = function (input, options) { if (options === undefined) { options = {}; } // We don't handle blobs, so this just delegates: return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); }; /***/ }), /***/ 6880: /***/ ((module) => { "use strict"; module.exports.mixin = function mixin(target, source) { const keys = Object.getOwnPropertyNames(source); for (let i = 0; i < keys.length; ++i) { Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i])); } }; module.exports.wrapperSymbol = Symbol("wrapper"); module.exports.implSymbol = Symbol("impl"); module.exports.wrapperForImpl = function (impl) { return impl[module.exports.wrapperSymbol]; }; module.exports.implForWrapper = function (wrapper) { return wrapper[module.exports.implSymbol]; }; /***/ }), /***/ 5560: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var wrappy = __nccwpck_require__(8264) module.exports = wrappy(once) module.exports.strict = wrappy(onceStrict) once.proto = once(function () { Object.defineProperty(Function.prototype, 'once', { value: function () { return once(this) }, configurable: true }) Object.defineProperty(Function.prototype, 'onceStrict', { value: function () { return onceStrict(this) }, configurable: true }) }) function once (fn) { var f = function () { if (f.called) return f.value f.called = true return f.value = fn.apply(this, arguments) } f.called = false return f } function onceStrict (fn) { var f = function () { if (f.called) throw new Error(f.onceError) f.called = true return f.value = fn.apply(this, arguments) } var name = fn.name || 'Function wrapped with `once`' f.onceError = name + " shouldn't be called more than once" f.called = false return f } /***/ }), /***/ 5500: /***/ ((module) => { "use strict"; const codes = {}; function createErrorType(code, message, Base) { if (!Base) { Base = Error } function getMessage (arg1, arg2, arg3) { if (typeof message === 'string') { return message } else { return message(arg1, arg2, arg3) } } class NodeError extends Base { constructor (arg1, arg2, arg3) { super(getMessage(arg1, arg2, arg3)); } } NodeError.prototype.name = Base.name; NodeError.prototype.code = code; codes[code] = NodeError; } // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js function oneOf(expected, thing) { if (Array.isArray(expected)) { const len = expected.length; expected = expected.map((i) => String(i)); if (len > 2) { return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + expected[len - 1]; } else if (len === 2) { return `one of ${thing} ${expected[0]} or ${expected[1]}`; } else { return `of ${thing} ${expected[0]}`; } } else { return `of ${thing} ${String(expected)}`; } } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith function startsWith(str, search, pos) { return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith function endsWith(str, search, this_len) { if (this_len === undefined || this_len > str.length) { this_len = str.length; } return str.substring(this_len - search.length, this_len) === search; } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes function includes(str, search, start) { if (typeof start !== 'number') { start = 0; } if (start + search.length > str.length) { return false; } else { return str.indexOf(search, start) !== -1; } } createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { return 'The value "' + value + '" is invalid for option "' + name + '"' }, TypeError); createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { // determiner: 'must be' or 'must not be' let determiner; if (typeof expected === 'string' && startsWith(expected, 'not ')) { determiner = 'must not be'; expected = expected.replace(/^not /, ''); } else { determiner = 'must be'; } let msg; if (endsWith(name, ' argument')) { // For cases like 'first argument' msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; } else { const type = includes(name, '.') ? 'property' : 'argument'; msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; } msg += `. Received type ${typeof actual}`; return msg; }, TypeError); createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { return 'The ' + name + ' method is not implemented' }); createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); createErrorType('ERR_STREAM_DESTROYED', function (name) { return 'Cannot call ' + name + ' after a stream was destroyed'; }); createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { return 'Unknown encoding: ' + arg }, TypeError); createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); module.exports.F = codes; /***/ }), /***/ 2063: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototypal inheritance, this class // prototypally inherits from Readable, and then parasitically from // Writable. /**/ var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) keys.push(key); return keys; }; /**/ module.exports = Duplex; var Readable = __nccwpck_require__(9274); var Writable = __nccwpck_require__(8797); __nccwpck_require__(9598)(Duplex, Readable); { // Allow the keys array to be GC'ed. var keys = objectKeys(Writable.prototype); for (var v = 0; v < keys.length; v++) { var method = keys[v]; if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } } function Duplex(options) { if (!(this instanceof Duplex)) return new Duplex(options); Readable.call(this, options); Writable.call(this, options); this.allowHalfOpen = true; if (options) { if (options.readable === false) this.readable = false; if (options.writable === false) this.writable = false; if (options.allowHalfOpen === false) { this.allowHalfOpen = false; this.once('end', onend); } } } Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState.highWaterMark; } }); Object.defineProperty(Duplex.prototype, 'writableBuffer', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState && this._writableState.getBuffer(); } }); Object.defineProperty(Duplex.prototype, 'writableLength', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState.length; } }); // the no-half-open enforcer function onend() { // If the writable side ended, then we're ok. if (this._writableState.ended) return; // no more data can be written. // But allow more writes to happen in this tick. process.nextTick(onEndNT, this); } function onEndNT(self) { self.end(); } Object.defineProperty(Duplex.prototype, 'destroyed', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { if (this._readableState === undefined || this._writableState === undefined) { return false; } return this._readableState.destroyed && this._writableState.destroyed; }, set: function set(value) { // we ignore the value if the stream // has not been initialized yet if (this._readableState === undefined || this._writableState === undefined) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; this._writableState.destroyed = value; } }); /***/ }), /***/ 5283: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. module.exports = PassThrough; var Transform = __nccwpck_require__(2337); __nccwpck_require__(9598)(PassThrough, Transform); function PassThrough(options) { if (!(this instanceof PassThrough)) return new PassThrough(options); Transform.call(this, options); } PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); }; /***/ }), /***/ 9274: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. module.exports = Readable; /**/ var Duplex; /**/ Readable.ReadableState = ReadableState; /**/ var EE = (__nccwpck_require__(4434).EventEmitter); var EElistenerCount = function EElistenerCount(emitter, type) { return emitter.listeners(type).length; }; /**/ /**/ var Stream = __nccwpck_require__(3283); /**/ var Buffer = (__nccwpck_require__(181).Buffer); var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } /**/ var debugUtil = __nccwpck_require__(9023); var debug; if (debugUtil && debugUtil.debuglog) { debug = debugUtil.debuglog('stream'); } else { debug = function debug() {}; } /**/ var BufferList = __nccwpck_require__(7336); var destroyImpl = __nccwpck_require__(5089); var _require = __nccwpck_require__(4874), getHighWaterMark = _require.getHighWaterMark; var _require$codes = (__nccwpck_require__(5500)/* .codes */ .F), ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. var StringDecoder; var createReadableStreamAsyncIterator; var from; __nccwpck_require__(9598)(Readable, Stream); var errorOrDestroy = destroyImpl.errorOrDestroy; var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; function prependListener(emitter, event, fn) { // Sadly this is not cacheable as some libraries bundle their own // event emitter implementation with them. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any // userland ones. NEVER DO THIS. This is here only because this code needs // to continue to work with older versions of Node.js that do not include // the prependListener() method. The goal is to eventually remove this hack. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; } function ReadableState(options, stream, isDuplex) { Duplex = Duplex || __nccwpck_require__(2063); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to // make all the buffer merging and length checks go away this.objectMode = !!options.objectMode; if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer // Note: 0 is a valid value, means "don't call _read preemptively ever" this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the // linked list can remove elements from the beginning faster than // array.shift() this.buffer = new BufferList(); this.length = 0; this.pipes = null; this.pipesCount = 0; this.flowing = null; this.ended = false; this.endEmitted = false; this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted // immediately, or on a later tick. We set this to true at first, because // any actions that shouldn't happen until "later" should generally also // not happen before the first read call. this.sync = true; // whenever we return null, then we set a flag to say // that we're awaiting a 'readable' event emission. this.needReadable = false; this.emittedReadable = false; this.readableListening = false; this.resumeScheduled = false; this.paused = true; // Should close be emitted on destroy. Defaults to true. this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') this.autoDestroy = !!options.autoDestroy; // has it been destroyed this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled this.readingMore = false; this.decoder = null; this.encoding = null; if (options.encoding) { if (!StringDecoder) StringDecoder = (__nccwpck_require__(634)/* .StringDecoder */ .I); this.decoder = new StringDecoder(options.encoding); this.encoding = options.encoding; } } function Readable(options) { Duplex = Duplex || __nccwpck_require__(2063); if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside // the ReadableState constructor, at least with V8 6.5 var isDuplex = this instanceof Duplex; this._readableState = new ReadableState(options, this, isDuplex); // legacy this.readable = true; if (options) { if (typeof options.read === 'function') this._read = options.read; if (typeof options.destroy === 'function') this._destroy = options.destroy; } Stream.call(this); } Object.defineProperty(Readable.prototype, 'destroyed', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { if (this._readableState === undefined) { return false; } return this._readableState.destroyed; }, set: function set(value) { // we ignore the value if the stream // has not been initialized yet if (!this._readableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; } }); Readable.prototype.destroy = destroyImpl.destroy; Readable.prototype._undestroy = destroyImpl.undestroy; Readable.prototype._destroy = function (err, cb) { cb(err); }; // Manually shove something into the read() buffer. // This returns true if the highWaterMark has not been hit yet, // similar to how Writable.write() returns true if you should // write() some more. Readable.prototype.push = function (chunk, encoding) { var state = this._readableState; var skipChunkCheck; if (!state.objectMode) { if (typeof chunk === 'string') { encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { chunk = Buffer.from(chunk, encoding); encoding = ''; } skipChunkCheck = true; } } else { skipChunkCheck = true; } return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); }; // Unshift should *always* be something directly out of read() Readable.prototype.unshift = function (chunk) { return readableAddChunk(this, chunk, null, true, false); }; function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { debug('readableAddChunk', chunk); var state = stream._readableState; if (chunk === null) { state.reading = false; onEofChunk(stream, state); } else { var er; if (!skipChunkCheck) er = chunkInvalid(state, chunk); if (er) { errorOrDestroy(stream, er); } else if (state.objectMode || chunk && chunk.length > 0) { if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { chunk = _uint8ArrayToBuffer(chunk); } if (addToFront) { if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); } else if (state.ended) { errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); } else if (state.destroyed) { return false; } else { state.reading = false; if (state.decoder && !encoding) { chunk = state.decoder.write(chunk); if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); } else { addChunk(stream, state, chunk, false); } } } else if (!addToFront) { state.reading = false; maybeReadMore(stream, state); } } // We can push more data if we are below the highWaterMark. // Also, if we have no data yet, we can stand some more bytes. // This is to work around cases where hwm=0, such as the repl. return !state.ended && (state.length < state.highWaterMark || state.length === 0); } function addChunk(stream, state, chunk, addToFront) { if (state.flowing && state.length === 0 && !state.sync) { state.awaitDrain = 0; stream.emit('data', chunk); } else { // update the buffer info. state.length += state.objectMode ? 1 : chunk.length; if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); if (state.needReadable) emitReadable(stream); } maybeReadMore(stream, state); } function chunkInvalid(state, chunk) { var er; if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); } return er; } Readable.prototype.isPaused = function () { return this._readableState.flowing === false; }; // backwards compatibility. Readable.prototype.setEncoding = function (enc) { if (!StringDecoder) StringDecoder = (__nccwpck_require__(634)/* .StringDecoder */ .I); var decoder = new StringDecoder(enc); this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: var p = this._readableState.buffer.head; var content = ''; while (p !== null) { content += decoder.write(p.data); p = p.next; } this._readableState.buffer.clear(); if (content !== '') this._readableState.buffer.push(content); this._readableState.length = content.length; return this; }; // Don't raise the hwm > 1GB var MAX_HWM = 0x40000000; function computeNewHighWaterMark(n) { if (n >= MAX_HWM) { // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. n = MAX_HWM; } else { // Get the next highest power of 2 to prevent increasing hwm excessively in // tiny amounts n--; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; n++; } return n; } // This function is designed to be inlinable, so please take care when making // changes to the function body. function howMuchToRead(n, state) { if (n <= 0 || state.length === 0 && state.ended) return 0; if (state.objectMode) return 1; if (n !== n) { // Only flow one buffer at a time if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; } // If we're asking for more than the current hwm, then raise the hwm. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); if (n <= state.length) return n; // Don't have enough if (!state.ended) { state.needReadable = true; return 0; } return state.length; } // you can override either this method, or the async _read(n) below. Readable.prototype.read = function (n) { debug('read', n); n = parseInt(n, 10); var state = this._readableState; var nOrig = n; if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we // already have a bunch of data in the buffer, then just trigger // the 'readable' event and move on. if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { debug('read: emitReadable', state.length, state.ended); if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); return null; } n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. if (n === 0 && state.ended) { if (state.length === 0) endReadable(this); return null; } // All the actual chunk generation logic needs to be // *below* the call to _read. The reason is that in certain // synthetic stream cases, such as passthrough streams, _read // may be a completely synchronous operation which may change // the state of the read buffer, providing enough data when // before there was *not* enough. // // So, the steps are: // 1. Figure out what the state of things will be after we do // a read from the buffer. // // 2. If that resulting state will trigger a _read, then call _read. // Note that this may be asynchronous, or synchronous. Yes, it is // deeply ugly to write APIs this way, but that still doesn't mean // that the Readable class should behave improperly, as streams are // designed to be sync/async agnostic. // Take note if the _read call is sync or async (ie, if the read call // has returned yet), so that we know whether or not it's safe to emit // 'readable' etc. // // 3. Actually pull the requested chunks out of the buffer and return. // if we need a readable event, then we need to do some reading. var doRead = state.needReadable; debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true; debug('length less than watermark', doRead); } // however, if we've ended, then there's no point, and if we're already // reading, then it's unnecessary. if (state.ended || state.reading) { doRead = false; debug('reading or ended', doRead); } else if (doRead) { debug('do read'); state.reading = true; state.sync = true; // if the length is currently zero, then we *need* a readable event. if (state.length === 0) state.needReadable = true; // call internal read method this._read(state.highWaterMark); state.sync = false; // If _read pushed data synchronously, then `reading` will be false, // and we need to re-evaluate how much data we can return to the user. if (!state.reading) n = howMuchToRead(nOrig, state); } var ret; if (n > 0) ret = fromList(n, state);else ret = null; if (ret === null) { state.needReadable = state.length <= state.highWaterMark; n = 0; } else { state.length -= n; state.awaitDrain = 0; } if (state.length === 0) { // If we have nothing in the buffer, then we want to know // as soon as we *do* get something into the buffer. if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. if (nOrig !== n && state.ended) endReadable(this); } if (ret !== null) this.emit('data', ret); return ret; }; function onEofChunk(stream, state) { debug('onEofChunk'); if (state.ended) return; if (state.decoder) { var chunk = state.decoder.end(); if (chunk && chunk.length) { state.buffer.push(chunk); state.length += state.objectMode ? 1 : chunk.length; } } state.ended = true; if (state.sync) { // if we are sync, wait until next tick to emit the data. // Otherwise we risk emitting data in the flow() // the readable code triggers during a read() call emitReadable(stream); } else { // emit 'readable' now to make sure it gets picked up. state.needReadable = false; if (!state.emittedReadable) { state.emittedReadable = true; emitReadable_(stream); } } } // Don't emit readable right away in sync mode, because this can trigger // another read() call => stack overflow. This way, it might trigger // a nextTick recursion warning, but that's not so bad. function emitReadable(stream) { var state = stream._readableState; debug('emitReadable', state.needReadable, state.emittedReadable); state.needReadable = false; if (!state.emittedReadable) { debug('emitReadable', state.flowing); state.emittedReadable = true; process.nextTick(emitReadable_, stream); } } function emitReadable_(stream) { var state = stream._readableState; debug('emitReadable_', state.destroyed, state.length, state.ended); if (!state.destroyed && (state.length || state.ended)) { stream.emit('readable'); state.emittedReadable = false; } // The stream needs another readable event if // 1. It is not flowing, as the flow mechanism will take // care of it. // 2. It is not ended. // 3. It is below the highWaterMark, so we can schedule // another readable later. state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; flow(stream); } // at this point, the user has presumably seen the 'readable' event, // and called read() to consume some data. that may have triggered // in turn another _read(n) call, in which case reading = true if // it's in progress. // However, if we're not ended, or reading, and the length < hwm, // then go ahead and try to read some more preemptively. function maybeReadMore(stream, state) { if (!state.readingMore) { state.readingMore = true; process.nextTick(maybeReadMore_, stream, state); } } function maybeReadMore_(stream, state) { // Attempt to read more data if we should. // // The conditions for reading more data are (one of): // - Not enough data buffered (state.length < state.highWaterMark). The loop // is responsible for filling the buffer with enough data if such data // is available. If highWaterMark is 0 and we are not in the flowing mode // we should _not_ attempt to buffer any extra data. We'll get more data // when the stream consumer calls read() instead. // - No data in the buffer, and the stream is in flowing mode. In this mode // the loop below is responsible for ensuring read() is called. Failing to // call read here would abort the flow and there's no other mechanism for // continuing the flow if the stream consumer has just subscribed to the // 'data' event. // // In addition to the above conditions to keep reading data, the following // conditions prevent the data from being read: // - The stream has ended (state.ended). // - There is already a pending 'read' operation (state.reading). This is a // case where the the stream has called the implementation defined _read() // method, but they are processing the call asynchronously and have _not_ // called push() with new data. In this case we skip performing more // read()s. The execution ends in this method again after the _read() ends // up calling push() with more data. while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { var len = state.length; debug('maybeReadMore read 0'); stream.read(0); if (len === state.length) // didn't get any data, stop spinning. break; } state.readingMore = false; } // abstract method. to be overridden in specific implementation classes. // call cb(er, data) where data is <= n in length. // for virtual (non-string, non-buffer) streams, "length" is somewhat // arbitrary, and perhaps not very meaningful. Readable.prototype._read = function (n) { errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); }; Readable.prototype.pipe = function (dest, pipeOpts) { var src = this; var state = this._readableState; switch (state.pipesCount) { case 0: state.pipes = dest; break; case 1: state.pipes = [state.pipes, dest]; break; default: state.pipes.push(dest); break; } state.pipesCount += 1; debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; var endFn = doEnd ? onend : unpipe; if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); dest.on('unpipe', onunpipe); function onunpipe(readable, unpipeInfo) { debug('onunpipe'); if (readable === src) { if (unpipeInfo && unpipeInfo.hasUnpiped === false) { unpipeInfo.hasUnpiped = true; cleanup(); } } } function onend() { debug('onend'); dest.end(); } // when the dest drains, it reduces the awaitDrain counter // on the source. This would be more elegant with a .once() // handler in flow(), but adding and removing repeatedly is // too slow. var ondrain = pipeOnDrain(src); dest.on('drain', ondrain); var cleanedUp = false; function cleanup() { debug('cleanup'); // cleanup event handlers once the pipe is broken dest.removeListener('close', onclose); dest.removeListener('finish', onfinish); dest.removeListener('drain', ondrain); dest.removeListener('error', onerror); dest.removeListener('unpipe', onunpipe); src.removeListener('end', onend); src.removeListener('end', unpipe); src.removeListener('data', ondata); cleanedUp = true; // if the reader is waiting for a drain event from this // specific writer, then it would cause it to never start // flowing again. // So, if this is awaiting a drain, then we just call it now. // If we don't know, then assume that we are waiting for one. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } src.on('data', ondata); function ondata(chunk) { debug('ondata'); var ret = dest.write(chunk); debug('dest.write', ret); if (ret === false) { // If the user unpiped during `dest.write()`, it is possible // to get stuck in a permanently paused state if that write // also returned false. // => Check whether `dest` is still a piping destination. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { debug('false write response, pause', state.awaitDrain); state.awaitDrain++; } src.pause(); } } // if the dest has an error, then stop piping into it. // however, don't suppress the throwing behavior for this. function onerror(er) { debug('onerror', er); unpipe(); dest.removeListener('error', onerror); if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); } // Make sure our error handler is attached before userland ones. prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. function onclose() { dest.removeListener('finish', onfinish); unpipe(); } dest.once('close', onclose); function onfinish() { debug('onfinish'); dest.removeListener('close', onclose); unpipe(); } dest.once('finish', onfinish); function unpipe() { debug('unpipe'); src.unpipe(dest); } // tell the dest that it's being piped to dest.emit('pipe', src); // start the flow if it hasn't been started already. if (!state.flowing) { debug('pipe resume'); src.resume(); } return dest; }; function pipeOnDrain(src) { return function pipeOnDrainFunctionResult() { var state = src._readableState; debug('pipeOnDrain', state.awaitDrain); if (state.awaitDrain) state.awaitDrain--; if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { state.flowing = true; flow(src); } }; } Readable.prototype.unpipe = function (dest) { var state = this._readableState; var unpipeInfo = { hasUnpiped: false }; // if we're not piping anywhere, then do nothing. if (state.pipesCount === 0) return this; // just one destination. most common case. if (state.pipesCount === 1) { // passed in one, but it's not the right one. if (dest && dest !== state.pipes) return this; if (!dest) dest = state.pipes; // got a match. state.pipes = null; state.pipesCount = 0; state.flowing = false; if (dest) dest.emit('unpipe', this, unpipeInfo); return this; } // slow case. multiple pipe destinations. if (!dest) { // remove all. var dests = state.pipes; var len = state.pipesCount; state.pipes = null; state.pipesCount = 0; state.flowing = false; for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, { hasUnpiped: false }); return this; } // try to find the right one. var index = indexOf(state.pipes, dest); if (index === -1) return this; state.pipes.splice(index, 1); state.pipesCount -= 1; if (state.pipesCount === 1) state.pipes = state.pipes[0]; dest.emit('unpipe', this, unpipeInfo); return this; }; // set up data events if they are asked for // Ensure readable listeners eventually get something Readable.prototype.on = function (ev, fn) { var res = Stream.prototype.on.call(this, ev, fn); var state = this._readableState; if (ev === 'data') { // update readableListening so that resume() may be a no-op // a few lines down. This is needed to support once('readable'). state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused if (state.flowing !== false) this.resume(); } else if (ev === 'readable') { if (!state.endEmitted && !state.readableListening) { state.readableListening = state.needReadable = true; state.flowing = false; state.emittedReadable = false; debug('on readable', state.length, state.reading); if (state.length) { emitReadable(this); } else if (!state.reading) { process.nextTick(nReadingNextTick, this); } } } return res; }; Readable.prototype.addListener = Readable.prototype.on; Readable.prototype.removeListener = function (ev, fn) { var res = Stream.prototype.removeListener.call(this, ev, fn); if (ev === 'readable') { // We need to check if there is someone still listening to // readable and reset the state. However this needs to happen // after readable has been emitted but before I/O (nextTick) to // support once('readable', fn) cycles. This means that calling // resume within the same tick will have no // effect. process.nextTick(updateReadableListening, this); } return res; }; Readable.prototype.removeAllListeners = function (ev) { var res = Stream.prototype.removeAllListeners.apply(this, arguments); if (ev === 'readable' || ev === undefined) { // We need to check if there is someone still listening to // readable and reset the state. However this needs to happen // after readable has been emitted but before I/O (nextTick) to // support once('readable', fn) cycles. This means that calling // resume within the same tick will have no // effect. process.nextTick(updateReadableListening, this); } return res; }; function updateReadableListening(self) { var state = self._readableState; state.readableListening = self.listenerCount('readable') > 0; if (state.resumeScheduled && !state.paused) { // flowing needs to be set to true now, otherwise // the upcoming resume will not flow. state.flowing = true; // crude way to check if we should resume } else if (self.listenerCount('data') > 0) { self.resume(); } } function nReadingNextTick(self) { debug('readable nexttick read 0'); self.read(0); } // pause() and resume() are remnants of the legacy readable stream API // If the user uses them, then switch into old mode. Readable.prototype.resume = function () { var state = this._readableState; if (!state.flowing) { debug('resume'); // we flow only if there is no one listening // for readable, but we still have to call // resume() state.flowing = !state.readableListening; resume(this, state); } state.paused = false; return this; }; function resume(stream, state) { if (!state.resumeScheduled) { state.resumeScheduled = true; process.nextTick(resume_, stream, state); } } function resume_(stream, state) { debug('resume', state.reading); if (!state.reading) { stream.read(0); } state.resumeScheduled = false; stream.emit('resume'); flow(stream); if (state.flowing && !state.reading) stream.read(0); } Readable.prototype.pause = function () { debug('call pause flowing=%j', this._readableState.flowing); if (this._readableState.flowing !== false) { debug('pause'); this._readableState.flowing = false; this.emit('pause'); } this._readableState.paused = true; return this; }; function flow(stream) { var state = stream._readableState; debug('flow', state.flowing); while (state.flowing && stream.read() !== null); } // wrap an old-style stream as the async data source. // This is *not* part of the readable stream interface. // It is an ugly unfortunate mess of history. Readable.prototype.wrap = function (stream) { var _this = this; var state = this._readableState; var paused = false; stream.on('end', function () { debug('wrapped end'); if (state.decoder && !state.ended) { var chunk = state.decoder.end(); if (chunk && chunk.length) _this.push(chunk); } _this.push(null); }); stream.on('data', function (chunk) { debug('wrapped data'); if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; var ret = _this.push(chunk); if (!ret) { paused = true; stream.pause(); } }); // proxy all the other methods. // important when wrapping filters and duplexes. for (var i in stream) { if (this[i] === undefined && typeof stream[i] === 'function') { this[i] = function methodWrap(method) { return function methodWrapReturnFunction() { return stream[method].apply(stream, arguments); }; }(i); } } // proxy certain important events. for (var n = 0; n < kProxyEvents.length; n++) { stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); } // when we try to consume some more bytes, simply unpause the // underlying stream. this._read = function (n) { debug('wrapped _read', n); if (paused) { paused = false; stream.resume(); } }; return this; }; if (typeof Symbol === 'function') { Readable.prototype[Symbol.asyncIterator] = function () { if (createReadableStreamAsyncIterator === undefined) { createReadableStreamAsyncIterator = __nccwpck_require__(4868); } return createReadableStreamAsyncIterator(this); }; } Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._readableState.highWaterMark; } }); Object.defineProperty(Readable.prototype, 'readableBuffer', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._readableState && this._readableState.buffer; } }); Object.defineProperty(Readable.prototype, 'readableFlowing', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._readableState.flowing; }, set: function set(state) { if (this._readableState) { this._readableState.flowing = state; } } }); // exposed for testing purposes only. Readable._fromList = fromList; Object.defineProperty(Readable.prototype, 'readableLength', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._readableState.length; } }); // Pluck off n bytes from an array of buffers. // Length is the combined lengths of all the buffers in the list. // This function is designed to be inlinable, so please take care when making // changes to the function body. function fromList(n, state) { // nothing buffered if (state.length === 0) return null; var ret; if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { // read it all, truncate the list if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); state.buffer.clear(); } else { // read part of list ret = state.buffer.consume(n, state.decoder); } return ret; } function endReadable(stream) { var state = stream._readableState; debug('endReadable', state.endEmitted); if (!state.endEmitted) { state.ended = true; process.nextTick(endReadableNT, state, stream); } } function endReadableNT(state, stream) { debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. if (!state.endEmitted && state.length === 0) { state.endEmitted = true; stream.readable = false; stream.emit('end'); if (state.autoDestroy) { // In case of duplex streams we need a way to detect // if the writable side is ready for autoDestroy as well var wState = stream._writableState; if (!wState || wState.autoDestroy && wState.finished) { stream.destroy(); } } } } if (typeof Symbol === 'function') { Readable.from = function (iterable, opts) { if (from === undefined) { from = __nccwpck_require__(4659); } return from(Readable, iterable, opts); }; } function indexOf(xs, x) { for (var i = 0, l = xs.length; i < l; i++) { if (xs[i] === x) return i; } return -1; } /***/ }), /***/ 2337: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where // some bits pass through, and others are simply ignored. (That would // be a valid example of a transform, of course.) // // While the output is causally related to the input, it's not a // necessarily symmetric or synchronous transformation. For example, // a zlib stream might take multiple plain-text writes(), and then // emit a single compressed chunk some time in the future. // // Here's how this works: // // The Transform stream has all the aspects of the readable and writable // stream classes. When you write(chunk), that calls _write(chunk,cb) // internally, and returns false if there's a lot of pending writes // buffered up. When you call read(), that calls _read(n) until // there's enough pending readable data buffered up. // // In a transform stream, the written data is placed in a buffer. When // _read(n) is called, it transforms the queued up data, calling the // buffered _write cb's as it consumes chunks. If consuming a single // written chunk would result in multiple output chunks, then the first // outputted bit calls the readcb, and subsequent chunks just go into // the read buffer, and will cause it to emit 'readable' if necessary. // // This way, back-pressure is actually determined by the reading side, // since _read has to be called to start processing a new chunk. However, // a pathological inflate type of transform can cause excessive buffering // here. For example, imagine a stream where every byte of input is // interpreted as an integer from 0-255, and then results in that many // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in // 1kb of data being output. In this case, you could write a very small // amount of input, and end up with a very large amount of output. In // such a pathological inflating mechanism, there'd be no way to tell // the system to stop doing the transform. A single 4MB write could // cause the system to run out of memory. // // However, even in such a pathological case, only a single written chunk // would be consumed, and then the rest would wait (un-transformed) until // the results of the previous transformed chunk were consumed. module.exports = Transform; var _require$codes = (__nccwpck_require__(5500)/* .codes */ .F), ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; var Duplex = __nccwpck_require__(2063); __nccwpck_require__(9598)(Transform, Duplex); function afterTransform(er, data) { var ts = this._transformState; ts.transforming = false; var cb = ts.writecb; if (cb === null) { return this.emit('error', new ERR_MULTIPLE_CALLBACK()); } ts.writechunk = null; ts.writecb = null; if (data != null) // single equals check for both `null` and `undefined` this.push(data); cb(er); var rs = this._readableState; rs.reading = false; if (rs.needReadable || rs.length < rs.highWaterMark) { this._read(rs.highWaterMark); } } function Transform(options) { if (!(this instanceof Transform)) return new Transform(options); Duplex.call(this, options); this._transformState = { afterTransform: afterTransform.bind(this), needTransform: false, transforming: false, writecb: null, writechunk: null, writeencoding: null }; // start out asking for a readable event once data is transformed. this._readableState.needReadable = true; // we have implemented the _read method, and done the other things // that Readable wants before the first _read call, so unset the // sync guard flag. this._readableState.sync = false; if (options) { if (typeof options.transform === 'function') this._transform = options.transform; if (typeof options.flush === 'function') this._flush = options.flush; } // When the writable side finishes, then flush out anything remaining. this.on('prefinish', prefinish); } function prefinish() { var _this = this; if (typeof this._flush === 'function' && !this._readableState.destroyed) { this._flush(function (er, data) { done(_this, er, data); }); } else { done(this, null, null); } } Transform.prototype.push = function (chunk, encoding) { this._transformState.needTransform = false; return Duplex.prototype.push.call(this, chunk, encoding); }; // This is the part where you do stuff! // override this function in implementation classes. // 'chunk' is an input chunk. // // Call `push(newChunk)` to pass along transformed output // to the readable side. You may call 'push' zero or more times. // // Call `cb(err)` when you are done with this chunk. If you pass // an error, then that'll put the hurt on the whole operation. If you // never call cb(), then you'll never get another chunk. Transform.prototype._transform = function (chunk, encoding, cb) { cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); }; Transform.prototype._write = function (chunk, encoding, cb) { var ts = this._transformState; ts.writecb = cb; ts.writechunk = chunk; ts.writeencoding = encoding; if (!ts.transforming) { var rs = this._readableState; if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } }; // Doesn't matter what the args are here. // _transform does all the work. // That we got here means that the readable side wants more data. Transform.prototype._read = function (n) { var ts = this._transformState; if (ts.writechunk !== null && !ts.transforming) { ts.transforming = true; this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); } else { // mark that we need a transform, so that any data that comes in // will get processed, now that we've asked for it. ts.needTransform = true; } }; Transform.prototype._destroy = function (err, cb) { Duplex.prototype._destroy.call(this, err, function (err2) { cb(err2); }); }; function done(stream, er, data) { if (er) return stream.emit('error', er); if (data != null) // single equals check for both `null` and `undefined` stream.push(data); // TODO(BridgeAR): Write a test for these two error cases // if there's nothing in the write buffer, then that means // that nothing more will ever be provided if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); return stream.push(null); } /***/ }), /***/ 8797: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // A bit simpler than readable streams. // Implement an async ._write(chunk, encoding, cb), and it'll handle all // the drain event emission and buffering. module.exports = Writable; /* */ function WriteReq(chunk, encoding, cb) { this.chunk = chunk; this.encoding = encoding; this.callback = cb; this.next = null; } // It seems a linked list but it is not // there will be only 2 of these for each stream function CorkedRequest(state) { var _this = this; this.next = null; this.entry = null; this.finish = function () { onCorkedFinish(_this, state); }; } /* */ /**/ var Duplex; /**/ Writable.WritableState = WritableState; /**/ var internalUtil = { deprecate: __nccwpck_require__(4488) }; /**/ /**/ var Stream = __nccwpck_require__(3283); /**/ var Buffer = (__nccwpck_require__(181).Buffer); var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } var destroyImpl = __nccwpck_require__(5089); var _require = __nccwpck_require__(4874), getHighWaterMark = _require.getHighWaterMark; var _require$codes = (__nccwpck_require__(5500)/* .codes */ .F), ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; var errorOrDestroy = destroyImpl.errorOrDestroy; __nccwpck_require__(9598)(Writable, Stream); function nop() {} function WritableState(options, stream, isDuplex) { Duplex = Duplex || __nccwpck_require__(2063); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream, // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream // contains buffers or objects. this.objectMode = !!options.objectMode; if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false // Note: 0 is a valid value, means that we always return false if // the entire buffer is not flushed immediately on write() this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called this.finalCalled = false; // drain event flag. this.needDrain = false; // at the start of calling end() this.ending = false; // when end() has been called, and returned this.ended = false; // when 'finish' is emitted this.finished = false; // has it been destroyed this.destroyed = false; // should we decode strings into buffers before passing to _write? // this is here so that some node-core streams can optimize string // handling at a lower level. var noDecode = options.decodeStrings === false; this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement // of how much we're waiting to get pushed to some underlying // socket or file. this.length = 0; // a flag to see when we're in the middle of a write. this.writing = false; // when true all writes will be buffered until .uncork() call this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. We set this to true at first, because any // actions that shouldn't happen until "later" should generally also // not happen before the first write call. this.sync = true; // a flag to know if we're processing previously buffered items, which // may call the _write() callback in the same tick, so that we don't // end up in an overlapped onwrite situation. this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) this.onwrite = function (er) { onwrite(stream, er); }; // the callback that the user supplies to write(chunk,encoding,cb) this.writecb = null; // the amount that is being written when _write is called. this.writelen = 0; this.bufferedRequest = null; this.lastBufferedRequest = null; // number of pending user-supplied write callbacks // this must be 0 before 'finish' can be emitted this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs // This is relevant for synchronous Transform streams this.prefinished = false; // True if the error was already emitted and should not be thrown again this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') this.autoDestroy = !!options.autoDestroy; // count buffered requests this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always // one allocated and free to use, and we maintain at most two this.corkedRequestsFree = new CorkedRequest(this); } WritableState.prototype.getBuffer = function getBuffer() { var current = this.bufferedRequest; var out = []; while (current) { out.push(current); current = current.next; } return out; }; (function () { try { Object.defineProperty(WritableState.prototype, 'buffer', { get: internalUtil.deprecate(function writableStateBufferGetter() { return this.getBuffer(); }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') }); } catch (_) {} })(); // Test _writableState for inheritance to account for Duplex streams, // whose prototype chain only points to Readable. var realHasInstance; if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { realHasInstance = Function.prototype[Symbol.hasInstance]; Object.defineProperty(Writable, Symbol.hasInstance, { value: function value(object) { if (realHasInstance.call(this, object)) return true; if (this !== Writable) return false; return object && object._writableState instanceof WritableState; } }); } else { realHasInstance = function realHasInstance(object) { return object instanceof this; }; } function Writable(options) { Duplex = Duplex || __nccwpck_require__(2063); // Writable ctor is applied to Duplexes, too. // `realHasInstance` is necessary because using plain `instanceof` // would return false, as no `_writableState` property is attached. // Trying to use the custom `instanceof` for Writable here will also break the // Node.js LazyTransform implementation, which has a non-trivial getter for // `_writableState` that would lead to infinite recursion. // Checking for a Stream.Duplex instance is faster here instead of inside // the WritableState constructor, at least with V8 6.5 var isDuplex = this instanceof Duplex; if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); this._writableState = new WritableState(options, this, isDuplex); // legacy. this.writable = true; if (options) { if (typeof options.write === 'function') this._write = options.write; if (typeof options.writev === 'function') this._writev = options.writev; if (typeof options.destroy === 'function') this._destroy = options.destroy; if (typeof options.final === 'function') this._final = options.final; } Stream.call(this); } // Otherwise people can pipe Writable streams, which is just wrong. Writable.prototype.pipe = function () { errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); }; function writeAfterEnd(stream, cb) { var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb errorOrDestroy(stream, er); process.nextTick(cb, er); } // Checks that a user-supplied chunk is valid, especially for the particular // mode the stream is in. Currently this means that `null` is never accepted // and undefined/non-string values are only allowed in object mode. function validChunk(stream, state, chunk, cb) { var er; if (chunk === null) { er = new ERR_STREAM_NULL_VALUES(); } else if (typeof chunk !== 'string' && !state.objectMode) { er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); } if (er) { errorOrDestroy(stream, er); process.nextTick(cb, er); return false; } return true; } Writable.prototype.write = function (chunk, encoding, cb) { var state = this._writableState; var ret = false; var isBuf = !state.objectMode && _isUint8Array(chunk); if (isBuf && !Buffer.isBuffer(chunk)) { chunk = _uint8ArrayToBuffer(chunk); } if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; if (typeof cb !== 'function') cb = nop; if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { state.pendingcb++; ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); } return ret; }; Writable.prototype.cork = function () { this._writableState.corked++; }; Writable.prototype.uncork = function () { var state = this._writableState; if (state.corked) { state.corked--; if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); } }; Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { // node::ParseEncoding() requires lower case. if (typeof encoding === 'string') encoding = encoding.toLowerCase(); if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); this._writableState.defaultEncoding = encoding; return this; }; Object.defineProperty(Writable.prototype, 'writableBuffer', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState && this._writableState.getBuffer(); } }); function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { chunk = Buffer.from(chunk, encoding); } return chunk; } Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState.highWaterMark; } }); // if we're already writing something, then just put this // in the queue, and wait our turn. Otherwise, call _write // If we return false, then we need a drain event, so set that flag. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { if (!isBuf) { var newChunk = decodeChunk(state, chunk, encoding); if (chunk !== newChunk) { isBuf = true; encoding = 'buffer'; chunk = newChunk; } } var len = state.objectMode ? 1 : chunk.length; state.length += len; var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. if (!ret) state.needDrain = true; if (state.writing || state.corked) { var last = state.lastBufferedRequest; state.lastBufferedRequest = { chunk: chunk, encoding: encoding, isBuf: isBuf, callback: cb, next: null }; if (last) { last.next = state.lastBufferedRequest; } else { state.bufferedRequest = state.lastBufferedRequest; } state.bufferedRequestCount += 1; } else { doWrite(stream, state, false, len, chunk, encoding, cb); } return ret; } function doWrite(stream, state, writev, len, chunk, encoding, cb) { state.writelen = len; state.writecb = cb; state.writing = true; state.sync = true; if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); state.sync = false; } function onwriteError(stream, state, sync, er, cb) { --state.pendingcb; if (sync) { // defer the callback if we are being called synchronously // to avoid piling up things on the stack process.nextTick(cb, er); // this can emit finish, and it will always happen // after error process.nextTick(finishMaybe, stream, state); stream._writableState.errorEmitted = true; errorOrDestroy(stream, er); } else { // the caller expect this to happen before if // it is async cb(er); stream._writableState.errorEmitted = true; errorOrDestroy(stream, er); // this can emit finish, but finish must // always follow error finishMaybe(stream, state); } } function onwriteStateUpdate(state) { state.writing = false; state.writecb = null; state.length -= state.writelen; state.writelen = 0; } function onwrite(stream, er) { var state = stream._writableState; var sync = state.sync; var cb = state.writecb; if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); onwriteStateUpdate(state); if (er) onwriteError(stream, state, sync, er, cb);else { // Check if we're actually ready to finish, but don't emit yet var finished = needFinish(state) || stream.destroyed; if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { clearBuffer(stream, state); } if (sync) { process.nextTick(afterWrite, stream, state, finished, cb); } else { afterWrite(stream, state, finished, cb); } } } function afterWrite(stream, state, finished, cb) { if (!finished) onwriteDrain(stream, state); state.pendingcb--; cb(); finishMaybe(stream, state); } // Must force callback to be called on nextTick, so that we don't // emit 'drain' before the write() consumer gets the 'false' return // value, and has a chance to attach a 'drain' listener. function onwriteDrain(stream, state) { if (state.length === 0 && state.needDrain) { state.needDrain = false; stream.emit('drain'); } } // if there's something in the buffer waiting, then process it function clearBuffer(stream, state) { state.bufferProcessing = true; var entry = state.bufferedRequest; if (stream._writev && entry && entry.next) { // Fast case, write everything using _writev() var l = state.bufferedRequestCount; var buffer = new Array(l); var holder = state.corkedRequestsFree; holder.entry = entry; var count = 0; var allBuffers = true; while (entry) { buffer[count] = entry; if (!entry.isBuf) allBuffers = false; entry = entry.next; count += 1; } buffer.allBuffers = allBuffers; doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time // as the hot path ends with doWrite state.pendingcb++; state.lastBufferedRequest = null; if (holder.next) { state.corkedRequestsFree = holder.next; holder.next = null; } else { state.corkedRequestsFree = new CorkedRequest(state); } state.bufferedRequestCount = 0; } else { // Slow case, write chunks one-by-one while (entry) { var chunk = entry.chunk; var encoding = entry.encoding; var cb = entry.callback; var len = state.objectMode ? 1 : chunk.length; doWrite(stream, state, false, len, chunk, encoding, cb); entry = entry.next; state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then // it means that we need to wait until it does. // also, that means that the chunk and cb are currently // being processed, so move the buffer counter past them. if (state.writing) { break; } } if (entry === null) state.lastBufferedRequest = null; } state.bufferedRequest = entry; state.bufferProcessing = false; } Writable.prototype._write = function (chunk, encoding, cb) { cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); }; Writable.prototype._writev = null; Writable.prototype.end = function (chunk, encoding, cb) { var state = this._writableState; if (typeof chunk === 'function') { cb = chunk; chunk = null; encoding = null; } else if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks if (state.corked) { state.corked = 1; this.uncork(); } // ignore unnecessary end() calls. if (!state.ending) endWritable(this, state, cb); return this; }; Object.defineProperty(Writable.prototype, 'writableLength', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState.length; } }); function needFinish(state) { return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; } function callFinal(stream, state) { stream._final(function (err) { state.pendingcb--; if (err) { errorOrDestroy(stream, err); } state.prefinished = true; stream.emit('prefinish'); finishMaybe(stream, state); }); } function prefinish(stream, state) { if (!state.prefinished && !state.finalCalled) { if (typeof stream._final === 'function' && !state.destroyed) { state.pendingcb++; state.finalCalled = true; process.nextTick(callFinal, stream, state); } else { state.prefinished = true; stream.emit('prefinish'); } } } function finishMaybe(stream, state) { var need = needFinish(state); if (need) { prefinish(stream, state); if (state.pendingcb === 0) { state.finished = true; stream.emit('finish'); if (state.autoDestroy) { // In case of duplex streams we need a way to detect // if the readable side is ready for autoDestroy as well var rState = stream._readableState; if (!rState || rState.autoDestroy && rState.endEmitted) { stream.destroy(); } } } } return need; } function endWritable(stream, state, cb) { state.ending = true; finishMaybe(stream, state); if (cb) { if (state.finished) process.nextTick(cb);else stream.once('finish', cb); } state.ended = true; stream.writable = false; } function onCorkedFinish(corkReq, state, err) { var entry = corkReq.entry; corkReq.entry = null; while (entry) { var cb = entry.callback; state.pendingcb--; cb(err); entry = entry.next; } // reuse the free corkReq. state.corkedRequestsFree.next = corkReq; } Object.defineProperty(Writable.prototype, 'destroyed', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { if (this._writableState === undefined) { return false; } return this._writableState.destroyed; }, set: function set(value) { // we ignore the value if the stream // has not been initialized yet if (!this._writableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._writableState.destroyed = value; } }); Writable.prototype.destroy = destroyImpl.destroy; Writable.prototype._undestroy = destroyImpl.undestroy; Writable.prototype._destroy = function (err, cb) { cb(err); }; /***/ }), /***/ 4868: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var _Object$setPrototypeO; function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } var finished = __nccwpck_require__(6815); var kLastResolve = Symbol('lastResolve'); var kLastReject = Symbol('lastReject'); var kError = Symbol('error'); var kEnded = Symbol('ended'); var kLastPromise = Symbol('lastPromise'); var kHandlePromise = Symbol('handlePromise'); var kStream = Symbol('stream'); function createIterResult(value, done) { return { value: value, done: done }; } function readAndResolve(iter) { var resolve = iter[kLastResolve]; if (resolve !== null) { var data = iter[kStream].read(); // we defer if data is null // we can be expecting either 'end' or // 'error' if (data !== null) { iter[kLastPromise] = null; iter[kLastResolve] = null; iter[kLastReject] = null; resolve(createIterResult(data, false)); } } } function onReadable(iter) { // we wait for the next tick, because it might // emit an error with process.nextTick process.nextTick(readAndResolve, iter); } function wrapForNext(lastPromise, iter) { return function (resolve, reject) { lastPromise.then(function () { if (iter[kEnded]) { resolve(createIterResult(undefined, true)); return; } iter[kHandlePromise](resolve, reject); }, reject); }; } var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { get stream() { return this[kStream]; }, next: function next() { var _this = this; // if we have detected an error in the meanwhile // reject straight away var error = this[kError]; if (error !== null) { return Promise.reject(error); } if (this[kEnded]) { return Promise.resolve(createIterResult(undefined, true)); } if (this[kStream].destroyed) { // We need to defer via nextTick because if .destroy(err) is // called, the error will be emitted via nextTick, and // we cannot guarantee that there is no error lingering around // waiting to be emitted. return new Promise(function (resolve, reject) { process.nextTick(function () { if (_this[kError]) { reject(_this[kError]); } else { resolve(createIterResult(undefined, true)); } }); }); } // if we have multiple next() calls // we will wait for the previous Promise to finish // this logic is optimized to support for await loops, // where next() is only called once at a time var lastPromise = this[kLastPromise]; var promise; if (lastPromise) { promise = new Promise(wrapForNext(lastPromise, this)); } else { // fast path needed to support multiple this.push() // without triggering the next() queue var data = this[kStream].read(); if (data !== null) { return Promise.resolve(createIterResult(data, false)); } promise = new Promise(this[kHandlePromise]); } this[kLastPromise] = promise; return promise; } }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { return this; }), _defineProperty(_Object$setPrototypeO, "return", function _return() { var _this2 = this; // destroy(err, cb) is a private API // we can guarantee we have that here, because we control the // Readable class this is attached to return new Promise(function (resolve, reject) { _this2[kStream].destroy(null, function (err) { if (err) { reject(err); return; } resolve(createIterResult(undefined, true)); }); }); }), _Object$setPrototypeO), AsyncIteratorPrototype); var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { var _Object$create; var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { value: stream, writable: true }), _defineProperty(_Object$create, kLastResolve, { value: null, writable: true }), _defineProperty(_Object$create, kLastReject, { value: null, writable: true }), _defineProperty(_Object$create, kError, { value: null, writable: true }), _defineProperty(_Object$create, kEnded, { value: stream._readableState.endEmitted, writable: true }), _defineProperty(_Object$create, kHandlePromise, { value: function value(resolve, reject) { var data = iterator[kStream].read(); if (data) { iterator[kLastPromise] = null; iterator[kLastResolve] = null; iterator[kLastReject] = null; resolve(createIterResult(data, false)); } else { iterator[kLastResolve] = resolve; iterator[kLastReject] = reject; } }, writable: true }), _Object$create)); iterator[kLastPromise] = null; finished(stream, function (err) { if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise // returned by next() and store the error if (reject !== null) { iterator[kLastPromise] = null; iterator[kLastResolve] = null; iterator[kLastReject] = null; reject(err); } iterator[kError] = err; return; } var resolve = iterator[kLastResolve]; if (resolve !== null) { iterator[kLastPromise] = null; iterator[kLastResolve] = null; iterator[kLastReject] = null; resolve(createIterResult(undefined, true)); } iterator[kEnded] = true; }); stream.on('readable', onReadable.bind(null, iterator)); return iterator; }; module.exports = createReadableStreamAsyncIterator; /***/ }), /***/ 7336: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } var _require = __nccwpck_require__(181), Buffer = _require.Buffer; var _require2 = __nccwpck_require__(9023), inspect = _require2.inspect; var custom = inspect && inspect.custom || 'inspect'; function copyBuffer(src, target, offset) { Buffer.prototype.copy.call(src, target, offset); } module.exports = /*#__PURE__*/function () { function BufferList() { _classCallCheck(this, BufferList); this.head = null; this.tail = null; this.length = 0; } _createClass(BufferList, [{ key: "push", value: function push(v) { var entry = { data: v, next: null }; if (this.length > 0) this.tail.next = entry;else this.head = entry; this.tail = entry; ++this.length; } }, { key: "unshift", value: function unshift(v) { var entry = { data: v, next: this.head }; if (this.length === 0) this.tail = entry; this.head = entry; ++this.length; } }, { key: "shift", value: function shift() { if (this.length === 0) return; var ret = this.head.data; if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; --this.length; return ret; } }, { key: "clear", value: function clear() { this.head = this.tail = null; this.length = 0; } }, { key: "join", value: function join(s) { if (this.length === 0) return ''; var p = this.head; var ret = '' + p.data; while (p = p.next) ret += s + p.data; return ret; } }, { key: "concat", value: function concat(n) { if (this.length === 0) return Buffer.alloc(0); var ret = Buffer.allocUnsafe(n >>> 0); var p = this.head; var i = 0; while (p) { copyBuffer(p.data, ret, i); i += p.data.length; p = p.next; } return ret; } // Consumes a specified amount of bytes or characters from the buffered data. }, { key: "consume", value: function consume(n, hasStrings) { var ret; if (n < this.head.data.length) { // `slice` is the same for buffers and strings. ret = this.head.data.slice(0, n); this.head.data = this.head.data.slice(n); } else if (n === this.head.data.length) { // First chunk is a perfect match. ret = this.shift(); } else { // Result spans more than one buffer. ret = hasStrings ? this._getString(n) : this._getBuffer(n); } return ret; } }, { key: "first", value: function first() { return this.head.data; } // Consumes a specified amount of characters from the buffered data. }, { key: "_getString", value: function _getString(n) { var p = this.head; var c = 1; var ret = p.data; n -= ret.length; while (p = p.next) { var str = p.data; var nb = n > str.length ? str.length : n; if (nb === str.length) ret += str;else ret += str.slice(0, n); n -= nb; if (n === 0) { if (nb === str.length) { ++c; if (p.next) this.head = p.next;else this.head = this.tail = null; } else { this.head = p; p.data = str.slice(nb); } break; } ++c; } this.length -= c; return ret; } // Consumes a specified amount of bytes from the buffered data. }, { key: "_getBuffer", value: function _getBuffer(n) { var ret = Buffer.allocUnsafe(n); var p = this.head; var c = 1; p.data.copy(ret); n -= p.data.length; while (p = p.next) { var buf = p.data; var nb = n > buf.length ? buf.length : n; buf.copy(ret, ret.length - n, 0, nb); n -= nb; if (n === 0) { if (nb === buf.length) { ++c; if (p.next) this.head = p.next;else this.head = this.tail = null; } else { this.head = p; p.data = buf.slice(nb); } break; } ++c; } this.length -= c; return ret; } // Make sure the linked list only shows the minimal necessary information. }, { key: custom, value: function value(_, options) { return inspect(this, _objectSpread(_objectSpread({}, options), {}, { // Only inspect one level. depth: 0, // It should not recurse. customInspect: false })); } }]); return BufferList; }(); /***/ }), /***/ 5089: /***/ ((module) => { "use strict"; // undocumented cb() API, needed for core, not for public API function destroy(err, cb) { var _this = this; var readableDestroyed = this._readableState && this._readableState.destroyed; var writableDestroyed = this._writableState && this._writableState.destroyed; if (readableDestroyed || writableDestroyed) { if (cb) { cb(err); } else if (err) { if (!this._writableState) { process.nextTick(emitErrorNT, this, err); } else if (!this._writableState.errorEmitted) { this._writableState.errorEmitted = true; process.nextTick(emitErrorNT, this, err); } } return this; } // we set destroyed to true before firing error callbacks in order // to make it re-entrance safe in case destroy() is called within callbacks if (this._readableState) { this._readableState.destroyed = true; } // if this is a duplex stream mark the writable part as destroyed as well if (this._writableState) { this._writableState.destroyed = true; } this._destroy(err || null, function (err) { if (!cb && err) { if (!_this._writableState) { process.nextTick(emitErrorAndCloseNT, _this, err); } else if (!_this._writableState.errorEmitted) { _this._writableState.errorEmitted = true; process.nextTick(emitErrorAndCloseNT, _this, err); } else { process.nextTick(emitCloseNT, _this); } } else if (cb) { process.nextTick(emitCloseNT, _this); cb(err); } else { process.nextTick(emitCloseNT, _this); } }); return this; } function emitErrorAndCloseNT(self, err) { emitErrorNT(self, err); emitCloseNT(self); } function emitCloseNT(self) { if (self._writableState && !self._writableState.emitClose) return; if (self._readableState && !self._readableState.emitClose) return; self.emit('close'); } function undestroy() { if (this._readableState) { this._readableState.destroyed = false; this._readableState.reading = false; this._readableState.ended = false; this._readableState.endEmitted = false; } if (this._writableState) { this._writableState.destroyed = false; this._writableState.ended = false; this._writableState.ending = false; this._writableState.finalCalled = false; this._writableState.prefinished = false; this._writableState.finished = false; this._writableState.errorEmitted = false; } } function emitErrorNT(self, err) { self.emit('error', err); } function errorOrDestroy(stream, err) { // We have tests that rely on errors being emitted // in the same tick, so changing this is semver major. // For now when you opt-in to autoDestroy we allow // the error to be emitted nextTick. In a future // semver major update we should change the default to this. var rState = stream._readableState; var wState = stream._writableState; if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); } module.exports = { destroy: destroy, undestroy: undestroy, errorOrDestroy: errorOrDestroy }; /***/ }), /***/ 6815: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Ported from https://github.com/mafintosh/end-of-stream with // permission from the author, Mathias Buus (@mafintosh). var ERR_STREAM_PREMATURE_CLOSE = (__nccwpck_require__(5500)/* .codes */ .F).ERR_STREAM_PREMATURE_CLOSE; function once(callback) { var called = false; return function () { if (called) return; called = true; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } callback.apply(this, args); }; } function noop() {} function isRequest(stream) { return stream.setHeader && typeof stream.abort === 'function'; } function eos(stream, opts, callback) { if (typeof opts === 'function') return eos(stream, null, opts); if (!opts) opts = {}; callback = once(callback || noop); var readable = opts.readable || opts.readable !== false && stream.readable; var writable = opts.writable || opts.writable !== false && stream.writable; var onlegacyfinish = function onlegacyfinish() { if (!stream.writable) onfinish(); }; var writableEnded = stream._writableState && stream._writableState.finished; var onfinish = function onfinish() { writable = false; writableEnded = true; if (!readable) callback.call(stream); }; var readableEnded = stream._readableState && stream._readableState.endEmitted; var onend = function onend() { readable = false; readableEnded = true; if (!writable) callback.call(stream); }; var onerror = function onerror(err) { callback.call(stream, err); }; var onclose = function onclose() { var err; if (readable && !readableEnded) { if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); return callback.call(stream, err); } if (writable && !writableEnded) { if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); return callback.call(stream, err); } }; var onrequest = function onrequest() { stream.req.on('finish', onfinish); }; if (isRequest(stream)) { stream.on('complete', onfinish); stream.on('abort', onclose); if (stream.req) onrequest();else stream.on('request', onrequest); } else if (writable && !stream._writableState) { // legacy streams stream.on('end', onlegacyfinish); stream.on('close', onlegacyfinish); } stream.on('end', onend); stream.on('finish', onfinish); if (opts.error !== false) stream.on('error', onerror); stream.on('close', onclose); return function () { stream.removeListener('complete', onfinish); stream.removeListener('abort', onclose); stream.removeListener('request', onrequest); if (stream.req) stream.req.removeListener('finish', onfinish); stream.removeListener('end', onlegacyfinish); stream.removeListener('close', onlegacyfinish); stream.removeListener('finish', onfinish); stream.removeListener('end', onend); stream.removeListener('error', onerror); stream.removeListener('close', onclose); }; } module.exports = eos; /***/ }), /***/ 4659: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } var ERR_INVALID_ARG_TYPE = (__nccwpck_require__(5500)/* .codes */ .F).ERR_INVALID_ARG_TYPE; function from(Readable, iterable, opts) { var iterator; if (iterable && typeof iterable.next === 'function') { iterator = iterable; } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); var readable = new Readable(_objectSpread({ objectMode: true }, opts)); // Reading boolean to protect against _read // being called before last iteration completion. var reading = false; readable._read = function () { if (!reading) { reading = true; next(); } }; function next() { return _next2.apply(this, arguments); } function _next2() { _next2 = _asyncToGenerator(function* () { try { var _yield$iterator$next = yield iterator.next(), value = _yield$iterator$next.value, done = _yield$iterator$next.done; if (done) { readable.push(null); } else if (readable.push(yield value)) { next(); } else { reading = false; } } catch (err) { readable.destroy(err); } }); return _next2.apply(this, arguments); } return readable; } module.exports = from; /***/ }), /***/ 6701: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Ported from https://github.com/mafintosh/pump with // permission from the author, Mathias Buus (@mafintosh). var eos; function once(callback) { var called = false; return function () { if (called) return; called = true; callback.apply(void 0, arguments); }; } var _require$codes = (__nccwpck_require__(5500)/* .codes */ .F), ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; function noop(err) { // Rethrow the error if it exists to avoid swallowing it if (err) throw err; } function isRequest(stream) { return stream.setHeader && typeof stream.abort === 'function'; } function destroyer(stream, reading, writing, callback) { callback = once(callback); var closed = false; stream.on('close', function () { closed = true; }); if (eos === undefined) eos = __nccwpck_require__(6815); eos(stream, { readable: reading, writable: writing }, function (err) { if (err) return callback(err); closed = true; callback(); }); var destroyed = false; return function (err) { if (closed) return; if (destroyed) return; destroyed = true; // request.destroy just do .end - .abort is what we want if (isRequest(stream)) return stream.abort(); if (typeof stream.destroy === 'function') return stream.destroy(); callback(err || new ERR_STREAM_DESTROYED('pipe')); }; } function call(fn) { fn(); } function pipe(from, to) { return from.pipe(to); } function popCallback(streams) { if (!streams.length) return noop; if (typeof streams[streams.length - 1] !== 'function') return noop; return streams.pop(); } function pipeline() { for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { streams[_key] = arguments[_key]; } var callback = popCallback(streams); if (Array.isArray(streams[0])) streams = streams[0]; if (streams.length < 2) { throw new ERR_MISSING_ARGS('streams'); } var error; var destroys = streams.map(function (stream, i) { var reading = i < streams.length - 1; var writing = i > 0; return destroyer(stream, reading, writing, function (err) { if (!error) error = err; if (err) destroys.forEach(call); if (reading) return; destroys.forEach(call); callback(error); }); }); return streams.reduce(pipe); } module.exports = pipeline; /***/ }), /***/ 4874: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var ERR_INVALID_OPT_VALUE = (__nccwpck_require__(5500)/* .codes */ .F).ERR_INVALID_OPT_VALUE; function highWaterMarkFrom(options, isDuplex, duplexKey) { return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; } function getHighWaterMark(state, options, duplexKey, isDuplex) { var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); if (hwm != null) { if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { var name = isDuplex ? duplexKey : 'highWaterMark'; throw new ERR_INVALID_OPT_VALUE(name, hwm); } return Math.floor(hwm); } // Default value return state.objectMode ? 16 : 16 * 1024; } module.exports = { getHighWaterMark: getHighWaterMark }; /***/ }), /***/ 3283: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = __nccwpck_require__(2203); /***/ }), /***/ 6131: /***/ ((module, exports, __nccwpck_require__) => { var Stream = __nccwpck_require__(2203); if (process.env.READABLE_STREAM === 'disable' && Stream) { module.exports = Stream.Readable; Object.assign(module.exports, Stream); module.exports.Stream = Stream; } else { exports = module.exports = __nccwpck_require__(9274); exports.Stream = Stream || exports; exports.Readable = exports; exports.Writable = __nccwpck_require__(8797); exports.Duplex = __nccwpck_require__(2063); exports.Transform = __nccwpck_require__(2337); exports.PassThrough = __nccwpck_require__(5283); exports.finished = __nccwpck_require__(6815); exports.pipeline = __nccwpck_require__(6701); } /***/ }), /***/ 7842: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const {PassThrough} = __nccwpck_require__(2203); const extend = __nccwpck_require__(3860); let debug = () => {}; if ( typeof process !== 'undefined' && 'env' in process && typeof process.env === 'object' && process.env.DEBUG === 'retry-request' ) { debug = message => { console.log('retry-request:', message); }; } const DEFAULTS = { objectMode: false, retries: 2, /* The maximum time to delay in seconds. If retryDelayMultiplier results in a delay greater than maxRetryDelay, retries should delay by maxRetryDelay seconds instead. */ maxRetryDelay: 64, /* The multiplier by which to increase the delay time between the completion of failed requests, and the initiation of the subsequent retrying request. */ retryDelayMultiplier: 2, /* The length of time to keep retrying in seconds. The last sleep period will be shortened as necessary, so that the last retry runs at deadline (and not considerably beyond it). The total time starting from when the initial request is sent, after which an error will be returned, regardless of the retrying attempts made meanwhile. */ totalTimeout: 600, noResponseRetries: 2, currentRetryAttempt: 0, shouldRetryFn: function (response) { const retryRanges = [ // https://en.wikipedia.org/wiki/List_of_HTTP_status_codes // 1xx - Retry (Informational, request still processing) // 2xx - Do not retry (Success) // 3xx - Do not retry (Redirect) // 4xx - Do not retry (Client errors) // 429 - Retry ("Too Many Requests") // 5xx - Retry (Server errors) [100, 199], [429, 429], [500, 599], ]; const statusCode = response.statusCode; debug(`Response status: ${statusCode}`); let range; while ((range = retryRanges.shift())) { if (statusCode >= range[0] && statusCode <= range[1]) { // Not a successful status or redirect. return true; } } }, }; function retryRequest(requestOpts, opts, callback) { if (typeof requestOpts === 'string') { requestOpts = {url: requestOpts}; } const streamMode = typeof arguments[arguments.length - 1] !== 'function'; if (typeof opts === 'function') { callback = opts; } const manualCurrentRetryAttemptWasSet = opts && typeof opts.currentRetryAttempt === 'number'; opts = extend({}, DEFAULTS, opts); if (typeof opts.request === 'undefined') { throw new Error('A request library must be provided to retry-request.'); } let currentRetryAttempt = opts.currentRetryAttempt; let numNoResponseAttempts = 0; let streamResponseHandled = false; let retryStream; let requestStream; let delayStream; let activeRequest; const retryRequest = { abort: function () { if (activeRequest && activeRequest.abort) { activeRequest.abort(); } }, }; if (streamMode) { retryStream = new PassThrough({objectMode: opts.objectMode}); retryStream.abort = resetStreams; } const timeOfFirstRequest = Date.now(); if (currentRetryAttempt > 0) { retryAfterDelay(currentRetryAttempt); } else { makeRequest(); } if (streamMode) { return retryStream; } else { return retryRequest; } function resetStreams() { delayStream = null; if (requestStream) { requestStream.abort && requestStream.abort(); requestStream.cancel && requestStream.cancel(); if (requestStream.destroy) { requestStream.destroy(); } else if (requestStream.end) { requestStream.end(); } } } function makeRequest() { let finishHandled = false; currentRetryAttempt++; debug(`Current retry attempt: ${currentRetryAttempt}`); function handleFinish(args = []) { if (!finishHandled) { finishHandled = true; retryStream.emit('complete', ...args); } } if (streamMode) { streamResponseHandled = false; delayStream = new PassThrough({objectMode: opts.objectMode}); requestStream = opts.request(requestOpts); setImmediate(() => { retryStream.emit('request'); }); requestStream // gRPC via google-cloud-node can emit an `error` as well as a `response` // Whichever it emits, we run with-- we can't run with both. That's what // is up with the `streamResponseHandled` tracking. .on('error', err => { if (streamResponseHandled) { return; } streamResponseHandled = true; onResponse(err); }) .on('response', (resp, body) => { if (streamResponseHandled) { return; } streamResponseHandled = true; onResponse(null, resp, body); }) .on('complete', (...params) => handleFinish(params)) .on('finish', (...params) => handleFinish(params)); requestStream.pipe(delayStream); } else { activeRequest = opts.request(requestOpts, onResponse); } } function retryAfterDelay(currentRetryAttempt) { if (streamMode) { resetStreams(); } const nextRetryDelay = getNextRetryDelay({ maxRetryDelay: opts.maxRetryDelay, retryDelayMultiplier: opts.retryDelayMultiplier, retryNumber: currentRetryAttempt, timeOfFirstRequest, totalTimeout: opts.totalTimeout, }); debug(`Next retry delay: ${nextRetryDelay}`); if (nextRetryDelay <= 0) { numNoResponseAttempts = opts.noResponseRetries + 1; return; } setTimeout(makeRequest, nextRetryDelay); } function onResponse(err, response, body) { // An error such as DNS resolution. if (err) { numNoResponseAttempts++; if (numNoResponseAttempts <= opts.noResponseRetries) { retryAfterDelay(numNoResponseAttempts); } else { if (streamMode) { retryStream.emit('error', err); retryStream.end(); } else { callback(err, response, body); } } return; } // Send the response to see if we should try again. // NOTE: "currentRetryAttempt" isn't accurate by default, as it counts // the very first request sent as the first "retry". It is only accurate // when a user provides their own "currentRetryAttempt" option at // instantiation. const adjustedCurrentRetryAttempt = manualCurrentRetryAttemptWasSet ? currentRetryAttempt : currentRetryAttempt - 1; if ( adjustedCurrentRetryAttempt < opts.retries && opts.shouldRetryFn(response) ) { retryAfterDelay(currentRetryAttempt); return; } // No more attempts need to be made, just continue on. if (streamMode) { retryStream.emit('response', response); delayStream.pipe(retryStream); requestStream.on('error', err => { retryStream.destroy(err); }); } else { callback(err, response, body); } } } module.exports = retryRequest; function getNextRetryDelay(config) { const { maxRetryDelay, retryDelayMultiplier, retryNumber, timeOfFirstRequest, totalTimeout, } = config; const maxRetryDelayMs = maxRetryDelay * 1000; const totalTimeoutMs = totalTimeout * 1000; const jitter = Math.floor(Math.random() * 1000); const calculatedNextRetryDelay = Math.pow(retryDelayMultiplier, retryNumber) * 1000 + jitter; const maxAllowableDelayMs = totalTimeoutMs - (Date.now() - timeOfFirstRequest); return Math.min( calculatedNextRetryDelay, maxAllowableDelayMs, maxRetryDelayMs ); } module.exports.defaults = DEFAULTS; module.exports.getNextRetryDelay = getNextRetryDelay; /***/ }), /***/ 5546: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = __nccwpck_require__(7084); /***/ }), /***/ 7084: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { var RetryOperation = __nccwpck_require__(9538); exports.operation = function(options) { var timeouts = exports.timeouts(options); return new RetryOperation(timeouts, { forever: options && (options.forever || options.retries === Infinity), unref: options && options.unref, maxRetryTime: options && options.maxRetryTime }); }; exports.timeouts = function(options) { if (options instanceof Array) { return [].concat(options); } var opts = { retries: 10, factor: 2, minTimeout: 1 * 1000, maxTimeout: Infinity, randomize: false }; for (var key in options) { opts[key] = options[key]; } if (opts.minTimeout > opts.maxTimeout) { throw new Error('minTimeout is greater than maxTimeout'); } var timeouts = []; for (var i = 0; i < opts.retries; i++) { timeouts.push(this.createTimeout(i, opts)); } if (options && options.forever && !timeouts.length) { timeouts.push(this.createTimeout(i, opts)); } // sort the array numerically ascending timeouts.sort(function(a,b) { return a - b; }); return timeouts; }; exports.createTimeout = function(attempt, opts) { var random = (opts.randomize) ? (Math.random() + 1) : 1; var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt)); timeout = Math.min(timeout, opts.maxTimeout); return timeout; }; exports.wrap = function(obj, options, methods) { if (options instanceof Array) { methods = options; options = null; } if (!methods) { methods = []; for (var key in obj) { if (typeof obj[key] === 'function') { methods.push(key); } } } for (var i = 0; i < methods.length; i++) { var method = methods[i]; var original = obj[method]; obj[method] = function retryWrapper(original) { var op = exports.operation(options); var args = Array.prototype.slice.call(arguments, 1); var callback = args.pop(); args.push(function(err) { if (op.retry(err)) { return; } if (err) { arguments[0] = op.mainError(); } callback.apply(this, arguments); }); op.attempt(function() { original.apply(obj, args); }); }.bind(obj, original); obj[method].options = options; } }; /***/ }), /***/ 9538: /***/ ((module) => { function RetryOperation(timeouts, options) { // Compatibility for the old (timeouts, retryForever) signature if (typeof options === 'boolean') { options = { forever: options }; } this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); this._timeouts = timeouts; this._options = options || {}; this._maxRetryTime = options && options.maxRetryTime || Infinity; this._fn = null; this._errors = []; this._attempts = 1; this._operationTimeout = null; this._operationTimeoutCb = null; this._timeout = null; this._operationStart = null; this._timer = null; if (this._options.forever) { this._cachedTimeouts = this._timeouts.slice(0); } } module.exports = RetryOperation; RetryOperation.prototype.reset = function() { this._attempts = 1; this._timeouts = this._originalTimeouts.slice(0); } RetryOperation.prototype.stop = function() { if (this._timeout) { clearTimeout(this._timeout); } if (this._timer) { clearTimeout(this._timer); } this._timeouts = []; this._cachedTimeouts = null; }; RetryOperation.prototype.retry = function(err) { if (this._timeout) { clearTimeout(this._timeout); } if (!err) { return false; } var currentTime = new Date().getTime(); if (err && currentTime - this._operationStart >= this._maxRetryTime) { this._errors.push(err); this._errors.unshift(new Error('RetryOperation timeout occurred')); return false; } this._errors.push(err); var timeout = this._timeouts.shift(); if (timeout === undefined) { if (this._cachedTimeouts) { // retry forever, only keep last error this._errors.splice(0, this._errors.length - 1); timeout = this._cachedTimeouts.slice(-1); } else { return false; } } var self = this; this._timer = setTimeout(function() { self._attempts++; if (self._operationTimeoutCb) { self._timeout = setTimeout(function() { self._operationTimeoutCb(self._attempts); }, self._operationTimeout); if (self._options.unref) { self._timeout.unref(); } } self._fn(self._attempts); }, timeout); if (this._options.unref) { this._timer.unref(); } return true; }; RetryOperation.prototype.attempt = function(fn, timeoutOps) { this._fn = fn; if (timeoutOps) { if (timeoutOps.timeout) { this._operationTimeout = timeoutOps.timeout; } if (timeoutOps.cb) { this._operationTimeoutCb = timeoutOps.cb; } } var self = this; if (this._operationTimeoutCb) { this._timeout = setTimeout(function() { self._operationTimeoutCb(); }, self._operationTimeout); } this._operationStart = new Date().getTime(); this._fn(this._attempts); }; RetryOperation.prototype.try = function(fn) { console.log('Using RetryOperation.try() is deprecated'); this.attempt(fn); }; RetryOperation.prototype.start = function(fn) { console.log('Using RetryOperation.start() is deprecated'); this.attempt(fn); }; RetryOperation.prototype.start = RetryOperation.prototype.try; RetryOperation.prototype.errors = function() { return this._errors; }; RetryOperation.prototype.attempts = function() { return this._attempts; }; RetryOperation.prototype.mainError = function() { if (this._errors.length === 0) { return null; } var counts = {}; var mainError = null; var mainErrorCount = 0; for (var i = 0; i < this._errors.length; i++) { var error = this._errors[i]; var message = error.message; var count = (counts[message] || 0) + 1; counts[message] = count; if (count >= mainErrorCount) { mainError = error; mainErrorCount = count; } } return mainError; }; /***/ }), /***/ 3058: /***/ ((module, exports, __nccwpck_require__) => { /* eslint-disable node/no-deprecated-api */ var buffer = __nccwpck_require__(181) var Buffer = buffer.Buffer // alternative to using Object.keys for old browsers function copyProps (src, dst) { for (var key in src) { dst[key] = src[key] } } if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { module.exports = buffer } else { // Copy properties from require('buffer') copyProps(buffer, exports) exports.Buffer = SafeBuffer } function SafeBuffer (arg, encodingOrOffset, length) { return Buffer(arg, encodingOrOffset, length) } // Copy static methods from Buffer copyProps(Buffer, SafeBuffer) SafeBuffer.from = function (arg, encodingOrOffset, length) { if (typeof arg === 'number') { throw new TypeError('Argument must not be a number') } return Buffer(arg, encodingOrOffset, length) } SafeBuffer.alloc = function (size, fill, encoding) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } var buf = Buffer(size) if (fill !== undefined) { if (typeof encoding === 'string') { buf.fill(fill, encoding) } else { buf.fill(fill) } } else { buf.fill(0) } return buf } SafeBuffer.allocUnsafe = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return Buffer(size) } SafeBuffer.allocUnsafeSlow = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return buffer.SlowBuffer(size) } /***/ }), /***/ 2560: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { ;(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 // 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 var buffers = [ 'comment', 'sgmlDecl', 'textNode', 'tagName', 'doctype', 'procInstName', 'procInstBody', 'entity', 'attribName', 'attribValue', 'cdata', 'script' ] sax.EVENTS = [ 'text', 'processinginstruction', 'sgmldeclaration', 'doctype', 'comment', 'opentagstart', 'attribute', 'opentag', 'closetag', 'opencdata', 'cdata', 'closecdata', 'error', 'end', 'ready', 'script', 'opennamespace', 'closenamespace' ] function SAXParser (strict, opt) { if (!(this instanceof SAXParser)) { return new SAXParser(strict, opt) } 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 = [] // 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) } // mostly just for error reporting parser.trackPosition = parser.opt.position !== false if (parser.trackPosition) { parser.position = parser.line = parser.column = 0 } emit(parser, 'onready') } if (!Object.create) { Object.create = function (o) { function F () {} F.prototype = o var newf = new F() return newf } } if (!Object.keys) { Object.keys = function (o) { var a = [] for (var i in o) if (o.hasOwnProperty(i)) a.push(i) return a } } 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 case 'cdata': emitNode(parser, 'oncdata', parser.cdata) parser.cdata = '' break case 'script': emitNode(parser, 'onscript', parser.script) parser.script = '' break default: error(parser, 'Max buffer length exceeded: ' + buffers[i]) } } maxActual = Math.max(maxActual, len) } // schedule the next check for the earliest possible buffer overrun. var m = sax.MAX_BUFFER_LENGTH - maxActual parser.bufferCheckPosition = m + parser.position } function clearBuffers (parser) { for (var i = 0, l = buffers.length; i < l; i++) { parser[buffers[i]] = '' } } function flushBuffers (parser) { closeText(parser) if (parser.cdata !== '') { emitNode(parser, 'oncdata', parser.cdata) parser.cdata = '' } if (parser.script !== '') { emitNode(parser, 'onscript', parser.script) parser.script = '' } } 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) } } var Stream try { Stream = (__nccwpck_require__(2203).Stream) } catch (ex) { Stream = function () {} } var streamWraps = sax.EVENTS.filter(function (ev) { return ev !== 'error' && ev !== 'end' }) function createStream (strict, opt) { return new SAXStream(strict, opt) } function SAXStream (strict, opt) { if (!(this instanceof SAXStream)) { return new SAXStream(strict, opt) } Stream.apply(this) this._parser = new SAXParser(strict, opt) this.writable = true this.readable = true var me = this this._parser.onend = function () { me.emit('end') } this._parser.onerror = function (er) { me.emit('error', er) // if didn't throw, then means error was handled. // go ahead and clear error, so we can write again. me._parser.error = null } this._decoder = null 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 }) }) } SAXStream.prototype = Object.create(Stream.prototype, { constructor: { value: SAXStream } }) SAXStream.prototype.write = function (data) { if (typeof Buffer === 'function' && typeof Buffer.isBuffer === 'function' && Buffer.isBuffer(data)) { if (!this._decoder) { var SD = (__nccwpck_require__(3193).StringDecoder) this._decoder = new SD('utf8') } data = this._decoder.write(data) } this._parser.write(data.toString()) this.emit('data', data) return true } SAXStream.prototype.end = function (chunk) { if (chunk && chunk.length) { this.write(chunk) } this._parser.end() return true } 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) } } return Stream.prototype.on.call(me, ev, handler) } // 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 } // 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]/ 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-]/ 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-]/ function isWhitespace (c) { return c === ' ' || c === '\n' || c === '\r' || c === '\t' } function isQuote (c) { return c === '"' || c === '\'' } function isAttribEnd (c) { return c === '>' || isWhitespace(c) } function isMatch (regex, c) { return regex.test(c) } function notMatch (regex, c) { return !isMatch(regex, c) } 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++, //