/******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 52605: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.create = void 0; const artifact_client_1 = __nccwpck_require__(48802); /** * Constructs an ArtifactClient */ function create() { return artifact_client_1.DefaultArtifactClient.create(); } exports.create = create; //# sourceMappingURL=artifact-client.js.map /***/ }), /***/ 48802: /***/ (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.DefaultArtifactClient = void 0; const core = __importStar(__nccwpck_require__(42186)); const upload_specification_1 = __nccwpck_require__(10183); const upload_http_client_1 = __nccwpck_require__(74354); const utils_1 = __nccwpck_require__(36327); const path_and_artifact_name_validation_1 = __nccwpck_require__(87398); const download_http_client_1 = __nccwpck_require__(8538); const download_specification_1 = __nccwpck_require__(95686); const config_variables_1 = __nccwpck_require__(42222); const path_1 = __nccwpck_require__(71017); class DefaultArtifactClient { /** * Constructs a DefaultArtifactClient */ static create() { return new DefaultArtifactClient(); } /** * Uploads an artifact */ uploadArtifact(name, files, rootDirectory, options) { return __awaiter(this, void 0, void 0, function* () { core.info(`Starting artifact upload For more detailed logs during the artifact upload process, enable step-debugging: https://docs.github.com/actions/monitoring-and-troubleshooting-workflows/enabling-debug-logging#enabling-step-debug-logging`); (0, path_and_artifact_name_validation_1.checkArtifactName)(name); // Get specification for the files being uploaded const uploadSpecification = (0, upload_specification_1.getUploadSpecification)(name, rootDirectory, files); const uploadResponse = { artifactName: name, artifactItems: [], size: 0, failedItems: [] }; const uploadHttpClient = new upload_http_client_1.UploadHttpClient(); if (uploadSpecification.length === 0) { core.warning(`No files found that can be uploaded`); } else { // Create an entry for the artifact in the file container const response = yield uploadHttpClient.createArtifactInFileContainer(name, options); if (!response.fileContainerResourceUrl) { core.debug(response.toString()); throw new Error('No URL provided by the Artifact Service to upload an artifact to'); } core.debug(`Upload Resource URL: ${response.fileContainerResourceUrl}`); core.info(`Container for artifact "${name}" successfully created. Starting upload of file(s)`); // Upload each of the files that were found concurrently const uploadResult = yield uploadHttpClient.uploadArtifactToFileContainer(response.fileContainerResourceUrl, uploadSpecification, options); // Update the size of the artifact to indicate we are done uploading // The uncompressed size is used for display when downloading a zip of the artifact from the UI core.info(`File upload process has finished. Finalizing the artifact upload`); yield uploadHttpClient.patchArtifactSize(uploadResult.totalSize, name); if (uploadResult.failedItems.length > 0) { core.info(`Upload finished. There were ${uploadResult.failedItems.length} items that failed to upload`); } else { core.info(`Artifact has been finalized. All files have been successfully uploaded!`); } core.info(` The raw size of all the files that were specified for upload is ${uploadResult.totalSize} bytes The size of all the files that were uploaded is ${uploadResult.uploadSize} bytes. This takes into account any gzip compression used to reduce the upload size, time and storage Note: The size of downloaded zips can differ significantly from the reported size. For more information see: https://github.com/actions/upload-artifact#zipped-artifact-downloads \r\n`); uploadResponse.artifactItems = uploadSpecification.map(item => item.absoluteFilePath); uploadResponse.size = uploadResult.uploadSize; uploadResponse.failedItems = uploadResult.failedItems; } return uploadResponse; }); } downloadArtifact(name, path, options) { return __awaiter(this, void 0, void 0, function* () { const downloadHttpClient = new download_http_client_1.DownloadHttpClient(); const artifacts = yield downloadHttpClient.listArtifacts(); if (artifacts.count === 0) { throw new Error(`Unable to find any artifacts for the associated workflow`); } const artifactToDownload = artifacts.value.find(artifact => { return artifact.name === name; }); if (!artifactToDownload) { throw new Error(`Unable to find an artifact with the name: ${name}`); } const items = yield downloadHttpClient.getContainerItems(artifactToDownload.name, artifactToDownload.fileContainerResourceUrl); if (!path) { path = (0, config_variables_1.getWorkSpaceDirectory)(); } path = (0, path_1.normalize)(path); path = (0, path_1.resolve)(path); // During upload, empty directories are rejected by the remote server so there should be no artifacts that consist of only empty directories const downloadSpecification = (0, download_specification_1.getDownloadSpecification)(name, items.value, path, (options === null || options === void 0 ? void 0 : options.createArtifactFolder) || false); if (downloadSpecification.filesToDownload.length === 0) { core.info(`No downloadable files were found for the artifact: ${artifactToDownload.name}`); } else { // Create all necessary directories recursively before starting any download yield (0, utils_1.createDirectoriesForArtifact)(downloadSpecification.directoryStructure); core.info('Directory structure has been set up for the artifact'); yield (0, utils_1.createEmptyFilesForArtifact)(downloadSpecification.emptyFilesToCreate); yield downloadHttpClient.downloadSingleArtifact(downloadSpecification.filesToDownload); } return { artifactName: name, downloadPath: downloadSpecification.rootDownloadLocation }; }); } downloadAllArtifacts(path) { return __awaiter(this, void 0, void 0, function* () { const downloadHttpClient = new download_http_client_1.DownloadHttpClient(); const response = []; const artifacts = yield downloadHttpClient.listArtifacts(); if (artifacts.count === 0) { core.info('Unable to find any artifacts for the associated workflow'); return response; } if (!path) { path = (0, config_variables_1.getWorkSpaceDirectory)(); } path = (0, path_1.normalize)(path); path = (0, path_1.resolve)(path); let downloadedArtifacts = 0; while (downloadedArtifacts < artifacts.count) { const currentArtifactToDownload = artifacts.value[downloadedArtifacts]; downloadedArtifacts += 1; core.info(`starting download of artifact ${currentArtifactToDownload.name} : ${downloadedArtifacts}/${artifacts.count}`); // Get container entries for the specific artifact const items = yield downloadHttpClient.getContainerItems(currentArtifactToDownload.name, currentArtifactToDownload.fileContainerResourceUrl); const downloadSpecification = (0, download_specification_1.getDownloadSpecification)(currentArtifactToDownload.name, items.value, path, true); if (downloadSpecification.filesToDownload.length === 0) { core.info(`No downloadable files were found for any artifact ${currentArtifactToDownload.name}`); } else { yield (0, utils_1.createDirectoriesForArtifact)(downloadSpecification.directoryStructure); yield (0, utils_1.createEmptyFilesForArtifact)(downloadSpecification.emptyFilesToCreate); yield downloadHttpClient.downloadSingleArtifact(downloadSpecification.filesToDownload); } response.push({ artifactName: currentArtifactToDownload.name, downloadPath: downloadSpecification.rootDownloadLocation }); } return response; }); } } exports.DefaultArtifactClient = DefaultArtifactClient; //# sourceMappingURL=artifact-client.js.map /***/ }), /***/ 42222: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isGhes = exports.getRetentionDays = exports.getWorkSpaceDirectory = exports.getWorkFlowRunId = exports.getRuntimeUrl = exports.getRuntimeToken = exports.getDownloadFileConcurrency = exports.getInitialRetryIntervalInMilliseconds = exports.getRetryMultiplier = exports.getRetryLimit = exports.getUploadChunkSize = exports.getUploadFileConcurrency = void 0; // The number of concurrent uploads that happens at the same time function getUploadFileConcurrency() { return 2; } exports.getUploadFileConcurrency = getUploadFileConcurrency; // When uploading large files that can't be uploaded with a single http call, this controls // the chunk size that is used during upload function getUploadChunkSize() { return 8 * 1024 * 1024; // 8 MB Chunks } exports.getUploadChunkSize = getUploadChunkSize; // The maximum number of retries that can be attempted before an upload or download fails function getRetryLimit() { return 5; } exports.getRetryLimit = getRetryLimit; // With exponential backoff, the larger the retry count, the larger the wait time before another attempt // The retry multiplier controls by how much the backOff time increases depending on the number of retries function getRetryMultiplier() { return 1.5; } exports.getRetryMultiplier = getRetryMultiplier; // The initial wait time if an upload or download fails and a retry is being attempted for the first time function getInitialRetryIntervalInMilliseconds() { return 3000; } exports.getInitialRetryIntervalInMilliseconds = getInitialRetryIntervalInMilliseconds; // The number of concurrent downloads that happens at the same time function getDownloadFileConcurrency() { return 2; } exports.getDownloadFileConcurrency = getDownloadFileConcurrency; function getRuntimeToken() { const token = process.env['ACTIONS_RUNTIME_TOKEN']; if (!token) { throw new Error('Unable to get ACTIONS_RUNTIME_TOKEN env variable'); } return token; } exports.getRuntimeToken = getRuntimeToken; function getRuntimeUrl() { const runtimeUrl = process.env['ACTIONS_RUNTIME_URL']; if (!runtimeUrl) { throw new Error('Unable to get ACTIONS_RUNTIME_URL env variable'); } return runtimeUrl; } exports.getRuntimeUrl = getRuntimeUrl; function getWorkFlowRunId() { const workFlowRunId = process.env['GITHUB_RUN_ID']; if (!workFlowRunId) { throw new Error('Unable to get GITHUB_RUN_ID env variable'); } return workFlowRunId; } exports.getWorkFlowRunId = getWorkFlowRunId; function getWorkSpaceDirectory() { const workspaceDirectory = process.env['GITHUB_WORKSPACE']; if (!workspaceDirectory) { throw new Error('Unable to get GITHUB_WORKSPACE env variable'); } return workspaceDirectory; } exports.getWorkSpaceDirectory = getWorkSpaceDirectory; function getRetentionDays() { return process.env['GITHUB_RETENTION_DAYS']; } exports.getRetentionDays = getRetentionDays; function isGhes() { const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com'); return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'; } exports.isGhes = isGhes; //# sourceMappingURL=config-variables.js.map /***/ }), /***/ 23549: /***/ ((__unused_webpack_module, exports) => { "use strict"; /** * CRC64: cyclic redundancy check, 64-bits * * In order to validate that artifacts are not being corrupted over the wire, this redundancy check allows us to * validate that there was no corruption during transmission. The implementation here is based on Go's hash/crc64 pkg, * but without the slicing-by-8 optimization: https://cs.opensource.google/go/go/+/master:src/hash/crc64/crc64.go * * This implementation uses a pregenerated table based on 0x9A6C9329AC4BC9B5 as the polynomial, the same polynomial that * is used for Azure Storage: https://github.com/Azure/azure-storage-net/blob/cbe605f9faa01bfc3003d75fc5a16b2eaccfe102/Lib/Common/Core/Util/Crc64.cs#L27 */ Object.defineProperty(exports, "__esModule", ({ value: true })); // when transpile target is >= ES2020 (after dropping node 12) these can be changed to bigint literals - ts(2737) const PREGEN_POLY_TABLE = [ BigInt('0x0000000000000000'), BigInt('0x7F6EF0C830358979'), BigInt('0xFEDDE190606B12F2'), BigInt('0x81B31158505E9B8B'), BigInt('0xC962E5739841B68F'), BigInt('0xB60C15BBA8743FF6'), BigInt('0x37BF04E3F82AA47D'), BigInt('0x48D1F42BC81F2D04'), BigInt('0xA61CECB46814FE75'), BigInt('0xD9721C7C5821770C'), BigInt('0x58C10D24087FEC87'), BigInt('0x27AFFDEC384A65FE'), BigInt('0x6F7E09C7F05548FA'), BigInt('0x1010F90FC060C183'), BigInt('0x91A3E857903E5A08'), BigInt('0xEECD189FA00BD371'), BigInt('0x78E0FF3B88BE6F81'), BigInt('0x078E0FF3B88BE6F8'), BigInt('0x863D1EABE8D57D73'), BigInt('0xF953EE63D8E0F40A'), BigInt('0xB1821A4810FFD90E'), BigInt('0xCEECEA8020CA5077'), BigInt('0x4F5FFBD87094CBFC'), BigInt('0x30310B1040A14285'), BigInt('0xDEFC138FE0AA91F4'), BigInt('0xA192E347D09F188D'), BigInt('0x2021F21F80C18306'), BigInt('0x5F4F02D7B0F40A7F'), BigInt('0x179EF6FC78EB277B'), BigInt('0x68F0063448DEAE02'), BigInt('0xE943176C18803589'), BigInt('0x962DE7A428B5BCF0'), BigInt('0xF1C1FE77117CDF02'), BigInt('0x8EAF0EBF2149567B'), BigInt('0x0F1C1FE77117CDF0'), BigInt('0x7072EF2F41224489'), BigInt('0x38A31B04893D698D'), BigInt('0x47CDEBCCB908E0F4'), BigInt('0xC67EFA94E9567B7F'), BigInt('0xB9100A5CD963F206'), BigInt('0x57DD12C379682177'), BigInt('0x28B3E20B495DA80E'), BigInt('0xA900F35319033385'), BigInt('0xD66E039B2936BAFC'), BigInt('0x9EBFF7B0E12997F8'), BigInt('0xE1D10778D11C1E81'), BigInt('0x606216208142850A'), BigInt('0x1F0CE6E8B1770C73'), BigInt('0x8921014C99C2B083'), BigInt('0xF64FF184A9F739FA'), BigInt('0x77FCE0DCF9A9A271'), BigInt('0x08921014C99C2B08'), BigInt('0x4043E43F0183060C'), BigInt('0x3F2D14F731B68F75'), BigInt('0xBE9E05AF61E814FE'), BigInt('0xC1F0F56751DD9D87'), BigInt('0x2F3DEDF8F1D64EF6'), BigInt('0x50531D30C1E3C78F'), BigInt('0xD1E00C6891BD5C04'), BigInt('0xAE8EFCA0A188D57D'), BigInt('0xE65F088B6997F879'), BigInt('0x9931F84359A27100'), BigInt('0x1882E91B09FCEA8B'), BigInt('0x67EC19D339C963F2'), BigInt('0xD75ADABD7A6E2D6F'), BigInt('0xA8342A754A5BA416'), BigInt('0x29873B2D1A053F9D'), BigInt('0x56E9CBE52A30B6E4'), BigInt('0x1E383FCEE22F9BE0'), BigInt('0x6156CF06D21A1299'), BigInt('0xE0E5DE5E82448912'), BigInt('0x9F8B2E96B271006B'), BigInt('0x71463609127AD31A'), BigInt('0x0E28C6C1224F5A63'), BigInt('0x8F9BD7997211C1E8'), BigInt('0xF0F5275142244891'), BigInt('0xB824D37A8A3B6595'), BigInt('0xC74A23B2BA0EECEC'), BigInt('0x46F932EAEA507767'), BigInt('0x3997C222DA65FE1E'), BigInt('0xAFBA2586F2D042EE'), BigInt('0xD0D4D54EC2E5CB97'), BigInt('0x5167C41692BB501C'), BigInt('0x2E0934DEA28ED965'), BigInt('0x66D8C0F56A91F461'), BigInt('0x19B6303D5AA47D18'), BigInt('0x980521650AFAE693'), BigInt('0xE76BD1AD3ACF6FEA'), BigInt('0x09A6C9329AC4BC9B'), BigInt('0x76C839FAAAF135E2'), BigInt('0xF77B28A2FAAFAE69'), BigInt('0x8815D86ACA9A2710'), BigInt('0xC0C42C4102850A14'), BigInt('0xBFAADC8932B0836D'), BigInt('0x3E19CDD162EE18E6'), BigInt('0x41773D1952DB919F'), BigInt('0x269B24CA6B12F26D'), BigInt('0x59F5D4025B277B14'), BigInt('0xD846C55A0B79E09F'), BigInt('0xA72835923B4C69E6'), BigInt('0xEFF9C1B9F35344E2'), BigInt('0x90973171C366CD9B'), BigInt('0x1124202993385610'), BigInt('0x6E4AD0E1A30DDF69'), BigInt('0x8087C87E03060C18'), BigInt('0xFFE938B633338561'), BigInt('0x7E5A29EE636D1EEA'), BigInt('0x0134D92653589793'), BigInt('0x49E52D0D9B47BA97'), BigInt('0x368BDDC5AB7233EE'), BigInt('0xB738CC9DFB2CA865'), BigInt('0xC8563C55CB19211C'), BigInt('0x5E7BDBF1E3AC9DEC'), BigInt('0x21152B39D3991495'), BigInt('0xA0A63A6183C78F1E'), BigInt('0xDFC8CAA9B3F20667'), BigInt('0x97193E827BED2B63'), BigInt('0xE877CE4A4BD8A21A'), BigInt('0x69C4DF121B863991'), BigInt('0x16AA2FDA2BB3B0E8'), BigInt('0xF86737458BB86399'), BigInt('0x8709C78DBB8DEAE0'), BigInt('0x06BAD6D5EBD3716B'), BigInt('0x79D4261DDBE6F812'), BigInt('0x3105D23613F9D516'), BigInt('0x4E6B22FE23CC5C6F'), BigInt('0xCFD833A67392C7E4'), BigInt('0xB0B6C36E43A74E9D'), BigInt('0x9A6C9329AC4BC9B5'), BigInt('0xE50263E19C7E40CC'), BigInt('0x64B172B9CC20DB47'), BigInt('0x1BDF8271FC15523E'), BigInt('0x530E765A340A7F3A'), BigInt('0x2C608692043FF643'), BigInt('0xADD397CA54616DC8'), BigInt('0xD2BD67026454E4B1'), BigInt('0x3C707F9DC45F37C0'), BigInt('0x431E8F55F46ABEB9'), BigInt('0xC2AD9E0DA4342532'), BigInt('0xBDC36EC59401AC4B'), BigInt('0xF5129AEE5C1E814F'), BigInt('0x8A7C6A266C2B0836'), BigInt('0x0BCF7B7E3C7593BD'), BigInt('0x74A18BB60C401AC4'), BigInt('0xE28C6C1224F5A634'), BigInt('0x9DE29CDA14C02F4D'), BigInt('0x1C518D82449EB4C6'), BigInt('0x633F7D4A74AB3DBF'), BigInt('0x2BEE8961BCB410BB'), BigInt('0x548079A98C8199C2'), BigInt('0xD53368F1DCDF0249'), BigInt('0xAA5D9839ECEA8B30'), BigInt('0x449080A64CE15841'), BigInt('0x3BFE706E7CD4D138'), BigInt('0xBA4D61362C8A4AB3'), BigInt('0xC52391FE1CBFC3CA'), BigInt('0x8DF265D5D4A0EECE'), BigInt('0xF29C951DE49567B7'), BigInt('0x732F8445B4CBFC3C'), BigInt('0x0C41748D84FE7545'), BigInt('0x6BAD6D5EBD3716B7'), BigInt('0x14C39D968D029FCE'), BigInt('0x95708CCEDD5C0445'), BigInt('0xEA1E7C06ED698D3C'), BigInt('0xA2CF882D2576A038'), BigInt('0xDDA178E515432941'), BigInt('0x5C1269BD451DB2CA'), BigInt('0x237C997575283BB3'), BigInt('0xCDB181EAD523E8C2'), BigInt('0xB2DF7122E51661BB'), BigInt('0x336C607AB548FA30'), BigInt('0x4C0290B2857D7349'), BigInt('0x04D364994D625E4D'), BigInt('0x7BBD94517D57D734'), BigInt('0xFA0E85092D094CBF'), BigInt('0x856075C11D3CC5C6'), BigInt('0x134D926535897936'), BigInt('0x6C2362AD05BCF04F'), BigInt('0xED9073F555E26BC4'), BigInt('0x92FE833D65D7E2BD'), BigInt('0xDA2F7716ADC8CFB9'), BigInt('0xA54187DE9DFD46C0'), BigInt('0x24F29686CDA3DD4B'), BigInt('0x5B9C664EFD965432'), BigInt('0xB5517ED15D9D8743'), BigInt('0xCA3F8E196DA80E3A'), BigInt('0x4B8C9F413DF695B1'), BigInt('0x34E26F890DC31CC8'), BigInt('0x7C339BA2C5DC31CC'), BigInt('0x035D6B6AF5E9B8B5'), BigInt('0x82EE7A32A5B7233E'), BigInt('0xFD808AFA9582AA47'), BigInt('0x4D364994D625E4DA'), BigInt('0x3258B95CE6106DA3'), BigInt('0xB3EBA804B64EF628'), BigInt('0xCC8558CC867B7F51'), BigInt('0x8454ACE74E645255'), BigInt('0xFB3A5C2F7E51DB2C'), BigInt('0x7A894D772E0F40A7'), BigInt('0x05E7BDBF1E3AC9DE'), BigInt('0xEB2AA520BE311AAF'), BigInt('0x944455E88E0493D6'), BigInt('0x15F744B0DE5A085D'), BigInt('0x6A99B478EE6F8124'), BigInt('0x224840532670AC20'), BigInt('0x5D26B09B16452559'), BigInt('0xDC95A1C3461BBED2'), BigInt('0xA3FB510B762E37AB'), BigInt('0x35D6B6AF5E9B8B5B'), BigInt('0x4AB846676EAE0222'), BigInt('0xCB0B573F3EF099A9'), BigInt('0xB465A7F70EC510D0'), BigInt('0xFCB453DCC6DA3DD4'), BigInt('0x83DAA314F6EFB4AD'), BigInt('0x0269B24CA6B12F26'), BigInt('0x7D0742849684A65F'), BigInt('0x93CA5A1B368F752E'), BigInt('0xECA4AAD306BAFC57'), BigInt('0x6D17BB8B56E467DC'), BigInt('0x12794B4366D1EEA5'), BigInt('0x5AA8BF68AECEC3A1'), BigInt('0x25C64FA09EFB4AD8'), BigInt('0xA4755EF8CEA5D153'), BigInt('0xDB1BAE30FE90582A'), BigInt('0xBCF7B7E3C7593BD8'), BigInt('0xC399472BF76CB2A1'), BigInt('0x422A5673A732292A'), BigInt('0x3D44A6BB9707A053'), BigInt('0x759552905F188D57'), BigInt('0x0AFBA2586F2D042E'), BigInt('0x8B48B3003F739FA5'), BigInt('0xF42643C80F4616DC'), BigInt('0x1AEB5B57AF4DC5AD'), BigInt('0x6585AB9F9F784CD4'), BigInt('0xE436BAC7CF26D75F'), BigInt('0x9B584A0FFF135E26'), BigInt('0xD389BE24370C7322'), BigInt('0xACE74EEC0739FA5B'), BigInt('0x2D545FB4576761D0'), BigInt('0x523AAF7C6752E8A9'), BigInt('0xC41748D84FE75459'), BigInt('0xBB79B8107FD2DD20'), BigInt('0x3ACAA9482F8C46AB'), BigInt('0x45A459801FB9CFD2'), BigInt('0x0D75ADABD7A6E2D6'), BigInt('0x721B5D63E7936BAF'), BigInt('0xF3A84C3BB7CDF024'), BigInt('0x8CC6BCF387F8795D'), BigInt('0x620BA46C27F3AA2C'), BigInt('0x1D6554A417C62355'), BigInt('0x9CD645FC4798B8DE'), BigInt('0xE3B8B53477AD31A7'), BigInt('0xAB69411FBFB21CA3'), BigInt('0xD407B1D78F8795DA'), BigInt('0x55B4A08FDFD90E51'), BigInt('0x2ADA5047EFEC8728') ]; class CRC64 { constructor() { this._crc = BigInt(0); } update(data) { const buffer = typeof data === 'string' ? Buffer.from(data) : data; let crc = CRC64.flip64Bits(this._crc); for (const dataByte of buffer) { const crcByte = Number(crc & BigInt(0xff)); crc = PREGEN_POLY_TABLE[crcByte ^ dataByte] ^ (crc >> BigInt(8)); } this._crc = CRC64.flip64Bits(crc); } digest(encoding) { switch (encoding) { case 'hex': return this._crc.toString(16).toUpperCase(); case 'base64': return this.toBuffer().toString('base64'); default: return this.toBuffer(); } } toBuffer() { return Buffer.from([0, 8, 16, 24, 32, 40, 48, 56].map(s => Number((this._crc >> BigInt(s)) & BigInt(0xff)))); } static flip64Bits(n) { return (BigInt(1) << BigInt(64)) - BigInt(1) - n; } } exports["default"] = CRC64; //# sourceMappingURL=crc64.js.map /***/ }), /***/ 8538: /***/ (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.DownloadHttpClient = void 0; const fs = __importStar(__nccwpck_require__(57147)); const core = __importStar(__nccwpck_require__(42186)); const zlib = __importStar(__nccwpck_require__(59796)); const utils_1 = __nccwpck_require__(36327); const url_1 = __nccwpck_require__(57310); const status_reporter_1 = __nccwpck_require__(39081); const perf_hooks_1 = __nccwpck_require__(4074); const http_manager_1 = __nccwpck_require__(16527); const config_variables_1 = __nccwpck_require__(42222); const requestUtils_1 = __nccwpck_require__(90755); class DownloadHttpClient { constructor() { this.downloadHttpManager = new http_manager_1.HttpManager((0, config_variables_1.getDownloadFileConcurrency)(), '@actions/artifact-download'); // downloads are usually significantly faster than uploads so display status information every second this.statusReporter = new status_reporter_1.StatusReporter(1000); } /** * Gets a list of all artifacts that are in a specific container */ listArtifacts() { return __awaiter(this, void 0, void 0, function* () { const artifactUrl = (0, utils_1.getArtifactUrl)(); // use the first client from the httpManager, `keep-alive` is not used so the connection will close immediately const client = this.downloadHttpManager.getClient(0); const headers = (0, utils_1.getDownloadHeaders)('application/json'); const response = yield (0, requestUtils_1.retryHttpClientRequest)('List Artifacts', () => __awaiter(this, void 0, void 0, function* () { return client.get(artifactUrl, headers); })); const body = yield response.readBody(); return JSON.parse(body); }); } /** * Fetches a set of container items that describe the contents of an artifact * @param artifactName the name of the artifact * @param containerUrl the artifact container URL for the run */ getContainerItems(artifactName, containerUrl) { return __awaiter(this, void 0, void 0, function* () { // the itemPath search parameter controls which containers will be returned const resourceUrl = new url_1.URL(containerUrl); resourceUrl.searchParams.append('itemPath', artifactName); // use the first client from the httpManager, `keep-alive` is not used so the connection will close immediately const client = this.downloadHttpManager.getClient(0); const headers = (0, utils_1.getDownloadHeaders)('application/json'); const response = yield (0, requestUtils_1.retryHttpClientRequest)('Get Container Items', () => __awaiter(this, void 0, void 0, function* () { return client.get(resourceUrl.toString(), headers); })); const body = yield response.readBody(); return JSON.parse(body); }); } /** * Concurrently downloads all the files that are part of an artifact * @param downloadItems information about what items to download and where to save them */ downloadSingleArtifact(downloadItems) { return __awaiter(this, void 0, void 0, function* () { const DOWNLOAD_CONCURRENCY = (0, config_variables_1.getDownloadFileConcurrency)(); // limit the number of files downloaded at a single time core.debug(`Download file concurrency is set to ${DOWNLOAD_CONCURRENCY}`); const parallelDownloads = [...new Array(DOWNLOAD_CONCURRENCY).keys()]; let currentFile = 0; let downloadedFiles = 0; core.info(`Total number of files that will be downloaded: ${downloadItems.length}`); this.statusReporter.setTotalNumberOfFilesToProcess(downloadItems.length); this.statusReporter.start(); yield Promise.all(parallelDownloads.map((index) => __awaiter(this, void 0, void 0, function* () { while (currentFile < downloadItems.length) { const currentFileToDownload = downloadItems[currentFile]; currentFile += 1; const startTime = perf_hooks_1.performance.now(); yield this.downloadIndividualFile(index, currentFileToDownload.sourceLocation, currentFileToDownload.targetPath); if (core.isDebug()) { core.debug(`File: ${++downloadedFiles}/${downloadItems.length}. ${currentFileToDownload.targetPath} took ${(perf_hooks_1.performance.now() - startTime).toFixed(3)} milliseconds to finish downloading`); } this.statusReporter.incrementProcessedCount(); } }))) .catch(error => { throw new Error(`Unable to download the artifact: ${error}`); }) .finally(() => { this.statusReporter.stop(); // safety dispose all connections this.downloadHttpManager.disposeAndReplaceAllClients(); }); }); } /** * Downloads an individual file * @param httpClientIndex the index of the http client that is used to make all of the calls * @param artifactLocation origin location where a file will be downloaded from * @param downloadPath destination location for the file being downloaded */ downloadIndividualFile(httpClientIndex, artifactLocation, downloadPath) { return __awaiter(this, void 0, void 0, function* () { let retryCount = 0; const retryLimit = (0, config_variables_1.getRetryLimit)(); let destinationStream = fs.createWriteStream(downloadPath); const headers = (0, utils_1.getDownloadHeaders)('application/json', true, true); // a single GET request is used to download a file const makeDownloadRequest = () => __awaiter(this, void 0, void 0, function* () { const client = this.downloadHttpManager.getClient(httpClientIndex); return yield client.get(artifactLocation, headers); }); // check the response headers to determine if the file was compressed using gzip const isGzip = (incomingHeaders) => { return ('content-encoding' in incomingHeaders && incomingHeaders['content-encoding'] === 'gzip'); }; // Increments the current retry count and then checks if the retry limit has been reached // If there have been too many retries, fail so the download stops. If there is a retryAfterValue value provided, // it will be used const backOff = (retryAfterValue) => __awaiter(this, void 0, void 0, function* () { retryCount++; if (retryCount > retryLimit) { return Promise.reject(new Error(`Retry limit has been reached. Unable to download ${artifactLocation}`)); } else { this.downloadHttpManager.disposeAndReplaceClient(httpClientIndex); if (retryAfterValue) { // Back off by waiting the specified time denoted by the retry-after header core.info(`Backoff due to too many requests, retry #${retryCount}. Waiting for ${retryAfterValue} milliseconds before continuing the download`); yield (0, utils_1.sleep)(retryAfterValue); } else { // Back off using an exponential value that depends on the retry count const backoffTime = (0, utils_1.getExponentialRetryTimeInMilliseconds)(retryCount); core.info(`Exponential backoff for retry #${retryCount}. Waiting for ${backoffTime} milliseconds before continuing the download`); yield (0, utils_1.sleep)(backoffTime); } core.info(`Finished backoff for retry #${retryCount}, continuing with download`); } }); const isAllBytesReceived = (expected, received) => { // be lenient, if any input is missing, assume success, i.e. not truncated if (!expected || !received || process.env['ACTIONS_ARTIFACT_SKIP_DOWNLOAD_VALIDATION']) { core.info('Skipping download validation.'); return true; } return parseInt(expected) === received; }; const resetDestinationStream = (fileDownloadPath) => __awaiter(this, void 0, void 0, function* () { destinationStream.close(); // await until file is created at downloadpath; node15 and up fs.createWriteStream had not created a file yet yield new Promise(resolve => { destinationStream.on('close', resolve); if (destinationStream.writableFinished) { resolve(); } }); yield (0, utils_1.rmFile)(fileDownloadPath); destinationStream = fs.createWriteStream(fileDownloadPath); }); // keep trying to download a file until a retry limit has been reached while (retryCount <= retryLimit) { let response; try { response = yield makeDownloadRequest(); } catch (error) { // if an error is caught, it is usually indicative of a timeout so retry the download core.info('An error occurred while attempting to download a file'); // eslint-disable-next-line no-console console.log(error); // increment the retryCount and use exponential backoff to wait before making the next request yield backOff(); continue; } let forceRetry = false; if ((0, utils_1.isSuccessStatusCode)(response.message.statusCode)) { // The body contains the contents of the file however calling response.readBody() causes all the content to be converted to a string // which can cause some gzip encoded data to be lost // Instead of using response.readBody(), response.message is a readableStream that can be directly used to get the raw body contents try { const isGzipped = isGzip(response.message.headers); yield this.pipeResponseToFile(response, destinationStream, isGzipped); if (isGzipped || isAllBytesReceived(response.message.headers['content-length'], yield (0, utils_1.getFileSize)(downloadPath))) { return; } else { forceRetry = true; } } catch (error) { // retry on error, most likely streams were corrupted forceRetry = true; } } if (forceRetry || (0, utils_1.isRetryableStatusCode)(response.message.statusCode)) { core.info(`A ${response.message.statusCode} response code has been received while attempting to download an artifact`); resetDestinationStream(downloadPath); // if a throttled status code is received, try to get the retryAfter header value, else differ to standard exponential backoff (0, utils_1.isThrottledStatusCode)(response.message.statusCode) ? yield backOff((0, utils_1.tryGetRetryAfterValueTimeInMilliseconds)(response.message.headers)) : yield backOff(); } else { // Some unexpected response code, fail immediately and stop the download (0, utils_1.displayHttpDiagnostics)(response); return Promise.reject(new Error(`Unexpected http ${response.message.statusCode} during download for ${artifactLocation}`)); } } }); } /** * Pipes the response from downloading an individual file to the appropriate destination stream while decoding gzip content if necessary * @param response the http response received when downloading a file * @param destinationStream the stream where the file should be written to * @param isGzip a boolean denoting if the content is compressed using gzip and if we need to decode it */ pipeResponseToFile(response, destinationStream, isGzip) { return __awaiter(this, void 0, void 0, function* () { yield new Promise((resolve, reject) => { if (isGzip) { const gunzip = zlib.createGunzip(); response.message .on('error', error => { core.info(`An error occurred while attempting to read the response stream`); gunzip.close(); destinationStream.close(); reject(error); }) .pipe(gunzip) .on('error', error => { core.info(`An error occurred while attempting to decompress the response stream`); destinationStream.close(); reject(error); }) .pipe(destinationStream) .on('close', () => { resolve(); }) .on('error', error => { core.info(`An error occurred while writing a downloaded file to ${destinationStream.path}`); reject(error); }); } else { response.message .on('error', error => { core.info(`An error occurred while attempting to read the response stream`); destinationStream.close(); reject(error); }) .pipe(destinationStream) .on('close', () => { resolve(); }) .on('error', error => { core.info(`An error occurred while writing a downloaded file to ${destinationStream.path}`); reject(error); }); } }); return; }); } } exports.DownloadHttpClient = DownloadHttpClient; //# sourceMappingURL=download-http-client.js.map /***/ }), /***/ 95686: /***/ (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.getDownloadSpecification = void 0; const path = __importStar(__nccwpck_require__(71017)); /** * Creates a specification for a set of files that will be downloaded * @param artifactName the name of the artifact * @param artifactEntries a set of container entries that describe that files that make up an artifact * @param downloadPath the path where the artifact will be downloaded to * @param includeRootDirectory specifies if there should be an extra directory (denoted by the artifact name) where the artifact files should be downloaded to */ function getDownloadSpecification(artifactName, artifactEntries, downloadPath, includeRootDirectory) { // use a set for the directory paths so that there are no duplicates const directories = new Set(); const specifications = { rootDownloadLocation: includeRootDirectory ? path.join(downloadPath, artifactName) : downloadPath, directoryStructure: [], emptyFilesToCreate: [], filesToDownload: [] }; for (const entry of artifactEntries) { // Ignore artifacts in the container that don't begin with the same name if (entry.path.startsWith(`${artifactName}/`) || entry.path.startsWith(`${artifactName}\\`)) { // normalize all separators to the local OS const normalizedPathEntry = path.normalize(entry.path); // entry.path always starts with the artifact name, if includeRootDirectory is false, remove the name from the beginning of the path const filePath = path.join(downloadPath, includeRootDirectory ? normalizedPathEntry : normalizedPathEntry.replace(artifactName, '')); // Case insensitive folder structure maintained in the backend, not every folder is created so the 'folder' // itemType cannot be relied upon. The file must be used to determine the directory structure if (entry.itemType === 'file') { // Get the directories that we need to create from the filePath for each individual file directories.add(path.dirname(filePath)); if (entry.fileLength === 0) { // An empty file was uploaded, create the empty files locally so that no extra http calls are made specifications.emptyFilesToCreate.push(filePath); } else { specifications.filesToDownload.push({ sourceLocation: entry.contentLocation, targetPath: filePath }); } } } } specifications.directoryStructure = Array.from(directories); return specifications; } exports.getDownloadSpecification = getDownloadSpecification; //# sourceMappingURL=download-specification.js.map /***/ }), /***/ 16527: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.HttpManager = void 0; const utils_1 = __nccwpck_require__(36327); /** * Used for managing http clients during either upload or download */ class HttpManager { constructor(clientCount, userAgent) { if (clientCount < 1) { throw new Error('There must be at least one client'); } this.userAgent = userAgent; this.clients = new Array(clientCount).fill((0, utils_1.createHttpClient)(userAgent)); } getClient(index) { return this.clients[index]; } // client disposal is necessary if a keep-alive connection is used to properly close the connection // for more information see: https://github.com/actions/http-client/blob/04e5ad73cd3fd1f5610a32116b0759eddf6570d2/index.ts#L292 disposeAndReplaceClient(index) { this.clients[index].dispose(); this.clients[index] = (0, utils_1.createHttpClient)(this.userAgent); } disposeAndReplaceAllClients() { for (const [index] of this.clients.entries()) { this.disposeAndReplaceClient(index); } } } exports.HttpManager = HttpManager; //# sourceMappingURL=http-manager.js.map /***/ }), /***/ 87398: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.checkArtifactFilePath = exports.checkArtifactName = void 0; const core_1 = __nccwpck_require__(42186); /** * Invalid characters that cannot be in the artifact name or an uploaded file. Will be rejected * from the server if attempted to be sent over. These characters are not allowed due to limitations with certain * file systems such as NTFS. To maintain platform-agnostic behavior, all characters that are not supported by an * individual filesystem/platform will not be supported on all fileSystems/platforms * * FilePaths can include characters such as \ and / which are not permitted in the artifact name alone */ const invalidArtifactFilePathCharacters = new Map([ ['"', ' Double quote "'], [':', ' Colon :'], ['<', ' Less than <'], ['>', ' Greater than >'], ['|', ' Vertical bar |'], ['*', ' Asterisk *'], ['?', ' Question mark ?'], ['\r', ' Carriage return \\r'], ['\n', ' Line feed \\n'] ]); const invalidArtifactNameCharacters = new Map([ ...invalidArtifactFilePathCharacters, ['\\', ' Backslash \\'], ['/', ' Forward slash /'] ]); /** * Scans the name of the artifact to make sure there are no illegal characters */ function checkArtifactName(name) { if (!name) { throw new Error(`Artifact name: ${name}, is incorrectly provided`); } for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactNameCharacters) { if (name.includes(invalidCharacterKey)) { throw new Error(`Artifact name is not valid: ${name}. Contains the following character: ${errorMessageForCharacter} Invalid characters include: ${Array.from(invalidArtifactNameCharacters.values()).toString()} These characters are not allowed in the artifact name due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems.`); } } (0, core_1.info)(`Artifact name is valid!`); } exports.checkArtifactName = checkArtifactName; /** * Scans the name of the filePath used to make sure there are no illegal characters */ function checkArtifactFilePath(path) { if (!path) { throw new Error(`Artifact path: ${path}, is incorrectly provided`); } for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactFilePathCharacters) { if (path.includes(invalidCharacterKey)) { throw new Error(`Artifact path is not valid: ${path}. Contains the following character: ${errorMessageForCharacter} Invalid characters include: ${Array.from(invalidArtifactFilePathCharacters.values()).toString()} The following characters are not allowed in files that are uploaded due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems. `); } } } exports.checkArtifactFilePath = checkArtifactFilePath; //# sourceMappingURL=path-and-artifact-name-validation.js.map /***/ }), /***/ 90755: /***/ (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.retryHttpClientRequest = exports.retry = void 0; const utils_1 = __nccwpck_require__(36327); const core = __importStar(__nccwpck_require__(42186)); const config_variables_1 = __nccwpck_require__(42222); function retry(name, operation, customErrorMessages, maxAttempts) { return __awaiter(this, void 0, void 0, function* () { let response = undefined; let statusCode = undefined; let isRetryable = false; let errorMessage = ''; let customErrorInformation = undefined; let attempt = 1; while (attempt <= maxAttempts) { try { response = yield operation(); statusCode = response.message.statusCode; if ((0, utils_1.isSuccessStatusCode)(statusCode)) { return response; } // Extra error information that we want to display if a particular response code is hit if (statusCode) { customErrorInformation = customErrorMessages.get(statusCode); } isRetryable = (0, utils_1.isRetryableStatusCode)(statusCode); errorMessage = `Artifact service responded with ${statusCode}`; } catch (error) { isRetryable = true; errorMessage = error.message; } if (!isRetryable) { core.info(`${name} - Error is not retryable`); if (response) { (0, utils_1.displayHttpDiagnostics)(response); } break; } core.info(`${name} - Attempt ${attempt} of ${maxAttempts} failed with error: ${errorMessage}`); yield (0, utils_1.sleep)((0, utils_1.getExponentialRetryTimeInMilliseconds)(attempt)); attempt++; } if (response) { (0, utils_1.displayHttpDiagnostics)(response); } if (customErrorInformation) { throw Error(`${name} failed: ${customErrorInformation}`); } throw Error(`${name} failed: ${errorMessage}`); }); } exports.retry = retry; function retryHttpClientRequest(name, method, customErrorMessages = new Map(), maxAttempts = (0, config_variables_1.getRetryLimit)()) { return __awaiter(this, void 0, void 0, function* () { return yield retry(name, method, customErrorMessages, maxAttempts); }); } exports.retryHttpClientRequest = retryHttpClientRequest; //# sourceMappingURL=requestUtils.js.map /***/ }), /***/ 39081: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.StatusReporter = void 0; const core_1 = __nccwpck_require__(42186); /** * Status Reporter that displays information about the progress/status of an artifact that is being uploaded or downloaded * * Variable display time that can be adjusted using the displayFrequencyInMilliseconds variable * The total status of the upload/download gets displayed according to this value * If there is a large file that is being uploaded, extra information about the individual status can also be displayed using the updateLargeFileStatus function */ class StatusReporter { constructor(displayFrequencyInMilliseconds) { this.totalNumberOfFilesToProcess = 0; this.processedCount = 0; this.largeFiles = new Map(); this.totalFileStatus = undefined; this.displayFrequencyInMilliseconds = displayFrequencyInMilliseconds; } setTotalNumberOfFilesToProcess(fileTotal) { this.totalNumberOfFilesToProcess = fileTotal; this.processedCount = 0; } start() { // displays information about the total upload/download status this.totalFileStatus = setInterval(() => { // display 1 decimal place without any rounding const percentage = this.formatPercentage(this.processedCount, this.totalNumberOfFilesToProcess); (0, core_1.info)(`Total file count: ${this.totalNumberOfFilesToProcess} ---- Processed file #${this.processedCount} (${percentage.slice(0, percentage.indexOf('.') + 2)}%)`); }, this.displayFrequencyInMilliseconds); } // if there is a large file that is being uploaded in chunks, this is used to display extra information about the status of the upload updateLargeFileStatus(fileName, chunkStartIndex, chunkEndIndex, totalUploadFileSize) { // display 1 decimal place without any rounding const percentage = this.formatPercentage(chunkEndIndex, totalUploadFileSize); (0, core_1.info)(`Uploaded ${fileName} (${percentage.slice(0, percentage.indexOf('.') + 2)}%) bytes ${chunkStartIndex}:${chunkEndIndex}`); } stop() { if (this.totalFileStatus) { clearInterval(this.totalFileStatus); } } incrementProcessedCount() { this.processedCount++; } formatPercentage(numerator, denominator) { // toFixed() rounds, so use extra precision to display accurate information even though 4 decimal places are not displayed return ((numerator / denominator) * 100).toFixed(4).toString(); } } exports.StatusReporter = StatusReporter; //# sourceMappingURL=status-reporter.js.map /***/ }), /***/ 40606: /***/ (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.createGZipFileInBuffer = exports.createGZipFileOnDisk = void 0; const fs = __importStar(__nccwpck_require__(57147)); const zlib = __importStar(__nccwpck_require__(59796)); const util_1 = __nccwpck_require__(73837); const stat = (0, util_1.promisify)(fs.stat); /** * GZipping certain files that are already compressed will likely not yield further size reductions. Creating large temporary gzip * files then will just waste a lot of time before ultimately being discarded (especially for very large files). * If any of these types of files are encountered then on-disk gzip creation will be skipped and the original file will be uploaded as-is */ const gzipExemptFileExtensions = [ '.gz', '.gzip', '.tgz', '.taz', '.Z', '.taZ', '.bz2', '.tbz', '.tbz2', '.tz2', '.lz', '.lzma', '.tlz', '.lzo', '.xz', '.txz', '.zst', '.zstd', '.tzst', '.zip', '.7z' // 7ZIP ]; /** * Creates a Gzip compressed file of an original file at the provided temporary filepath location * @param {string} originalFilePath filepath of whatever will be compressed. The original file will be unmodified * @param {string} tempFilePath the location of where the Gzip file will be created * @returns the size of gzip file that gets created */ function createGZipFileOnDisk(originalFilePath, tempFilePath) { return __awaiter(this, void 0, void 0, function* () { for (const gzipExemptExtension of gzipExemptFileExtensions) { if (originalFilePath.endsWith(gzipExemptExtension)) { // return a really large number so that the original file gets uploaded return Number.MAX_SAFE_INTEGER; } } return new Promise((resolve, reject) => { const inputStream = fs.createReadStream(originalFilePath); const gzip = zlib.createGzip(); const outputStream = fs.createWriteStream(tempFilePath); inputStream.pipe(gzip).pipe(outputStream); outputStream.on('finish', () => __awaiter(this, void 0, void 0, function* () { // wait for stream to finish before calculating the size which is needed as part of the Content-Length header when starting an upload const size = (yield stat(tempFilePath)).size; resolve(size); })); outputStream.on('error', error => { // eslint-disable-next-line no-console console.log(error); reject(error); }); }); }); } exports.createGZipFileOnDisk = createGZipFileOnDisk; /** * Creates a GZip file in memory using a buffer. Should be used for smaller files to reduce disk I/O * @param originalFilePath the path to the original file that is being GZipped * @returns a buffer with the GZip file */ function createGZipFileInBuffer(originalFilePath) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { var _a, e_1, _b, _c; const inputStream = fs.createReadStream(originalFilePath); const gzip = zlib.createGzip(); inputStream.pipe(gzip); // read stream into buffer, using experimental async iterators see https://github.com/nodejs/readable-stream/issues/403#issuecomment-479069043 const chunks = []; try { for (var _d = true, gzip_1 = __asyncValues(gzip), gzip_1_1; gzip_1_1 = yield gzip_1.next(), _a = gzip_1_1.done, !_a;) { _c = gzip_1_1.value; _d = false; try { const chunk = _c; chunks.push(chunk); } finally { _d = true; } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (!_d && !_a && (_b = gzip_1.return)) yield _b.call(gzip_1); } finally { if (e_1) throw e_1.error; } } resolve(Buffer.concat(chunks)); })); }); } exports.createGZipFileInBuffer = createGZipFileInBuffer; //# sourceMappingURL=upload-gzip.js.map /***/ }), /***/ 74354: /***/ (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.UploadHttpClient = void 0; const fs = __importStar(__nccwpck_require__(57147)); const core = __importStar(__nccwpck_require__(42186)); const tmp = __importStar(__nccwpck_require__(68065)); const stream = __importStar(__nccwpck_require__(12781)); const utils_1 = __nccwpck_require__(36327); const config_variables_1 = __nccwpck_require__(42222); const util_1 = __nccwpck_require__(73837); const url_1 = __nccwpck_require__(57310); const perf_hooks_1 = __nccwpck_require__(4074); const status_reporter_1 = __nccwpck_require__(39081); const http_client_1 = __nccwpck_require__(96255); const http_manager_1 = __nccwpck_require__(16527); const upload_gzip_1 = __nccwpck_require__(40606); const requestUtils_1 = __nccwpck_require__(90755); const stat = (0, util_1.promisify)(fs.stat); class UploadHttpClient { constructor() { this.uploadHttpManager = new http_manager_1.HttpManager((0, config_variables_1.getUploadFileConcurrency)(), '@actions/artifact-upload'); this.statusReporter = new status_reporter_1.StatusReporter(10000); } /** * Creates a file container for the new artifact in the remote blob storage/file service * @param {string} artifactName Name of the artifact being created * @returns The response from the Artifact Service if the file container was successfully created */ createArtifactInFileContainer(artifactName, options) { return __awaiter(this, void 0, void 0, function* () { const parameters = { Type: 'actions_storage', Name: artifactName }; // calculate retention period if (options && options.retentionDays) { const maxRetentionStr = (0, config_variables_1.getRetentionDays)(); parameters.RetentionDays = (0, utils_1.getProperRetention)(options.retentionDays, maxRetentionStr); } const data = JSON.stringify(parameters, null, 2); const artifactUrl = (0, utils_1.getArtifactUrl)(); // use the first client from the httpManager, `keep-alive` is not used so the connection will close immediately const client = this.uploadHttpManager.getClient(0); const headers = (0, utils_1.getUploadHeaders)('application/json', false); // Extra information to display when a particular HTTP code is returned // If a 403 is returned when trying to create a file container, the customer has exceeded // their storage quota so no new artifact containers can be created const customErrorMessages = new Map([ [ http_client_1.HttpCodes.Forbidden, (0, config_variables_1.isGhes)() ? 'Please reference [Enabling GitHub Actions for GitHub Enterprise Server](https://docs.github.com/en/enterprise-server@3.8/admin/github-actions/enabling-github-actions-for-github-enterprise-server) to ensure Actions storage is configured correctly.' : 'Artifact storage quota has been hit. Unable to upload any new artifacts' ], [ http_client_1.HttpCodes.BadRequest, `The artifact name ${artifactName} is not valid. Request URL ${artifactUrl}` ] ]); const response = yield (0, requestUtils_1.retryHttpClientRequest)('Create Artifact Container', () => __awaiter(this, void 0, void 0, function* () { return client.post(artifactUrl, data, headers); }), customErrorMessages); const body = yield response.readBody(); return JSON.parse(body); }); } /** * Concurrently upload all of the files in chunks * @param {string} uploadUrl Base Url for the artifact that was created * @param {SearchResult[]} filesToUpload A list of information about the files being uploaded * @returns The size of all the files uploaded in bytes */ uploadArtifactToFileContainer(uploadUrl, filesToUpload, options) { return __awaiter(this, void 0, void 0, function* () { const FILE_CONCURRENCY = (0, config_variables_1.getUploadFileConcurrency)(); const MAX_CHUNK_SIZE = (0, config_variables_1.getUploadChunkSize)(); core.debug(`File Concurrency: ${FILE_CONCURRENCY}, and Chunk Size: ${MAX_CHUNK_SIZE}`); const parameters = []; // by default, file uploads will continue if there is an error unless specified differently in the options let continueOnError = true; if (options) { if (options.continueOnError === false) { continueOnError = false; } } // prepare the necessary parameters to upload all the files for (const file of filesToUpload) { const resourceUrl = new url_1.URL(uploadUrl); resourceUrl.searchParams.append('itemPath', file.uploadFilePath); parameters.push({ file: file.absoluteFilePath, resourceUrl: resourceUrl.toString(), maxChunkSize: MAX_CHUNK_SIZE, continueOnError }); } const parallelUploads = [...new Array(FILE_CONCURRENCY).keys()]; const failedItemsToReport = []; let currentFile = 0; let completedFiles = 0; let uploadFileSize = 0; let totalFileSize = 0; let abortPendingFileUploads = false; this.statusReporter.setTotalNumberOfFilesToProcess(filesToUpload.length); this.statusReporter.start(); // only allow a certain amount of files to be uploaded at once, this is done to reduce potential errors yield Promise.all(parallelUploads.map((index) => __awaiter(this, void 0, void 0, function* () { while (currentFile < filesToUpload.length) { const currentFileParameters = parameters[currentFile]; currentFile += 1; if (abortPendingFileUploads) { failedItemsToReport.push(currentFileParameters.file); continue; } const startTime = perf_hooks_1.performance.now(); const uploadFileResult = yield this.uploadFileAsync(index, currentFileParameters); if (core.isDebug()) { core.debug(`File: ${++completedFiles}/${filesToUpload.length}. ${currentFileParameters.file} took ${(perf_hooks_1.performance.now() - startTime).toFixed(3)} milliseconds to finish upload`); } uploadFileSize += uploadFileResult.successfulUploadSize; totalFileSize += uploadFileResult.totalSize; if (uploadFileResult.isSuccess === false) { failedItemsToReport.push(currentFileParameters.file); if (!continueOnError) { // fail fast core.error(`aborting artifact upload`); abortPendingFileUploads = true; } } this.statusReporter.incrementProcessedCount(); } }))); this.statusReporter.stop(); // done uploading, safety dispose all connections this.uploadHttpManager.disposeAndReplaceAllClients(); core.info(`Total size of all the files uploaded is ${uploadFileSize} bytes`); return { uploadSize: uploadFileSize, totalSize: totalFileSize, failedItems: failedItemsToReport }; }); } /** * Asynchronously uploads a file. The file is compressed and uploaded using GZip if it is determined to save space. * If the upload file is bigger than the max chunk size it will be uploaded via multiple calls * @param {number} httpClientIndex The index of the httpClient that is being used to make all of the calls * @param {UploadFileParameters} parameters Information about the file that needs to be uploaded * @returns The size of the file that was uploaded in bytes along with any failed uploads */ uploadFileAsync(httpClientIndex, parameters) { return __awaiter(this, void 0, void 0, function* () { const fileStat = yield stat(parameters.file); const totalFileSize = fileStat.size; const isFIFO = fileStat.isFIFO(); let offset = 0; let isUploadSuccessful = true; let failedChunkSizes = 0; let uploadFileSize = 0; let isGzip = true; // the file that is being uploaded is less than 64k in size to increase throughput and to minimize disk I/O // for creating a new GZip file, an in-memory buffer is used for compression // with named pipes the file size is reported as zero in that case don't read the file in memory if (!isFIFO && totalFileSize < 65536) { core.debug(`${parameters.file} is less than 64k in size. Creating a gzip file in-memory to potentially reduce the upload size`); const buffer = yield (0, upload_gzip_1.createGZipFileInBuffer)(parameters.file); // An open stream is needed in the event of a failure and we need to retry. If a NodeJS.ReadableStream is directly passed in, // it will not properly get reset to the start of the stream if a chunk upload needs to be retried let openUploadStream; if (totalFileSize < buffer.byteLength) { // compression did not help with reducing the size, use a readable stream from the original file for upload core.debug(`The gzip file created for ${parameters.file} did not help with reducing the size of the file. The original file will be uploaded as-is`); openUploadStream = () => fs.createReadStream(parameters.file); isGzip = false; uploadFileSize = totalFileSize; } else { // create a readable stream using a PassThrough stream that is both readable and writable core.debug(`A gzip file created for ${parameters.file} helped with reducing the size of the original file. The file will be uploaded using gzip.`); openUploadStream = () => { const passThrough = new stream.PassThrough(); passThrough.end(buffer); return passThrough; }; uploadFileSize = buffer.byteLength; } const result = yield this.uploadChunk(httpClientIndex, parameters.resourceUrl, openUploadStream, 0, uploadFileSize - 1, uploadFileSize, isGzip, totalFileSize); if (!result) { // chunk failed to upload isUploadSuccessful = false; failedChunkSizes += uploadFileSize; core.warning(`Aborting upload for ${parameters.file} due to failure`); } return { isSuccess: isUploadSuccessful, successfulUploadSize: uploadFileSize - failedChunkSizes, totalSize: totalFileSize }; } else { // the file that is being uploaded is greater than 64k in size, a temporary file gets created on disk using the // npm tmp-promise package and this file gets used to create a GZipped file const tempFile = yield tmp.file(); core.debug(`${parameters.file} is greater than 64k in size. Creating a gzip file on-disk ${tempFile.path} to potentially reduce the upload size`); // create a GZip file of the original file being uploaded, the original file should not be modified in any way uploadFileSize = yield (0, upload_gzip_1.createGZipFileOnDisk)(parameters.file, tempFile.path); let uploadFilePath = tempFile.path; // compression did not help with size reduction, use the original file for upload and delete the temp GZip file // for named pipes totalFileSize is zero, this assumes compression did help if (!isFIFO && totalFileSize < uploadFileSize) { core.debug(`The gzip file created for ${parameters.file} did not help with reducing the size of the file. The original file will be uploaded as-is`); uploadFileSize = totalFileSize; uploadFilePath = parameters.file; isGzip = false; } else { core.debug(`The gzip file created for ${parameters.file} is smaller than the original file. The file will be uploaded using gzip.`); } let abortFileUpload = false; // upload only a single chunk at a time while (offset < uploadFileSize) { const chunkSize = Math.min(uploadFileSize - offset, parameters.maxChunkSize); const startChunkIndex = offset; const endChunkIndex = offset + chunkSize - 1; offset += parameters.maxChunkSize; if (abortFileUpload) { // if we don't want to continue in the event of an error, any pending upload chunks will be marked as failed failedChunkSizes += chunkSize; continue; } const result = yield this.uploadChunk(httpClientIndex, parameters.resourceUrl, () => fs.createReadStream(uploadFilePath, { start: startChunkIndex, end: endChunkIndex, autoClose: false }), startChunkIndex, endChunkIndex, uploadFileSize, isGzip, totalFileSize); if (!result) { // Chunk failed to upload, report as failed and do not continue uploading any more chunks for the file. It is possible that part of a chunk was // successfully uploaded so the server may report a different size for what was uploaded isUploadSuccessful = false; failedChunkSizes += chunkSize; core.warning(`Aborting upload for ${parameters.file} due to failure`); abortFileUpload = true; } else { // if an individual file is greater than 8MB (1024*1024*8) in size, display extra information about the upload status if (uploadFileSize > 8388608) { this.statusReporter.updateLargeFileStatus(parameters.file, startChunkIndex, endChunkIndex, uploadFileSize); } } } // Delete the temporary file that was created as part of the upload. If the temp file does not get manually deleted by // calling cleanup, it gets removed when the node process exits. For more info see: https://www.npmjs.com/package/tmp-promise#about core.debug(`deleting temporary gzip file ${tempFile.path}`); yield tempFile.cleanup(); return { isSuccess: isUploadSuccessful, successfulUploadSize: uploadFileSize - failedChunkSizes, totalSize: totalFileSize }; } }); } /** * Uploads a chunk of an individual file to the specified resourceUrl. If the upload fails and the status code * indicates a retryable status, we try to upload the chunk as well * @param {number} httpClientIndex The index of the httpClient being used to make all the necessary calls * @param {string} resourceUrl Url of the resource that the chunk will be uploaded to * @param {NodeJS.ReadableStream} openStream Stream of the file that will be uploaded * @param {number} start Starting byte index of file that the chunk belongs to * @param {number} end Ending byte index of file that the chunk belongs to * @param {number} uploadFileSize Total size of the file in bytes that is being uploaded * @param {boolean} isGzip Denotes if we are uploading a Gzip compressed stream * @param {number} totalFileSize Original total size of the file that is being uploaded * @returns if the chunk was successfully uploaded */ uploadChunk(httpClientIndex, resourceUrl, openStream, start, end, uploadFileSize, isGzip, totalFileSize) { return __awaiter(this, void 0, void 0, function* () { // open a new stream and read it to compute the digest const digest = yield (0, utils_1.digestForStream)(openStream()); // prepare all the necessary headers before making any http call const headers = (0, utils_1.getUploadHeaders)('application/octet-stream', true, isGzip, totalFileSize, end - start + 1, (0, utils_1.getContentRange)(start, end, uploadFileSize), digest); const uploadChunkRequest = () => __awaiter(this, void 0, void 0, function* () { const client = this.uploadHttpManager.getClient(httpClientIndex); return yield client.sendStream('PUT', resourceUrl, openStream(), headers); }); let retryCount = 0; const retryLimit = (0, config_variables_1.getRetryLimit)(); // Increments the current retry count and then checks if the retry limit has been reached // If there have been too many retries, fail so the download stops const incrementAndCheckRetryLimit = (response) => { retryCount++; if (retryCount > retryLimit) { if (response) { (0, utils_1.displayHttpDiagnostics)(response); } core.info(`Retry limit has been reached for chunk at offset ${start} to ${resourceUrl}`); return true; } return false; }; const backOff = (retryAfterValue) => __awaiter(this, void 0, void 0, function* () { this.uploadHttpManager.disposeAndReplaceClient(httpClientIndex); if (retryAfterValue) { core.info(`Backoff due to too many requests, retry #${retryCount}. Waiting for ${retryAfterValue} milliseconds before continuing the upload`); yield (0, utils_1.sleep)(retryAfterValue); } else { const backoffTime = (0, utils_1.getExponentialRetryTimeInMilliseconds)(retryCount); core.info(`Exponential backoff for retry #${retryCount}. Waiting for ${backoffTime} milliseconds before continuing the upload at offset ${start}`); yield (0, utils_1.sleep)(backoffTime); } core.info(`Finished backoff for retry #${retryCount}, continuing with upload`); return; }); // allow for failed chunks to be retried multiple times while (retryCount <= retryLimit) { let response; try { response = yield uploadChunkRequest(); } catch (error) { // if an error is caught, it is usually indicative of a timeout so retry the upload core.info(`An error has been caught http-client index ${httpClientIndex}, retrying the upload`); // eslint-disable-next-line no-console console.log(error); if (incrementAndCheckRetryLimit()) { return false; } yield backOff(); continue; } // Always read the body of the response. There is potential for a resource leak if the body is not read which will // result in the connection remaining open along with unintended consequences when trying to dispose of the client yield response.readBody(); if ((0, utils_1.isSuccessStatusCode)(response.message.statusCode)) { return true; } else if ((0, utils_1.isRetryableStatusCode)(response.message.statusCode)) { core.info(`A ${response.message.statusCode} status code has been received, will attempt to retry the upload`); if (incrementAndCheckRetryLimit(response)) { return false; } (0, utils_1.isThrottledStatusCode)(response.message.statusCode) ? yield backOff((0, utils_1.tryGetRetryAfterValueTimeInMilliseconds)(response.message.headers)) : yield backOff(); } else { core.error(`Unexpected response. Unable to upload chunk to ${resourceUrl}`); (0, utils_1.displayHttpDiagnostics)(response); return false; } } return false; }); } /** * Updates the size of the artifact from -1 which was initially set when the container was first created for the artifact. * Updating the size indicates that we are done uploading all the contents of the artifact */ patchArtifactSize(size, artifactName) { return __awaiter(this, void 0, void 0, function* () { const resourceUrl = new url_1.URL((0, utils_1.getArtifactUrl)()); resourceUrl.searchParams.append('artifactName', artifactName); const parameters = { Size: size }; const data = JSON.stringify(parameters, null, 2); core.debug(`URL is ${resourceUrl.toString()}`); // use the first client from the httpManager, `keep-alive` is not used so the connection will close immediately const client = this.uploadHttpManager.getClient(0); const headers = (0, utils_1.getUploadHeaders)('application/json', false); // Extra information to display when a particular HTTP code is returned const customErrorMessages = new Map([ [ http_client_1.HttpCodes.NotFound, `An Artifact with the name ${artifactName} was not found` ] ]); // TODO retry for all possible response codes, the artifact upload is pretty much complete so it at all costs we should try to finish this const response = yield (0, requestUtils_1.retryHttpClientRequest)('Finalize artifact upload', () => __awaiter(this, void 0, void 0, function* () { return client.patch(resourceUrl.toString(), data, headers); }), customErrorMessages); yield response.readBody(); core.debug(`Artifact ${artifactName} has been successfully uploaded, total size in bytes: ${size}`); }); } } exports.UploadHttpClient = UploadHttpClient; //# sourceMappingURL=upload-http-client.js.map /***/ }), /***/ 10183: /***/ (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.getUploadSpecification = void 0; const fs = __importStar(__nccwpck_require__(57147)); const core_1 = __nccwpck_require__(42186); const path_1 = __nccwpck_require__(71017); const path_and_artifact_name_validation_1 = __nccwpck_require__(87398); /** * Creates a specification that describes how each file that is part of the artifact will be uploaded * @param artifactName the name of the artifact being uploaded. Used during upload to denote where the artifact is stored on the server * @param rootDirectory an absolute file path that denotes the path that should be removed from the beginning of each artifact file * @param artifactFiles a list of absolute file paths that denote what should be uploaded as part of the artifact */ function getUploadSpecification(artifactName, rootDirectory, artifactFiles) { // artifact name was checked earlier on, no need to check again const specifications = []; if (!fs.existsSync(rootDirectory)) { throw new Error(`Provided rootDirectory ${rootDirectory} does not exist`); } if (!fs.statSync(rootDirectory).isDirectory()) { throw new Error(`Provided rootDirectory ${rootDirectory} is not a valid directory`); } // Normalize and resolve, this allows for either absolute or relative paths to be used rootDirectory = (0, path_1.normalize)(rootDirectory); rootDirectory = (0, path_1.resolve)(rootDirectory); /* Example to demonstrate behavior Input: artifactName: my-artifact rootDirectory: '/home/user/files/plz-upload' artifactFiles: [ '/home/user/files/plz-upload/file1.txt', '/home/user/files/plz-upload/file2.txt', '/home/user/files/plz-upload/dir/file3.txt' ] Output: specifications: [ ['/home/user/files/plz-upload/file1.txt', 'my-artifact/file1.txt'], ['/home/user/files/plz-upload/file1.txt', 'my-artifact/file2.txt'], ['/home/user/files/plz-upload/file1.txt', 'my-artifact/dir/file3.txt'] ] */ for (let file of artifactFiles) { if (!fs.existsSync(file)) { throw new Error(`File ${file} does not exist`); } if (!fs.statSync(file).isDirectory()) { // Normalize and resolve, this allows for either absolute or relative paths to be used file = (0, path_1.normalize)(file); file = (0, path_1.resolve)(file); if (!file.startsWith(rootDirectory)) { throw new Error(`The rootDirectory: ${rootDirectory} is not a parent directory of the file: ${file}`); } // Check for forbidden characters in file paths that will be rejected during upload const uploadPath = file.replace(rootDirectory, ''); (0, path_and_artifact_name_validation_1.checkArtifactFilePath)(uploadPath); /* uploadFilePath denotes where the file will be uploaded in the file container on the server. During a run, if multiple artifacts are uploaded, they will all be saved in the same container. The artifact name is used as the root directory in the container to separate and distinguish uploaded artifacts path.join handles all the following cases and would return 'artifact-name/file-to-upload.txt join('artifact-name/', 'file-to-upload.txt') join('artifact-name/', '/file-to-upload.txt') join('artifact-name', 'file-to-upload.txt') join('artifact-name', '/file-to-upload.txt') */ specifications.push({ absoluteFilePath: file, uploadFilePath: (0, path_1.join)(artifactName, uploadPath) }); } else { // Directories are rejected by the server during upload (0, core_1.debug)(`Removing ${file} from rawSearchResults because it is a directory`); } } return specifications; } exports.getUploadSpecification = getUploadSpecification; //# sourceMappingURL=upload-specification.js.map /***/ }), /***/ 36327: /***/ (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 })); exports.digestForStream = exports.sleep = exports.getProperRetention = exports.rmFile = exports.getFileSize = exports.createEmptyFilesForArtifact = exports.createDirectoriesForArtifact = exports.displayHttpDiagnostics = exports.getArtifactUrl = exports.createHttpClient = exports.getUploadHeaders = exports.getDownloadHeaders = exports.getContentRange = exports.tryGetRetryAfterValueTimeInMilliseconds = exports.isThrottledStatusCode = exports.isRetryableStatusCode = exports.isForbiddenStatusCode = exports.isSuccessStatusCode = exports.getApiVersion = exports.parseEnvNumber = exports.getExponentialRetryTimeInMilliseconds = void 0; const crypto_1 = __importDefault(__nccwpck_require__(6113)); const fs_1 = __nccwpck_require__(57147); const core_1 = __nccwpck_require__(42186); const http_client_1 = __nccwpck_require__(96255); const auth_1 = __nccwpck_require__(35526); const config_variables_1 = __nccwpck_require__(42222); const crc64_1 = __importDefault(__nccwpck_require__(23549)); /** * Returns a retry time in milliseconds that exponentially gets larger * depending on the amount of retries that have been attempted */ function getExponentialRetryTimeInMilliseconds(retryCount) { if (retryCount < 0) { throw new Error('RetryCount should not be negative'); } else if (retryCount === 0) { return (0, config_variables_1.getInitialRetryIntervalInMilliseconds)(); } const minTime = (0, config_variables_1.getInitialRetryIntervalInMilliseconds)() * (0, config_variables_1.getRetryMultiplier)() * retryCount; const maxTime = minTime * (0, config_variables_1.getRetryMultiplier)(); // returns a random number between the minTime (inclusive) and the maxTime (exclusive) return Math.trunc(Math.random() * (maxTime - minTime) + minTime); } exports.getExponentialRetryTimeInMilliseconds = getExponentialRetryTimeInMilliseconds; /** * Parses a env variable that is a number */ function parseEnvNumber(key) { const value = Number(process.env[key]); if (Number.isNaN(value) || value < 0) { return undefined; } return value; } exports.parseEnvNumber = parseEnvNumber; /** * Various utility functions to help with the necessary API calls */ function getApiVersion() { return '6.0-preview'; } exports.getApiVersion = getApiVersion; function isSuccessStatusCode(statusCode) { if (!statusCode) { return false; } return statusCode >= 200 && statusCode < 300; } exports.isSuccessStatusCode = isSuccessStatusCode; function isForbiddenStatusCode(statusCode) { if (!statusCode) { return false; } return statusCode === http_client_1.HttpCodes.Forbidden; } exports.isForbiddenStatusCode = isForbiddenStatusCode; function isRetryableStatusCode(statusCode) { if (!statusCode) { return false; } const retryableStatusCodes = [ http_client_1.HttpCodes.BadGateway, http_client_1.HttpCodes.GatewayTimeout, http_client_1.HttpCodes.InternalServerError, http_client_1.HttpCodes.ServiceUnavailable, http_client_1.HttpCodes.TooManyRequests, 413 // Payload Too Large ]; return retryableStatusCodes.includes(statusCode); } exports.isRetryableStatusCode = isRetryableStatusCode; function isThrottledStatusCode(statusCode) { if (!statusCode) { return false; } return statusCode === http_client_1.HttpCodes.TooManyRequests; } exports.isThrottledStatusCode = isThrottledStatusCode; /** * Attempts to get the retry-after value from a set of http headers. The retry time * is originally denoted in seconds, so if present, it is converted to milliseconds * @param headers all the headers received when making an http call */ function tryGetRetryAfterValueTimeInMilliseconds(headers) { if (headers['retry-after']) { const retryTime = Number(headers['retry-after']); if (!isNaN(retryTime)) { (0, core_1.info)(`Retry-After header is present with a value of ${retryTime}`); return retryTime * 1000; } (0, core_1.info)(`Returned retry-after header value: ${retryTime} is non-numeric and cannot be used`); return undefined; } (0, core_1.info)(`No retry-after header was found. Dumping all headers for diagnostic purposes`); // eslint-disable-next-line no-console console.log(headers); return undefined; } exports.tryGetRetryAfterValueTimeInMilliseconds = tryGetRetryAfterValueTimeInMilliseconds; function getContentRange(start, end, total) { // Format: `bytes start-end/fileSize // start and end are inclusive // For a 200 byte chunk starting at byte 0: // Content-Range: bytes 0-199/200 return `bytes ${start}-${end}/${total}`; } exports.getContentRange = getContentRange; /** * Sets all the necessary headers when downloading an artifact * @param {string} contentType the type of content being uploaded * @param {boolean} isKeepAlive is the same connection being used to make multiple calls * @param {boolean} acceptGzip can we accept a gzip encoded response * @param {string} acceptType the type of content that we can accept * @returns appropriate headers to make a specific http call during artifact download */ function getDownloadHeaders(contentType, isKeepAlive, acceptGzip) { const requestOptions = {}; if (contentType) { requestOptions['Content-Type'] = contentType; } if (isKeepAlive) { requestOptions['Connection'] = 'Keep-Alive'; // keep alive for at least 10 seconds before closing the connection requestOptions['Keep-Alive'] = '10'; } if (acceptGzip) { // if we are expecting a response with gzip encoding, it should be using an octet-stream in the accept header requestOptions['Accept-Encoding'] = 'gzip'; requestOptions['Accept'] = `application/octet-stream;api-version=${getApiVersion()}`; } else { // default to application/json if we are not working with gzip content requestOptions['Accept'] = `application/json;api-version=${getApiVersion()}`; } return requestOptions; } exports.getDownloadHeaders = getDownloadHeaders; /** * Sets all the necessary headers when uploading an artifact * @param {string} contentType the type of content being uploaded * @param {boolean} isKeepAlive is the same connection being used to make multiple calls * @param {boolean} isGzip is the connection being used to upload GZip compressed content * @param {number} uncompressedLength the original size of the content if something is being uploaded that has been compressed * @param {number} contentLength the length of the content that is being uploaded * @param {string} contentRange the range of the content that is being uploaded * @returns appropriate headers to make a specific http call during artifact upload */ function getUploadHeaders(contentType, isKeepAlive, isGzip, uncompressedLength, contentLength, contentRange, digest) { const requestOptions = {}; requestOptions['Accept'] = `application/json;api-version=${getApiVersion()}`; if (contentType) { requestOptions['Content-Type'] = contentType; } if (isKeepAlive) { requestOptions['Connection'] = 'Keep-Alive'; // keep alive for at least 10 seconds before closing the connection requestOptions['Keep-Alive'] = '10'; } if (isGzip) { requestOptions['Content-Encoding'] = 'gzip'; requestOptions['x-tfs-filelength'] = uncompressedLength; } if (contentLength) { requestOptions['Content-Length'] = contentLength; } if (contentRange) { requestOptions['Content-Range'] = contentRange; } if (digest) { requestOptions['x-actions-results-crc64'] = digest.crc64; requestOptions['x-actions-results-md5'] = digest.md5; } return requestOptions; } exports.getUploadHeaders = getUploadHeaders; function createHttpClient(userAgent) { return new http_client_1.HttpClient(userAgent, [ new auth_1.BearerCredentialHandler((0, config_variables_1.getRuntimeToken)()) ]); } exports.createHttpClient = createHttpClient; function getArtifactUrl() { const artifactUrl = `${(0, config_variables_1.getRuntimeUrl)()}_apis/pipelines/workflows/${(0, config_variables_1.getWorkFlowRunId)()}/artifacts?api-version=${getApiVersion()}`; (0, core_1.debug)(`Artifact Url: ${artifactUrl}`); return artifactUrl; } exports.getArtifactUrl = getArtifactUrl; /** * Uh oh! Something might have gone wrong during either upload or download. The IHtttpClientResponse object contains information * about the http call that was made by the actions http client. This information might be useful to display for diagnostic purposes, but * this entire object is really big and most of the information is not really useful. This function takes the response object and displays only * the information that we want. * * Certain information such as the TLSSocket and the Readable state are not really useful for diagnostic purposes so they can be avoided. * Other information such as the headers, the response code and message might be useful, so this is displayed. */ function displayHttpDiagnostics(response) { (0, core_1.info)(`##### Begin Diagnostic HTTP information ##### Status Code: ${response.message.statusCode} Status Message: ${response.message.statusMessage} Header Information: ${JSON.stringify(response.message.headers, undefined, 2)} ###### End Diagnostic HTTP information ######`); } exports.displayHttpDiagnostics = displayHttpDiagnostics; function createDirectoriesForArtifact(directories) { return __awaiter(this, void 0, void 0, function* () { for (const directory of directories) { yield fs_1.promises.mkdir(directory, { recursive: true }); } }); } exports.createDirectoriesForArtifact = createDirectoriesForArtifact; function createEmptyFilesForArtifact(emptyFilesToCreate) { return __awaiter(this, void 0, void 0, function* () { for (const filePath of emptyFilesToCreate) { yield (yield fs_1.promises.open(filePath, 'w')).close(); } }); } exports.createEmptyFilesForArtifact = createEmptyFilesForArtifact; function getFileSize(filePath) { return __awaiter(this, void 0, void 0, function* () { const stats = yield fs_1.promises.stat(filePath); (0, core_1.debug)(`${filePath} size:(${stats.size}) blksize:(${stats.blksize}) blocks:(${stats.blocks})`); return stats.size; }); } exports.getFileSize = getFileSize; function rmFile(filePath) { return __awaiter(this, void 0, void 0, function* () { yield fs_1.promises.unlink(filePath); }); } exports.rmFile = rmFile; function getProperRetention(retentionInput, retentionSetting) { if (retentionInput < 0) { throw new Error('Invalid retention, minimum value is 1.'); } let retention = retentionInput; if (retentionSetting) { const maxRetention = parseInt(retentionSetting); if (!isNaN(maxRetention) && maxRetention < retention) { (0, core_1.warning)(`Retention days is greater than the max value allowed by the repository setting, reduce retention to ${maxRetention} days`); retention = maxRetention; } } return retention; } exports.getProperRetention = getProperRetention; function sleep(milliseconds) { return __awaiter(this, void 0, void 0, function* () { return new Promise(resolve => setTimeout(resolve, milliseconds)); }); } exports.sleep = sleep; function digestForStream(stream) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => { const crc64 = new crc64_1.default(); const md5 = crypto_1.default.createHash('md5'); stream .on('data', data => { crc64.update(data); md5.update(data); }) .on('end', () => resolve({ crc64: crc64.digest('base64'), md5: md5.digest('base64') })) .on('error', reject); }); }); } exports.digestForStream = digestForStream; //# sourceMappingURL=utils.js.map /***/ }), /***/ 87351: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.issue = exports.issueCommand = void 0; const os = __importStar(__nccwpck_require__(22037)); const utils_1 = __nccwpck_require__(5278); /** * Commands * * Command Format: * ::name key=value,key=value::message * * Examples: * ::warning::This is the message * ::set-env name=MY_VAR::some value */ function issueCommand(command, properties, message) { const cmd = new Command(command, properties, message); process.stdout.write(cmd.toString() + os.EOL); } exports.issueCommand = issueCommand; function issue(name, message = '') { issueCommand(name, {}, message); } exports.issue = issue; const CMD_STRING = '::'; class Command { constructor(command, properties, message) { if (!command) { command = 'missing.command'; } this.command = command; this.properties = properties; this.message = message; } toString() { let cmdStr = CMD_STRING + this.command; if (this.properties && Object.keys(this.properties).length > 0) { cmdStr += ' '; let first = true; for (const key in this.properties) { if (this.properties.hasOwnProperty(key)) { const val = this.properties[key]; if (val) { if (first) { first = false; } else { cmdStr += ','; } cmdStr += `${key}=${escapeProperty(val)}`; } } } } cmdStr += `${CMD_STRING}${escapeData(this.message)}`; return cmdStr; } } function escapeData(s) { return utils_1.toCommandValue(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A'); } function escapeProperty(s) { return utils_1.toCommandValue(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A') .replace(/:/g, '%3A') .replace(/,/g, '%2C'); } //# sourceMappingURL=command.js.map /***/ }), /***/ 42186: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; const command_1 = __nccwpck_require__(87351); const file_command_1 = __nccwpck_require__(717); const utils_1 = __nccwpck_require__(5278); const os = __importStar(__nccwpck_require__(22037)); const path = __importStar(__nccwpck_require__(71017)); const oidc_utils_1 = __nccwpck_require__(98041); /** * The code to exit an action */ var ExitCode; (function (ExitCode) { /** * A code indicating that the action was successful */ ExitCode[ExitCode["Success"] = 0] = "Success"; /** * A code indicating that the action was a failure */ ExitCode[ExitCode["Failure"] = 1] = "Failure"; })(ExitCode = exports.ExitCode || (exports.ExitCode = {})); //----------------------------------------------------------------------- // Variables //----------------------------------------------------------------------- /** * Sets env variable for this action and future actions in the job * @param name the name of the variable to set * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function exportVariable(name, val) { const convertedVal = utils_1.toCommandValue(val); process.env[name] = convertedVal; const filePath = process.env['GITHUB_ENV'] || ''; if (filePath) { return file_command_1.issueFileCommand('ENV', file_command_1.prepareKeyValueMessage(name, val)); } command_1.issueCommand('set-env', { name }, convertedVal); } exports.exportVariable = exportVariable; /** * Registers a secret which will get masked from logs * @param secret value of the secret */ function setSecret(secret) { command_1.issueCommand('add-mask', {}, secret); } exports.setSecret = setSecret; /** * Prepends inputPath to the PATH (for this action and future actions) * @param inputPath */ function addPath(inputPath) { const filePath = process.env['GITHUB_PATH'] || ''; if (filePath) { file_command_1.issueFileCommand('PATH', inputPath); } else { command_1.issueCommand('add-path', {}, inputPath); } process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; } exports.addPath = addPath; /** * Gets the value of an input. * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. * Returns an empty string if the value is not defined. * * @param name name of the input to get * @param options optional. See InputOptions. * @returns string */ function getInput(name, options) { const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; if (options && options.required && !val) { throw new Error(`Input required and not supplied: ${name}`); } if (options && options.trimWhitespace === false) { return val; } return val.trim(); } exports.getInput = getInput; /** * Gets the values of an multiline input. Each value is also trimmed. * * @param name name of the input to get * @param options optional. See InputOptions. * @returns string[] * */ function getMultilineInput(name, options) { const inputs = getInput(name, options) .split('\n') .filter(x => x !== ''); if (options && options.trimWhitespace === false) { return inputs; } return inputs.map(input => input.trim()); } exports.getMultilineInput = getMultilineInput; /** * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. * Support boolean input list: `true | True | TRUE | false | False | FALSE` . * The return value is also in boolean type. * ref: https://yaml.org/spec/1.2/spec.html#id2804923 * * @param name name of the input to get * @param options optional. See InputOptions. * @returns boolean */ function getBooleanInput(name, options) { const trueValue = ['true', 'True', 'TRUE']; const falseValue = ['false', 'False', 'FALSE']; const val = getInput(name, options); if (trueValue.includes(val)) return true; if (falseValue.includes(val)) return false; throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); } exports.getBooleanInput = getBooleanInput; /** * Sets the value of an output. * * @param name name of the output to set * @param value value to store. Non-string values will be converted to a string via JSON.stringify */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function setOutput(name, value) { const filePath = process.env['GITHUB_OUTPUT'] || ''; if (filePath) { return file_command_1.issueFileCommand('OUTPUT', file_command_1.prepareKeyValueMessage(name, value)); } process.stdout.write(os.EOL); command_1.issueCommand('set-output', { name }, utils_1.toCommandValue(value)); } exports.setOutput = setOutput; /** * Enables or disables the echoing of commands into stdout for the rest of the step. * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. * */ function setCommandEcho(enabled) { command_1.issue('echo', enabled ? 'on' : 'off'); } exports.setCommandEcho = setCommandEcho; //----------------------------------------------------------------------- // Results //----------------------------------------------------------------------- /** * Sets the action status to failed. * When the action exits it will be with an exit code of 1 * @param message add error issue message */ function setFailed(message) { process.exitCode = ExitCode.Failure; error(message); } exports.setFailed = setFailed; //----------------------------------------------------------------------- // Logging Commands //----------------------------------------------------------------------- /** * Gets whether Actions Step Debug is on or not */ function isDebug() { return process.env['RUNNER_DEBUG'] === '1'; } exports.isDebug = isDebug; /** * Writes debug message to user log * @param message debug message */ function debug(message) { command_1.issueCommand('debug', {}, message); } exports.debug = debug; /** * Adds an error issue * @param message error issue message. Errors will be converted to string via toString() * @param properties optional properties to add to the annotation. */ function error(message, properties = {}) { command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); } exports.error = error; /** * Adds a warning issue * @param message warning issue message. Errors will be converted to string via toString() * @param properties optional properties to add to the annotation. */ function warning(message, properties = {}) { command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); } exports.warning = warning; /** * Adds a notice issue * @param message notice issue message. Errors will be converted to string via toString() * @param properties optional properties to add to the annotation. */ function notice(message, properties = {}) { command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); } exports.notice = notice; /** * Writes info to log with console.log. * @param message info message */ function info(message) { process.stdout.write(message + os.EOL); } exports.info = info; /** * Begin an output group. * * Output until the next `groupEnd` will be foldable in this group * * @param name The name of the output group */ function startGroup(name) { command_1.issue('group', name); } exports.startGroup = startGroup; /** * End an output group. */ function endGroup() { command_1.issue('endgroup'); } exports.endGroup = endGroup; /** * Wrap an asynchronous function call in a group. * * Returns the same type as the function itself. * * @param name The name of the group * @param fn The function to wrap in the group */ function group(name, fn) { return __awaiter(this, void 0, void 0, function* () { startGroup(name); let result; try { result = yield fn(); } finally { endGroup(); } return result; }); } exports.group = group; //----------------------------------------------------------------------- // Wrapper action state //----------------------------------------------------------------------- /** * Saves state for current action, the state can only be retrieved by this action's post job execution. * * @param name name of the state to store * @param value value to store. Non-string values will be converted to a string via JSON.stringify */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function saveState(name, value) { const filePath = process.env['GITHUB_STATE'] || ''; if (filePath) { return file_command_1.issueFileCommand('STATE', file_command_1.prepareKeyValueMessage(name, value)); } command_1.issueCommand('save-state', { name }, utils_1.toCommandValue(value)); } exports.saveState = saveState; /** * Gets the value of an state set by this action's main execution. * * @param name name of the state to get * @returns string */ function getState(name) { return process.env[`STATE_${name}`] || ''; } exports.getState = getState; function getIDToken(aud) { return __awaiter(this, void 0, void 0, function* () { return yield oidc_utils_1.OidcClient.getIDToken(aud); }); } exports.getIDToken = getIDToken; /** * Summary exports */ var summary_1 = __nccwpck_require__(81327); Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); /** * @deprecated use core.summary */ var summary_2 = __nccwpck_require__(81327); Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); /** * Path exports */ var path_utils_1 = __nccwpck_require__(2981); Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } })); Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } })); Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } })); //# sourceMappingURL=core.js.map /***/ }), /***/ 717: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // For internal use, subject to change. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; 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.prepareKeyValueMessage = exports.issueFileCommand = void 0; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ const fs = __importStar(__nccwpck_require__(57147)); const os = __importStar(__nccwpck_require__(22037)); const uuid_1 = __nccwpck_require__(75840); const utils_1 = __nccwpck_require__(5278); function issueFileCommand(command, message) { const filePath = process.env[`GITHUB_${command}`]; if (!filePath) { throw new Error(`Unable to find environment variable for file command ${command}`); } if (!fs.existsSync(filePath)) { throw new Error(`Missing file at path: ${filePath}`); } fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, { encoding: 'utf8' }); } exports.issueFileCommand = issueFileCommand; function prepareKeyValueMessage(key, value) { const delimiter = `ghadelimiter_${uuid_1.v4()}`; const convertedValue = utils_1.toCommandValue(value); // These should realistically never happen, but just in case someone finds a // way to exploit uuid generation let's not allow keys or values that contain // the delimiter. if (key.includes(delimiter)) { throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); } if (convertedValue.includes(delimiter)) { throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); } return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; } exports.prepareKeyValueMessage = prepareKeyValueMessage; //# sourceMappingURL=file-command.js.map /***/ }), /***/ 98041: /***/ (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__(96255); const auth_1 = __nccwpck_require__(35526); const core_1 = __nccwpck_require__(42186); class OidcClient { static createHttpClient(allowRetry = true, maxRetry = 10) { const requestOptions = { allowRetries: allowRetry, maxRetries: maxRetry }; return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions); } static getRequestToken() { const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN']; if (!token) { throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable'); } return token; } static getIDTokenUrl() { const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL']; if (!runtimeUrl) { throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable'); } return runtimeUrl; } static getCall(id_token_url) { var _a; return __awaiter(this, void 0, void 0, function* () { const httpclient = OidcClient.createHttpClient(); const res = yield httpclient .getJson(id_token_url) .catch(error => { throw new Error(`Failed to get ID Token. \n Error Code : ${error.statusCode}\n Error Message: ${error.result.message}`); }); const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; if (!id_token) { throw new Error('Response json body do not have ID Token field'); } return id_token; }); } static getIDToken(audience) { return __awaiter(this, void 0, void 0, function* () { try { // New ID Token is requested from action service let id_token_url = OidcClient.getIDTokenUrl(); if (audience) { const encodedAudience = encodeURIComponent(audience); id_token_url = `${id_token_url}&audience=${encodedAudience}`; } core_1.debug(`ID token url is ${id_token_url}`); const id_token = yield OidcClient.getCall(id_token_url); core_1.setSecret(id_token); return id_token; } catch (error) { throw new Error(`Error message: ${error.message}`); } }); } } exports.OidcClient = OidcClient; //# sourceMappingURL=oidc-utils.js.map /***/ }), /***/ 2981: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; 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.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; const path = __importStar(__nccwpck_require__(71017)); /** * toPosixPath converts the given path to the posix form. On Windows, \\ will be * replaced with /. * * @param pth. Path to transform. * @return string Posix path. */ function toPosixPath(pth) { return pth.replace(/[\\]/g, '/'); } exports.toPosixPath = toPosixPath; /** * toWin32Path converts the given path to the win32 form. On Linux, / will be * replaced with \\. * * @param pth. Path to transform. * @return string Win32 path. */ function toWin32Path(pth) { return pth.replace(/[/]/g, '\\'); } exports.toWin32Path = toWin32Path; /** * toPlatformPath converts the given path to a platform-specific path. It does * this by replacing instances of / and \ with the platform-specific path * separator. * * @param pth The path to platformize. * @return string The platform-specific path. */ function toPlatformPath(pth) { return pth.replace(/[/\\]/g, path.sep); } exports.toPlatformPath = toPlatformPath; //# sourceMappingURL=path-utils.js.map /***/ }), /***/ 81327: /***/ (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__(22037); const fs_1 = __nccwpck_require__(57147); const { access, appendFile, writeFile } = fs_1.promises; exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; class Summary { constructor() { this._buffer = ''; } /** * 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 /***/ }), /***/ 5278: /***/ ((__unused_webpack_module, exports) => { "use strict"; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toCommandProperties = exports.toCommandValue = void 0; /** * Sanitizes an input into a string so it can be passed into issueCommand safely * @param input input to sanitize into a string */ function toCommandValue(input) { if (input === null || input === undefined) { return ''; } else 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 /***/ }), /***/ 28090: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { 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.hashFiles = exports.create = void 0; const internal_globber_1 = __nccwpck_require__(28298); const internal_hash_files_1 = __nccwpck_require__(2448); /** * 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; /** * Computes the sha256 hash of a glob * * @param patterns Patterns separated by newlines * @param options Glob options */ function hashFiles(patterns, options, verbose = false) { return __awaiter(this, void 0, void 0, function* () { let followSymbolicLinks = true; if (options && typeof options.followSymbolicLinks === 'boolean') { followSymbolicLinks = options.followSymbolicLinks; } const globber = yield create(patterns, { followSymbolicLinks }); return internal_hash_files_1.hashFiles(globber, verbose); }); } exports.hashFiles = hashFiles; //# sourceMappingURL=glob.js.map /***/ }), /***/ 51026: /***/ (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__(42186)); /** * Returns a copy with defaults filled in. */ function getOptions(copy) { const result = { followSymbolicLinks: true, implicitDescendants: true, matchDirectories: true, omitBrokenSymbolicLinks: true }; if (copy) { if (typeof copy.followSymbolicLinks === 'boolean') { result.followSymbolicLinks = copy.followSymbolicLinks; core.debug(`followSymbolicLinks '${result.followSymbolicLinks}'`); } if (typeof copy.implicitDescendants === 'boolean') { result.implicitDescendants = copy.implicitDescendants; core.debug(`implicitDescendants '${result.implicitDescendants}'`); } if (typeof copy.matchDirectories === 'boolean') { result.matchDirectories = copy.matchDirectories; core.debug(`matchDirectories '${result.matchDirectories}'`); } if (typeof copy.omitBrokenSymbolicLinks === 'boolean') { result.omitBrokenSymbolicLinks = copy.omitBrokenSymbolicLinks; core.debug(`omitBrokenSymbolicLinks '${result.omitBrokenSymbolicLinks}'`); } } return result; } exports.getOptions = getOptions; //# sourceMappingURL=internal-glob-options-helper.js.map /***/ }), /***/ 28298: /***/ (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__(42186)); const fs = __importStar(__nccwpck_require__(57147)); const globOptionsHelper = __importStar(__nccwpck_require__(51026)); const path = __importStar(__nccwpck_require__(71017)); const patternHelper = __importStar(__nccwpck_require__(29005)); const internal_match_kind_1 = __nccwpck_require__(81063); const internal_pattern_1 = __nccwpck_require__(64536); const internal_search_state_1 = __nccwpck_require__(89117); const IS_WINDOWS = process.platform === 'win32'; class DefaultGlobber { constructor(options) { this.patterns = []; this.searchPaths = []; this.options = globOptionsHelper.getOptions(options); } 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 && options.matchDirectories) { yield yield __await(item.path); } // Descend? else if (!partialMatch) { continue; } // Push the child items in reverse const childLevel = item.level + 1; const childItems = (yield __await(fs.promises.readdir(item.path))).map(x => new internal_search_state_1.SearchState(path.join(item.path, x), childLevel)); stack.push(...childItems.reverse()); } // File else if (match & internal_match_kind_1.MatchKind.File) { yield yield __await(item.path); } } }); } /** * 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 /***/ }), /***/ 2448: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __asyncValues = (this && this.__asyncValues) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.hashFiles = void 0; const crypto = __importStar(__nccwpck_require__(6113)); const core = __importStar(__nccwpck_require__(42186)); const fs = __importStar(__nccwpck_require__(57147)); const stream = __importStar(__nccwpck_require__(12781)); const util = __importStar(__nccwpck_require__(73837)); const path = __importStar(__nccwpck_require__(71017)); function hashFiles(globber, verbose = false) { var e_1, _a; var _b; return __awaiter(this, void 0, void 0, function* () { const writeDelegate = verbose ? core.info : core.debug; let hasMatch = false; const githubWorkspace = (_b = process.env['GITHUB_WORKSPACE']) !== null && _b !== void 0 ? _b : process.cwd(); const result = crypto.createHash('sha256'); let count = 0; try { for (var _c = __asyncValues(globber.globGenerator()), _d; _d = yield _c.next(), !_d.done;) { const file = _d.value; writeDelegate(file); if (!file.startsWith(`${githubWorkspace}${path.sep}`)) { writeDelegate(`Ignore '${file}' since it is not under GITHUB_WORKSPACE.`); continue; } if (fs.statSync(file).isDirectory()) { writeDelegate(`Skip directory '${file}'.`); continue; } const hash = crypto.createHash('sha256'); const pipeline = util.promisify(stream.pipeline); yield pipeline(fs.createReadStream(file), hash); result.write(hash.digest()); count++; if (!hasMatch) { hasMatch = true; } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_d && !_d.done && (_a = _c.return)) yield _a.call(_c); } finally { if (e_1) throw e_1.error; } } result.end(); if (hasMatch) { writeDelegate(`Found ${count} files to hash.`); return result.digest('hex'); } else { writeDelegate(`No matches found for glob`); return ''; } }); } exports.hashFiles = hashFiles; //# sourceMappingURL=internal-hash-files.js.map /***/ }), /***/ 81063: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MatchKind = void 0; /** * Indicates whether a pattern matches a path */ var MatchKind; (function (MatchKind) { /** Not matched */ MatchKind[MatchKind["None"] = 0] = "None"; /** Matched if the path is a directory */ MatchKind[MatchKind["Directory"] = 1] = "Directory"; /** Matched if the path is a regular file */ MatchKind[MatchKind["File"] = 2] = "File"; /** Matched */ MatchKind[MatchKind["All"] = 3] = "All"; })(MatchKind = exports.MatchKind || (exports.MatchKind = {})); //# sourceMappingURL=internal-match-kind.js.map /***/ }), /***/ 1849: /***/ (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__(71017)); const assert_1 = __importDefault(__nccwpck_require__(39491)); const IS_WINDOWS = process.platform === 'win32'; /** * Similar to path.dirname except normalizes the path separators and slightly better handling for Windows UNC paths. * * 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 /***/ }), /***/ 96836: /***/ (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__(71017)); const pathHelper = __importStar(__nccwpck_require__(1849)); const assert_1 = __importDefault(__nccwpck_require__(39491)); const IS_WINDOWS = process.platform === 'win32'; /** * Helper class for parsing paths into segments */ class Path { /** * Constructs a Path * @param itemPath Path or array of segments */ constructor(itemPath) { this.segments = []; // String if (typeof itemPath === 'string') { assert_1.default(itemPath, `Parameter 'itemPath' must not be empty`); // Normalize slashes and trim unnecessary trailing slash itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); // Not rooted if (!pathHelper.hasRoot(itemPath)) { this.segments = itemPath.split(path.sep); } // Rooted else { // Add all segments, while not at the root let remaining = itemPath; let dir = pathHelper.dirname(remaining); while (dir !== remaining) { // Add the segment const basename = path.basename(remaining); this.segments.unshift(basename); // Truncate the last segment remaining = dir; dir = pathHelper.dirname(remaining); } // Remainder is the root this.segments.unshift(remaining); } } // Array else { // Must not be empty assert_1.default(itemPath.length > 0, `Parameter 'itemPath' must not be an empty array`); // Each segment for (let i = 0; i < itemPath.length; i++) { let segment = itemPath[i]; // Must not be empty assert_1.default(segment, `Parameter 'itemPath' must not contain any empty segments`); // Normalize slashes segment = pathHelper.normalizeSeparators(itemPath[i]); // Root segment if (i === 0 && pathHelper.hasRoot(segment)) { segment = pathHelper.safeTrimTrailingSeparator(segment); assert_1.default(segment === pathHelper.dirname(segment), `Parameter 'itemPath' root segment contains information for multiple segments`); this.segments.push(segment); } // All other segments else { // Must not contain slash assert_1.default(!segment.includes(path.sep), `Parameter 'itemPath' contains unexpected path separators`); this.segments.push(segment); } } } } /** * 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 /***/ }), /***/ 29005: /***/ (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__(1849)); const internal_match_kind_1 = __nccwpck_require__(81063); const IS_WINDOWS = process.platform === 'win32'; /** * Given an array of patterns, returns an array of paths to search. * Duplicates and paths under other included paths are filtered out. */ function getSearchPaths(patterns) { // Ignore negate patterns patterns = patterns.filter(x => !x.negate); // Create a map of all search paths const searchPathMap = {}; for (const pattern of patterns) { const key = IS_WINDOWS ? pattern.searchPath.toUpperCase() : pattern.searchPath; searchPathMap[key] = 'candidate'; } 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 /***/ }), /***/ 64536: /***/ (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__(22037)); const path = __importStar(__nccwpck_require__(71017)); const pathHelper = __importStar(__nccwpck_require__(1849)); const assert_1 = __importDefault(__nccwpck_require__(39491)); const minimatch_1 = __nccwpck_require__(83973); const internal_match_kind_1 = __nccwpck_require__(81063); const internal_path_1 = __nccwpck_require__(96836); const IS_WINDOWS = process.platform === 'win32'; class Pattern { constructor(patternOrNegate, isImplicitPattern = false, segments, homedir) { /** * Indicates whether matches should be excluded from the result set */ this.negate = false; // Pattern overload let pattern; if (typeof patternOrNegate === 'string') { pattern = patternOrNegate.trim(); } // Segments overload else { // Convert to pattern segments = segments || []; assert_1.default(segments.length, `Parameter 'segments' must not empty`); const root = Pattern.getLiteral(segments[0]); assert_1.default(root && pathHelper.hasAbsoluteRoot(root), `Parameter 'segments' first element must be a root path`); pattern = new internal_path_1.Path(segments).toString().trim(); if (patternOrNegate) { pattern = `!${pattern}`; } } // Negate while (pattern.startsWith('!')) { this.negate = !this.negate; pattern = pattern.substr(1).trim(); } // Normalize slashes and ensures absolute root pattern = Pattern.fixupPattern(pattern, homedir); // Segments this.segments = new internal_path_1.Path(pattern).segments; // Trailing slash indicates the pattern should only match directories, not regular files this.trailingSeparator = pathHelper .normalizeSeparators(pattern) .endsWith(path.sep); pattern = pathHelper.safeTrimTrailingSeparator(pattern); // Search path (literal path prior to the first glob segment) let foundGlob = false; const searchSegments = this.segments .map(x => Pattern.getLiteral(x)) .filter(x => !foundGlob && !(foundGlob = x === '')); this.searchPath = new internal_path_1.Path(searchSegments).toString(); // Root RegExp (required when determining partial match) this.rootRegExp = new RegExp(Pattern.regExpEscape(searchSegments[0]), IS_WINDOWS ? 'i' : ''); this.isImplicitPattern = isImplicitPattern; // Create minimatch const minimatchOptions = { dot: true, nobrace: true, nocase: IS_WINDOWS, nocomment: true, noext: true, nonegate: true }; pattern = IS_WINDOWS ? pattern.replace(/\\/g, '/') : pattern; this.minimatch = new minimatch_1.Minimatch(pattern, minimatchOptions); } /** * Matches the pattern against the specified path */ match(itemPath) { // Last segment is globstar? if (this.segments[this.segments.length - 1] === '**') { // Normalize slashes itemPath = pathHelper.normalizeSeparators(itemPath); // Append a trailing slash. Otherwise Minimatch will not match the directory immediately // preceding the globstar. For example, given the pattern `/foo/**`, Minimatch returns // false for `/foo` but returns true for `/foo/`. Append a trailing slash to handle that quirk. if (!itemPath.endsWith(path.sep) && this.isImplicitPattern === false) { // Note, this is safe because the constructor ensures the pattern has an absolute root. // For example, formats like C: and C:foo on Windows are resolved to an absolute root. itemPath = `${itemPath}${path.sep}`; } } else { // Normalize slashes and trim unnecessary trailing slash itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); } // Match if (this.minimatch.match(itemPath)) { return this.trailingSeparator ? internal_match_kind_1.MatchKind.Directory : internal_match_kind_1.MatchKind.All; } return internal_match_kind_1.MatchKind.None; } /** * Indicates whether the pattern may match descendants of the specified path */ partialMatch(itemPath) { // Normalize slashes and trim unnecessary trailing slash itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); // matchOne does not handle root path correctly if (pathHelper.dirname(itemPath) === itemPath) { return this.rootRegExp.test(itemPath); } return this.minimatch.matchOne(itemPath.split(IS_WINDOWS ? /\\+/ : /\/+/), this.minimatch.set[0], true); } /** * Escapes glob patterns within a path */ static globEscape(s) { return (IS_WINDOWS ? s : s.replace(/\\/g, '\\\\')) // escape '\' on Linux/macOS .replace(/(\[)(?=[^/]+\])/g, '[[]') // escape '[' when ']' follows within the path segment .replace(/\?/g, '[?]') // escape '?' .replace(/\*/g, '[*]'); // escape '*' } /** * Normalizes slashes and ensures absolute root */ static fixupPattern(pattern, homedir) { // Empty assert_1.default(pattern, 'pattern cannot be empty'); // Must not contain `.` segment, unless first segment // Must not contain `..` segment const literalSegments = new internal_path_1.Path(pattern).segments.map(x => Pattern.getLiteral(x)); assert_1.default(literalSegments.every((x, i) => (x !== '.' || i === 0) && x !== '..'), `Invalid pattern '${pattern}'. Relative pathing '.' and '..' is not allowed.`); // Must not contain globs in root, e.g. Windows UNC path \\foo\b*r assert_1.default(!pathHelper.hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`); // Normalize slashes pattern = pathHelper.normalizeSeparators(pattern); // Replace leading `.` segment if (pattern === '.' || pattern.startsWith(`.${path.sep}`)) { pattern = Pattern.globEscape(process.cwd()) + pattern.substr(1); } // Replace leading `~` segment else if (pattern === '~' || pattern.startsWith(`~${path.sep}`)) { homedir = homedir || os.homedir(); assert_1.default(homedir, 'Unable to determine HOME directory'); assert_1.default(pathHelper.hasAbsoluteRoot(homedir), `Expected HOME directory to be a rooted path. Actual '${homedir}'`); pattern = Pattern.globEscape(homedir) + pattern.substr(1); } // Replace relative drive root, e.g. pattern is C: or C:foo else if (IS_WINDOWS && (pattern.match(/^[A-Z]:$/i) || pattern.match(/^[A-Z]:[^\\]/i))) { let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', pattern.substr(0, 2)); if (pattern.length > 2 && !root.endsWith('\\')) { root += '\\'; } pattern = Pattern.globEscape(root) + pattern.substr(2); } // Replace relative root, e.g. pattern is \ or \foo else if (IS_WINDOWS && (pattern === '\\' || pattern.match(/^\\[^\\]/))) { let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', '\\'); if (!root.endsWith('\\')) { root += '\\'; } pattern = Pattern.globEscape(root) + pattern.substr(1); } // Otherwise ensure absolute root else { pattern = pathHelper.ensureAbsoluteRoot(Pattern.globEscape(process.cwd()), pattern); } return pathHelper.normalizeSeparators(pattern); } /** * Attempts to unescape a pattern segment to create a literal path segment. * Otherwise returns empty string. */ static getLiteral(segment) { let literal = ''; for (let i = 0; i < segment.length; i++) { const c = segment[i]; // Escape if (c === '\\' && !IS_WINDOWS && i + 1 < segment.length) { literal += segment[++i]; continue; } // Wildcard else if (c === '*' || c === '?') { return ''; } // Character set else if (c === '[' && i + 1 < segment.length) { let set = ''; let closed = -1; for (let i2 = i + 1; i2 < segment.length; i2++) { const c2 = segment[i2]; // Escape if (c2 === '\\' && !IS_WINDOWS && i2 + 1 < segment.length) { set += segment[++i2]; continue; } // Closed else if (c2 === ']') { closed = i2; break; } // Otherwise else { set += c2; } } // Closed? if (closed >= 0) { // Cannot convert if (set.length > 1) { return ''; } // Convert to literal if (set) { literal += set; i = closed; continue; } } // Otherwise fall thru } // Append literal += c; } return literal; } /** * Escapes regexp special characters * https://javascript.info/regexp-escaping */ static regExpEscape(s) { return s.replace(/[[\\^$.|?*+()]/g, '\\$&'); } } exports.Pattern = Pattern; //# sourceMappingURL=internal-pattern.js.map /***/ }), /***/ 89117: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SearchState = void 0; class SearchState { constructor(path, level) { this.path = path; this.level = level; } } exports.SearchState = SearchState; //# sourceMappingURL=internal-search-state.js.map /***/ }), /***/ 35526: /***/ (function(__unused_webpack_module, exports) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0; class BasicCredentialHandler { constructor(username, password) { 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 /***/ }), /***/ 96255: /***/ (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__(13685)); const https = __importStar(__nccwpck_require__(95687)); const pm = __importStar(__nccwpck_require__(19835)); const tunnel = __importStar(__nccwpck_require__(74294)); 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()); }); })); }); } } 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 /***/ }), /***/ 19835: /***/ ((__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) { return new URL(proxyVar); } else { return undefined; } } exports.getProxyUrl = getProxyUrl; function checkBypass(reqUrl) { if (!reqUrl.hostname) { return false; } 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 (upperReqHosts.some(x => x === upperNoProxyItem)) { return true; } } return false; } exports.checkBypass = checkBypass; //# sourceMappingURL=proxy.js.map /***/ }), /***/ 45818: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildCryptographicMaterialsCacheKeyHelpers = void 0; const serialize_1 = __nccwpck_require__(26683); const portable_compare_1 = __nccwpck_require__(89046); // 512 bits of 0 for padding between hashes in decryption materials cache ID generation. const BIT_PAD_512 = Buffer.alloc(64); function buildCryptographicMaterialsCacheKeyHelpers(fromUtf8, toUtf8, sha512) { const { serializeEncryptionContext, serializeEncryptedDataKey } = (0, serialize_1.serializeFactory)(fromUtf8); return { buildEncryptionMaterialCacheKey, buildDecryptionMaterialCacheKey, encryptedDataKeysHash, encryptionContextHash, }; async function buildEncryptionMaterialCacheKey(partition, { suite, encryptionContext }) { const algorithmInfo = suite ? [new Uint8Array([1]), (0, serialize_1.uInt16BE)(suite.id)] : [new Uint8Array([0])]; const key = await sha512(await sha512(fromUtf8(partition)), ...algorithmInfo, await encryptionContextHash(encryptionContext)); return toUtf8(key); } async function buildDecryptionMaterialCacheKey(partition, { suite, encryptedDataKeys, encryptionContext }) { const { id } = suite; const key = await sha512(await sha512(fromUtf8(partition)), (0, serialize_1.uInt16BE)(id), ...(await encryptedDataKeysHash(encryptedDataKeys)), BIT_PAD_512, await encryptionContextHash(encryptionContext)); return toUtf8(key); } async function encryptedDataKeysHash(encryptedDataKeys) { const hashes = await Promise.all(encryptedDataKeys .map(serializeEncryptedDataKey) .map(async (edk) => sha512(edk))); return hashes.sort(portable_compare_1.compare); } async function encryptionContextHash(context) { /* The AAD section is uInt16BE(length) + AAD * see: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/message-format.html#header-aad * However, the RAW Keyring wants _only_ the ADD. * So, I just slice off the length. */ const serializedContext = serializeEncryptionContext(context).slice(2); return sha512(serializedContext); } } exports.buildCryptographicMaterialsCacheKeyHelpers = buildCryptographicMaterialsCacheKeyHelpers; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYnVpbGRfY3J5cHRvZ3JhcGhpY19tYXRlcmlhbHNfY2FjaGVfa2V5X2hlbHBlcnMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvYnVpbGRfY3J5cHRvZ3JhcGhpY19tYXRlcmlhbHNfY2FjaGVfa2V5X2hlbHBlcnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7OztBQVN0QyxxREFBa0U7QUFDbEUseURBQTRDO0FBRTVDLHlGQUF5RjtBQUN6RixNQUFNLFdBQVcsR0FBRyxNQUFNLENBQUMsS0FBSyxDQUFDLEVBQUUsQ0FBQyxDQUFBO0FBRXBDLFNBQWdCLDBDQUEwQyxDQUd4RCxRQUF1QyxFQUN2QyxNQUFxQyxFQUNyQyxNQUFpRTtJQUVqRSxNQUFNLEVBQUUsMEJBQTBCLEVBQUUseUJBQXlCLEVBQUUsR0FDN0QsSUFBQSw0QkFBZ0IsRUFBQyxRQUFRLENBQUMsQ0FBQTtJQUU1QixPQUFPO1FBQ0wsK0JBQStCO1FBQy9CLCtCQUErQjtRQUMvQixxQkFBcUI7UUFDckIscUJBQXFCO0tBQ3RCLENBQUE7SUFFRCxLQUFLLFVBQVUsK0JBQStCLENBQzVDLFNBQWlCLEVBQ2pCLEVBQUUsS0FBSyxFQUFFLGlCQUFpQixFQUF3QjtRQUVsRCxNQUFNLGFBQWEsR0FBRyxLQUFLO1lBQ3pCLENBQUMsQ0FBQyxDQUFDLElBQUksVUFBVSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMs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0FBQyx5QkFBeUIsQ0FBQzthQUM5QixHQUFHLENBQUMsS0FBSyxFQUFFLEdBQUcsRUFBRSxFQUFFLENBQUMsTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQ25DLENBQUE7UUFDRCxPQUFPLE1BQU0sQ0FBQyxJQUFJLENBQUMsMEJBQU8sQ0FBQyxDQUFBO0lBQzdCLENBQUM7SUFFRCxLQUFLLFVBQVUscUJBQXFCLENBQUMsT0FBMEI7UUFDN0Q7Ozs7V0FJRztRQUNILE1BQU0saUJBQWlCLEdBQUcsMEJBQTBCLENBQUMsT0FBTyxDQUFDLENBQUMsS0FBSyxDQUFDLENBQUMsQ0FBQyxDQUFBO1FBQ3RFLE9BQU8sTUFBTSxDQUFDLGlCQUFpQixDQUFDLENBQUE7SUFDbEMsQ0FBQztBQUNILENBQUM7QUFyRUQsZ0dBcUVDIn0= /***/ }), /***/ 63886: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.cacheEntryHasExceededLimits = exports.decryptMaterials = exports.getEncryptionMaterials = exports.decorateProperties = void 0; const material_management_1 = __nccwpck_require__(77519); const serialize_1 = __nccwpck_require__(26683); function decorateProperties(obj, input) { const { cache, backingMaterialsManager, maxAge, maxBytesEncrypted, maxMessagesEncrypted, partition, } = input; /* Precondition: A caching material manager needs a cache. */ (0, material_management_1.needs)(cache, 'You must provide a cache.'); /* Precondition: A caching material manager needs a way to get material. */ (0, material_management_1.needs)(backingMaterialsManager, 'You must provide a backing material source.'); /* Precondition: You *can not* cache something forever. */ (0, material_management_1.needs)(maxAge > 0, 'You must configure a maxAge'); /* Precondition: maxBytesEncrypted must be inside bounds. i.e. positive and not more than the maximum. */ (0, material_management_1.needs)(!maxBytesEncrypted || (maxBytesEncrypted > 0 && serialize_1.Maximum.BYTES_PER_CACHED_KEY_LIMIT >= maxBytesEncrypted), 'maxBytesEncrypted is outside of bounds.'); /* Precondition: maxMessagesEncrypted must be inside bounds. i.e. positive and not more than the maximum. */ (0, material_management_1.needs)(!maxMessagesEncrypted || (maxMessagesEncrypted > 0 && serialize_1.Maximum.MESSAGES_PER_CACHED_KEY_LIMIT >= maxMessagesEncrypted), 'maxMessagesEncrypted is outside of bounds.'); /* Precondition: partition must be a string. */ (0, material_management_1.needs)(partition && typeof partition === 'string', 'partition must be a string.'); (0, material_management_1.readOnlyProperty)(obj, '_cache', cache); (0, material_management_1.readOnlyProperty)(obj, '_backingMaterialsManager', backingMaterialsManager); (0, material_management_1.readOnlyProperty)(obj, '_maxAge', maxAge); (0, material_management_1.readOnlyProperty)(obj, '_maxBytesEncrypted', maxBytesEncrypted || serialize_1.Maximum.BYTES_PER_CACHED_KEY_LIMIT); (0, material_management_1.readOnlyProperty)(obj, '_maxMessagesEncrypted', maxMessagesEncrypted || serialize_1.Maximum.MESSAGES_PER_CACHED_KEY_LIMIT); (0, material_management_1.readOnlyProperty)(obj, '_partition', partition); } exports.decorateProperties = decorateProperties; function getEncryptionMaterials({ buildEncryptionMaterialCacheKey, }) { return async function getEncryptionMaterials(request) { const { suite, encryptionContext, plaintextLength, commitmentPolicy } = request; /* Check for early return (Postcondition): If I can not cache the EncryptionMaterial, do not even look. */ if ((suite && !suite.cacheSafe) || typeof plaintextLength !== 'number' || plaintextLength < 0) { const material = await this._backingMaterialsManager.getEncryptionMaterials(request); return material; } const cacheKey = await buildEncryptionMaterialCacheKey(this._partition, { suite, encryptionContext, }); const entry = this._cache.getEncryptionMaterial(cacheKey, plaintextLength); /* Check for early return (Postcondition): If I have a valid EncryptionMaterial, return it. */ if (entry && !this._cacheEntryHasExceededLimits(entry)) { return cloneResponse(entry.response); } else { this._cache.del(cacheKey); } const material = await this._backingMaterialsManager /* Strip any information about the plaintext from the backing request, * because the resulting response may be used to encrypt multiple plaintexts. */ .getEncryptionMaterials({ suite, encryptionContext, commitmentPolicy }); /* Check for early return (Postcondition): If I can not cache the EncryptionMaterial, just return it. */ if (!material.suite.cacheSafe) return material; /* It is possible for an entry to exceed limits immediately. * The simplest case is to need to encrypt more than then maxBytesEncrypted. * In this case, I return the response to encrypt the data, * but do not put a know invalid item into the cache. */ const testEntry = { response: material, now: Date.now(), messagesEncrypted: 1, bytesEncrypted: plaintextLength, }; if (!this._cacheEntryHasExceededLimits(testEntry)) { this._cache.putEncryptionMaterial(cacheKey, material, plaintextLength, this._maxAge); return cloneResponse(material); } else { /* Postcondition: If the material has exceeded limits it MUST NOT be cloned. * If it is cloned, and the clone is returned, * then there exist a copy of the unencrypted data key. * It is true that this data would be caught by GC, it is better to just not rely on that. */ return material; } }; } exports.getEncryptionMaterials = getEncryptionMaterials; function decryptMaterials({ buildDecryptionMaterialCacheKey, }) { return async function decryptMaterials(request) { const { suite } = request; /* Check for early return (Postcondition): If I can not cache the DecryptionMaterial, do not even look. */ if (!suite.cacheSafe) { const material = await this._backingMaterialsManager.decryptMaterials(request); return material; } const cacheKey = await buildDecryptionMaterialCacheKey(this._partition, request); const entry = this._cache.getDecryptionMaterial(cacheKey); /* Check for early return (Postcondition): If I have a valid DecryptionMaterial, return it. */ if (entry && !this._cacheEntryHasExceededLimits(entry)) { return cloneResponse(entry.response); } else { this._cache.del(cacheKey); } const material = await this._backingMaterialsManager.decryptMaterials(request); this._cache.putDecryptionMaterial(cacheKey, material, this._maxAge); return cloneResponse(material); }; } exports.decryptMaterials = decryptMaterials; function cacheEntryHasExceededLimits() { return function cacheEntryHasExceededLimits({ now, messagesEncrypted, bytesEncrypted }) { const age = Date.now() - now; return (age > this._maxAge || messagesEncrypted > this._maxMessagesEncrypted || bytesEncrypted > this._maxBytesEncrypted); }; } exports.cacheEntryHasExceededLimits = cacheEntryHasExceededLimits; /** * I need to clone the underlying material. * Because when the Encryption SDK is done with material, it will zero it out. * Plucking off the material and cloning just that and then returning the rest of the response * can just be handled in one place. * @param material EncryptionMaterial|DecryptionMaterial * @return EncryptionMaterial|DecryptionMaterial */ function cloneResponse(material) { return (0, material_management_1.cloneMaterial)(material); } //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY2FjaGluZ19jcnlwdG9ncmFwaGljX21hdGVyaWFsc19kZWNvcmF0b3JzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL2NhY2hpbmdfY3J5cHRvZ3JhcGhpY19tYXRlcmlhbHNfZGVjb3JhdG9ycy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUEsb0VBQW9FO0FBQ3BFLHNDQUFzQzs7O0FBRXRDLHlFQWF3QztBQUN4QyxxREFBK0M7QUFPL0MsU0FBZ0Isa0JBQWtCLENBQ2hDLEdBQStCLEVBQy9CLEtBQThDO0lBRTlDLE1BQU0sRUFDSixLQUFLLEVBQ0wsdUJBQXVCLEVBQ3ZCLE1BQU0sRUFDTixpQkFBaUIsRUFDakIsb0JBQW9CLEVBQ3BCLFNBQVMsR0FDVixHQUFHLEtBQUssQ0FBQTtJQUVULDZEQUE2RDtJQUM3RCxJQUFBLDJCQUFLLEVBQUMsS0FBSyxFQUFFLDJCQUEyQixDQUFDLENBQUE7SUFDekMsMkVBQTJFO0lBQzNFLElBQUEsMkJBQUssRUFBQyx1QkFBdUIsRUFBRSw2Q0FBNkMsQ0FBQyxDQUFBO0lBQzdFLDBEQUEwRDtJQUMxRCxJQUFBLDJCQUFLLEVBQUMsTUFBTSxHQUFHLENBQUMsRUFBRSw2QkFBNkIsQ0FBQyxDQUFBO0lBQ2hELDBHQUEwRztJQUMxRyxJQUFBLDJCQUFLLEVBQ0gsQ0FBQyxpQkFBaUI7UUFDaEIsQ0FBQyxpQkFBaUIsR0FBRyxDQUFDO1lBQ3BCLG1CQUFPLENBQUMsMEJBQTBCLElBQUksaUJBQWlCLENBQUMsRUFDNUQseUNBQXlDLENBQzFDLENBQUE7SUFDRCw2R0FBNkc7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0FBQztBQWRELGtFQWNDO0FBRUQ7Ozs7Ozs7R0FPRztBQUNILFNBQVMsYUFBYSxDQUdwQixRQUFXO0lBQ1gsT0FBTyxJQUFBLG1DQUFhLEVBQUMsUUFBUSxDQUFDLENBQUE7QUFDaEMsQ0FBQyJ9 /***/ }), /***/ 10791: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY3J5cHRvZ3JhcGhpY19tYXRlcmlhbHNfY2FjaGUuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvY3J5cHRvZ3JhcGhpY19tYXRlcmlhbHNfY2FjaGUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0MifQ== /***/ }), /***/ 29460: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getLocalCryptographicMaterialsCache = void 0; const lru_cache_1 = __importDefault(__nccwpck_require__(7129)); const material_management_1 = __nccwpck_require__(77519); function getLocalCryptographicMaterialsCache(capacity, proactiveFrequency = 1000 * 60) { const cache = new lru_cache_1.default({ max: capacity, dispose(_key, value) { /* Zero out the unencrypted dataKey, when the material is removed from the cache. */ value.response.zeroUnencryptedDataKey(); }, }); (function proactivelyTryAndEvictTail() { const timeout = setTimeout(() => { mayEvictTail(); proactivelyTryAndEvictTail(); }, proactiveFrequency); /* In Node.js the event loop will _only_ exit if there are no outstanding events. * This means that if I did nothing the event loop would *always* be blocked. * This is unfortunate and very bad for things like Lambda. * So, I tell Node.js to not wait for this timer. * See: https://nodejs.org/api/timers.html#timers_timeout_unref */ // @ts-ignore timeout.unref && timeout.unref(); })(); return { putEncryptionMaterial(key, material, plaintextLength, maxAge) { /* Precondition: putEncryptionMaterial plaintextLength can not be negative. */ (0, material_management_1.needs)(plaintextLength >= 0, 'Malformed plaintextLength'); /* Precondition: Only cache EncryptionMaterial. */ (0, material_management_1.needs)((0, material_management_1.isEncryptionMaterial)(material), 'Malformed response.'); /* Precondition: Only cache EncryptionMaterial that is cacheSafe. */ (0, material_management_1.needs)(material.suite.cacheSafe, 'Can not cache non-cache safe material'); const entry = Object.seal({ response: material, bytesEncrypted: plaintextLength, messagesEncrypted: 1, now: Date.now(), }); cache.set(key, entry, maxAge); }, putDecryptionMaterial(key, material, maxAge) { /* Precondition: Only cache DecryptionMaterial. */ (0, material_management_1.needs)((0, material_management_1.isDecryptionMaterial)(material), 'Malformed response.'); /* Precondition: Only cache DecryptionMaterial that is cacheSafe. */ (0, material_management_1.needs)(material.suite.cacheSafe, 'Can not cache non-cache safe material'); const entry = Object.seal({ response: material, bytesEncrypted: 0, messagesEncrypted: 0, now: Date.now(), }); cache.set(key, entry, maxAge); }, getEncryptionMaterial(key, plaintextLength) { /* Precondition: plaintextLength can not be negative. */ (0, material_management_1.needs)(plaintextLength >= 0, 'Malformed plaintextLength'); const entry = cache.get(key); /* Check for early return (Postcondition): If this key does not have an EncryptionMaterial, return false. */ if (!entry) return false; /* Postcondition: Only return EncryptionMaterial. */ (0, material_management_1.needs)((0, material_management_1.isEncryptionMaterial)(entry.response), 'Malformed response.'); entry.bytesEncrypted += plaintextLength; entry.messagesEncrypted += 1; return entry; }, getDecryptionMaterial(key) { const entry = cache.get(key); /* Check for early return (Postcondition): If this key does not have a DecryptionMaterial, return false. */ if (!entry) return false; /* Postcondition: Only return DecryptionMaterial. */ (0, material_management_1.needs)((0, material_management_1.isDecryptionMaterial)(entry.response), 'Malformed response.'); return entry; }, del(key) { cache.del(key); }, }; function mayEvictTail() { // @ts-ignore const { tail } = cache.dumpLru(); /* Check for early return (Postcondition) UNTESTED: If there is no tail, then the cache is empty. */ if (!tail) return; /* The underlying Yallist tail Node has a `value`. * This value is a lru-cache Entry and has a `key`. */ const { key } = tail.value; // Peek will evict, but not update the "recently used"-ness of the key. cache.peek(key); } } exports.getLocalCryptographicMaterialsCache = getLocalCryptographicMaterialsCache; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZ2V0X2xvY2FsX2NyeXB0b2dyYXBoaWNfbWF0ZXJpYWxzX2NhY2hlLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL2dldF9sb2NhbF9jcnlwdG9ncmFwaGljX21hdGVyaWFsc19jYWNoZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUEsb0VBQW9FO0FBQ3BFLHNDQUFzQzs7Ozs7O0FBRXRDLDBEQUEyQjtBQUMzQix5RUFPd0M7QUFTeEMsU0FBZ0IsbUNBQW1DLENBR2pELFFBQWdCLEVBQ2hCLHFCQUE2QixJQUFJLEdBQUcsRUFBRTtJQUV0QyxNQUFNLEtBQUssR0FBRyxJQUFJLG1CQUFHLENBQW1CO1FBQ3RDLEdBQUcsRUFBRSxRQUFRO1FBQ2IsT0FBTyxDQUFDLElBQUksRUFBRSxLQUFLO1lBQ2pCLG9GQUFvRjtZQUNwRixLQUFLLENBQUMsUUFBUSxDQUFDLHNCQUFzQixFQUFFLENBQUE7UUFDekMsQ0FBQztLQUNGLENBQUMsQ0FlRDtJQUFBLENBQUMsU0FBUywwQkFBMEI7UUFDbkMsTUFBTSxPQUFPLEdBQUcsVUFBVSxDQUFDLEdBQUcsRUFBRTtZQUM5QixZQUFZLEVBQUUsQ0FBQTtZQUNkLDBCQUEwQixFQUFFLENBQUE7UUFDOUIsQ0FBQyxFQUFFLGtCQUFrQixDQUFDLENBQUE7U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QUFDLEdBQUcsQ0FBQyxDQUFBO1lBQzVCLDJHQUEyRztZQUMzRyxJQUFJLENBQUMsS0FBSztnQkFBRSxPQUFPLEtBQUssQ0FBQTtZQUN4QixvREFBb0Q7WUFDcEQsSUFBQSwyQkFBSyxFQUFDLElBQUEsMENBQW9CLEVBQUMsS0FBSyxDQUFDLFFBQVEsQ0FBQyxFQUFFLHFCQUFxQixDQUFDLENBQUE7WUFFbEUsT0FBTyxLQUFtQyxDQUFBO1FBQzVDLENBQUM7UUFDRCxHQUFHLENBQUMsR0FBVztZQUNiLEtBQUssQ0FBQyxHQUFHLENBQUMsR0FBRyxDQUFDLENBQUE7UUFDaEIsQ0FBQztLQUNGLENBQUE7SUFFRCxTQUFTLFlBQVk7UUFDbkIsYUFBYTtRQUNiLE1BQU0sRUFBRSxJQUFJLEVBQUUsR0FBRyxLQUFLLENBQUMsT0FBTyxFQUFFLENBQUE7UUFDaEMsb0dBQW9HO1FBQ3BHLElBQUksQ0FBQyxJQUFJO1lBQUUsT0FBTTtRQUNqQjs7V0FFRztRQUNILE1BQU0sRUFBRSxHQUFHLEVBQUUsR0FBRyxJQUFJLENBQUMsS0FBSyxDQUFBO1FBQzFCLHVFQUF1RTtRQUN2RSxLQUFLLENBQUMsSUFBSSxDQUFDLEdBQUcsQ0FBQyxDQUFBO0lBQ2pCLENBQUM7QUFDSCxDQUFDO0FBMUhELGtGQTBIQyJ9 /***/ }), /***/ 24339: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 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__(10791), exports); __exportStar(__nccwpck_require__(63886), exports); __exportStar(__nccwpck_require__(45818), exports); __exportStar(__nccwpck_require__(29460), exports); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7Ozs7Ozs7Ozs7Ozs7Ozs7QUFFdEMsa0VBQStDO0FBQy9DLCtFQUE0RDtBQUM1RCxvRkFBaUU7QUFDakUsNEVBQXlEIn0= /***/ }), /***/ 89046: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.compare = void 0; /* Node has Buffer.compare, * but browsers have nothing. * This is a simple compare function that is portable. * This function is *not* constant time. */ function compare(a, b) { const length = a.byteLength > b.byteLength ? b.byteLength : a.byteLength; for (let i = 0; length > i; i += 1) { if (a[i] > b[i]) return 1; if (a[i] < b[i]) return -1; } if (a.byteLength > b.byteLength) return 1; if (a.byteLength < b.byteLength) return -1; return 0; } exports.compare = compare; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicG9ydGFibGVfY29tcGFyZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9wb3J0YWJsZV9jb21wYXJlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7QUFFdEM7Ozs7R0FJRztBQUNILFNBQWdCLE9BQU8sQ0FBQyxDQUFhLEVBQUUsQ0FBYTtJQUNsRCxNQUFNLE1BQU0sR0FBRyxDQUFDLENBQUMsVUFBVSxHQUFHLENBQUMsQ0FBQyxVQUFVLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxVQUFVLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxVQUFVLENBQUE7SUFFeEUsS0FBSyxJQUFJLENBQUMsR0FBRyxDQUFDLEVBQUUsTUFBTSxHQUFHLENBQUMsRUFBRSxDQUFDLElBQUksQ0FBQyxFQUFFO1FBQ2xDLElBQUksQ0FBQyxDQUFDLENBQUMsQ0FBQyxHQUFHLENBQUMsQ0FBQyxDQUFDLENBQUM7WUFBRSxPQUFPLENBQUMsQ0FBQTtRQUN6QixJQUFJLENBQUMsQ0FBQyxDQUFDLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxDQUFDO1lBQUUsT0FBTyxDQUFDLENBQUMsQ0FBQTtLQUMzQjtJQUVELElBQUksQ0FBQyxDQUFDLFVBQVUsR0FBRyxDQUFDLENBQUMsVUFBVTtRQUFFLE9BQU8sQ0FBQyxDQUFBO0lBQ3pDLElBQUksQ0FBQyxDQUFDLFVBQVUsR0FBRyxDQUFDLENBQUMsVUFBVTtRQUFFLE9BQU8sQ0FBQyxDQUFDLENBQUE7SUFFMUMsT0FBTyxDQUFDLENBQUE7QUFDVixDQUFDO0FBWkQsMEJBWUMifQ== /***/ }), /***/ 33125: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NodeCachingMaterialsManager = void 0; const cache_material_1 = __nccwpck_require__(24339); const material_management_node_1 = __nccwpck_require__(12563); const sha512_1 = __nccwpck_require__(64701); const crypto_1 = __nccwpck_require__(6113); const fromUtf8 = (input) => Buffer.from(input, 'utf8'); const toUtf8 = (input) => Buffer.from(input).toString('utf8'); const cacheKeyHelpers = (0, cache_material_1.buildCryptographicMaterialsCacheKeyHelpers)(fromUtf8, toUtf8, sha512_1.sha512); class NodeCachingMaterialsManager { constructor(input) { const backingMaterialsManager = input.backingMaterials instanceof material_management_node_1.KeyringNode ? new material_management_node_1.NodeDefaultCryptographicMaterialsManager(input.backingMaterials) : input.backingMaterials; /* Precondition: A partition value must exist for NodeCachingMaterialsManager. * The maximum hash function at this time is 512. * So I create 64 bytes of random data. */ const { partition = (0, crypto_1.randomBytes)(64).toString('base64') } = input; (0, cache_material_1.decorateProperties)(this, { ...input, backingMaterialsManager, partition, }); } getEncryptionMaterials = (0, cache_material_1.getEncryptionMaterials)(cacheKeyHelpers); decryptMaterials = (0, cache_material_1.decryptMaterials)(cacheKeyHelpers); _cacheEntryHasExceededLimits = (0, cache_material_1.cacheEntryHasExceededLimits)(); } exports.NodeCachingMaterialsManager = NodeCachingMaterialsManager; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY2FjaGluZ19tYXRlcmlhbHNfbWFuYWdlcl9ub2RlLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL2NhY2hpbmdfbWF0ZXJpYWxzX21hbmFnZXJfbm9kZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUEsb0VBQW9FO0FBQ3BFLHNDQUFzQzs7O0FBRXRDLCtEQVNtQztBQUNuQyxtRkFPNkM7QUFDN0MscUNBQWlDO0FBQ2pDLG1DQUFvQztBQUVwQyxNQUFNLFFBQVEsR0FBRyxDQUFDLEtBQWEsRUFBRSxFQUFFLENBQUMsTUFBTSxDQUFDLElBQUksQ0FBQyxLQUFLLEVBQUUsTUFBTSxDQUFDLENBQUE7QUFDOUQsTUFBTSxNQUFNLEdBQUcsQ0FBQyxLQUFpQixFQUFFLEVBQUUsQ0FBQyxNQUFNLENBQUMsSUFBSSxDQUFDLEtBQUssQ0FBQyxDQUFDLFFBQVEsQ0FBQyxNQUFNLENBQUMsQ0FBQTtBQUV6RSxNQUFNLGVBQWUsR0FBRyxJQUFBLDJEQUEwQyxFQUNoRSxRQUFRLEVBQ1IsTUFBTSxFQUNOLGVBQU0sQ0FDUCxDQUFBO0FBRUQsTUFBYSwyQkFBMkI7SUFVdEMsWUFBWSxLQUF1RDtRQUNqRSxNQUFNLHVCQUF1QixHQUMzQixLQUFLLENBQUMsZ0JBQWdCLFlBQVksc0NBQVc7WUFDM0MsQ0FBQyxDQUFDLElBQUksbUVBQXdDLENBQUMsS0FBSyxDQUFDLGdCQUFnQixDQUFDO1lBQ3RFLENBQUMsQ0FBRSxLQUFLLENBQUMsZ0JBQTZELENBQUE7UUFFMUU7OztXQUdHO1FBQ0gsTUFBTSxFQUFFLFNBQVMsR0FBRyxJQUFBLG9CQUFXLEVBQUMsRUFBRSxDQUFDLENBQUMsUUFBUSxDQUFDLFFBQVEsQ0FBQyxFQUFFLEdBQUcsS0FBSyxDQUFBO1FBRWhFLElBQUEsbUNBQWtCLEVBQUMsSUFBSSxFQUFFO1lBQ3ZCLEdBQUcsS0FBSztZQUNSLHVCQUF1QjtZQUN2QixTQUFTO1NBQ1YsQ0FBQyxDQUFBO0lBQ0osQ0FBQztJQUVELHNCQUFzQixHQUNwQixJQUFBLHVDQUFzQixFQUFxQixlQUFlLENBQUMsQ0FBQTtJQUM3RCxnQkFBZ0IsR0FDZCxJQUFBLGlDQUFnQixFQUFxQixlQUFlLENBQUMsQ0FBQTtJQUN2RCw0QkFBNEIsR0FDMUIsSUFBQSw0Q0FBMkIsR0FBc0IsQ0FBQTtDQUNwRDtBQW5DRCxrRUFtQ0MifQ== /***/ }), /***/ 71470: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 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.getLocalCryptographicMaterialsCache = void 0; __exportStar(__nccwpck_require__(33125), exports); var cache_material_1 = __nccwpck_require__(24339); Object.defineProperty(exports, "getLocalCryptographicMaterialsCache", ({ enumerable: true, get: function () { return cache_material_1.getLocalCryptographicMaterialsCache; } })); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7Ozs7Ozs7Ozs7Ozs7Ozs7O0FBRXRDLG1FQUFnRDtBQUNoRCw2REFBZ0Y7QUFBdkUscUlBQUEsbUNBQW1DLE9BQUEifQ== /***/ }), /***/ 64701: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.sha512 = void 0; const crypto_1 = __nccwpck_require__(6113); const sha512 = async (...data) => data .map((item) => (typeof item === 'string' ? Buffer.from(item) : item)) .reduce((hash, item) => hash.update(item), (0, crypto_1.createHash)('sha512')) .digest(); exports.sha512 = sha512; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2hhNTEyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL3NoYTUxMi50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUEsb0VBQW9FO0FBQ3BFLHNDQUFzQzs7O0FBRXRDLG1DQUFtQztBQUU1QixNQUFNLE1BQU0sR0FBRyxLQUFLLEVBQUUsR0FBRyxJQUE2QixFQUFFLEVBQUUsQ0FDL0QsSUFBSTtLQUNELEdBQUcsQ0FBQyxDQUFDLElBQUksRUFBRSxFQUFFLENBQUMsQ0FBQyxPQUFPLElBQUksS0FBSyxRQUFRLENBQUMsQ0FBQyxDQUFDLE1BQU0sQ0FBQyxJQUFJLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQyxDQUFDLElBQUksQ0FBQyxDQUFDO0tBQ3BFLE1BQU0sQ0FBQyxDQUFDLElBQUksRUFBRSxJQUFJLEVBQUUsRUFBRSxDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsSUFBSSxDQUFDLEVBQUUsSUFBQSxtQkFBVSxFQUFDLFFBQVEsQ0FBQyxDQUFDO0tBQy9ELE1BQU0sRUFBRSxDQUFBO0FBSkEsUUFBQSxNQUFNLFVBSU4ifQ== /***/ }), /***/ 17783: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 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.buildClient = void 0; __exportStar(__nccwpck_require__(3096), exports); __exportStar(__nccwpck_require__(62355), exports); __exportStar(__nccwpck_require__(12563), exports); __exportStar(__nccwpck_require__(71470), exports); __exportStar(__nccwpck_require__(29551), exports); __exportStar(__nccwpck_require__(86979), exports); __exportStar(__nccwpck_require__(55276), exports); const encrypt_node_1 = __nccwpck_require__(3096); const decrypt_node_1 = __nccwpck_require__(62355); function buildClient(options) { return { ...(0, encrypt_node_1.buildEncrypt)(options), ...(0, decrypt_node_1.buildDecrypt)(options), }; } exports.buildClient = buildClient; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7Ozs7Ozs7Ozs7Ozs7Ozs7O0FBRXRDLDJEQUF3QztBQUN4QywyREFBd0M7QUFDeEMsdUVBQW9EO0FBQ3BELDZFQUEwRDtBQUMxRCwrREFBNEM7QUFDNUMsbUVBQWdEO0FBQ2hELG1FQUFnRDtBQU9oRCwyREFBdUQ7QUFDdkQsMkRBQXVEO0FBRXZELFNBQWdCLFdBQVcsQ0FDekIsT0FBMEM7SUFFMUMsT0FBTztRQUNMLEdBQUcsSUFBQSwyQkFBWSxFQUFDLE9BQU8sQ0FBQztRQUN4QixHQUFHLElBQUEsMkJBQVksRUFBQyxPQUFPLENBQUM7S0FDekIsQ0FBQTtBQUNILENBQUM7QUFQRCxrQ0FPQyJ9 /***/ }), /***/ 32374: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AwsCrc32 = void 0; var tslib_1 = __nccwpck_require__(5066); var util_1 = __nccwpck_require__(41236); var index_1 = __nccwpck_require__(47327); var AwsCrc32 = /** @class */ (function () { function AwsCrc32() { this.crc32 = new index_1.Crc32(); } AwsCrc32.prototype.update = function (toHash) { if ((0, util_1.isEmptyData)(toHash)) return; this.crc32.update((0, util_1.convertToBuffer)(toHash)); }; AwsCrc32.prototype.digest = function () { return tslib_1.__awaiter(this, void 0, void 0, function () { return tslib_1.__generator(this, function (_a) { return [2 /*return*/, (0, util_1.numToUint8)(this.crc32.digest())]; }); }); }; AwsCrc32.prototype.reset = function () { this.crc32 = new index_1.Crc32(); }; return AwsCrc32; }()); exports.AwsCrc32 = AwsCrc32; //# sourceMappingURL=aws_crc32.js.map /***/ }), /***/ 47327: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AwsCrc32 = exports.Crc32 = exports.crc32 = void 0; var tslib_1 = __nccwpck_require__(5066); var util_1 = __nccwpck_require__(41236); function crc32(data) { return new Crc32().update(data).digest(); } exports.crc32 = crc32; var Crc32 = /** @class */ (function () { function Crc32() { this.checksum = 0xffffffff; } Crc32.prototype.update = function (data) { var e_1, _a; try { for (var data_1 = tslib_1.__values(data), data_1_1 = data_1.next(); !data_1_1.done; data_1_1 = data_1.next()) { var byte = data_1_1.value; this.checksum = (this.checksum >>> 8) ^ lookupTable[(this.checksum ^ byte) & 0xff]; } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (data_1_1 && !data_1_1.done && (_a = data_1.return)) _a.call(data_1); } finally { if (e_1) throw e_1.error; } } return this; }; Crc32.prototype.digest = function () { return (this.checksum ^ 0xffffffff) >>> 0; }; return Crc32; }()); exports.Crc32 = Crc32; // prettier-ignore var a_lookUpTable = [ 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D, ]; var lookupTable = (0, util_1.uint32ArrayFrom)(a_lookUpTable); var aws_crc32_1 = __nccwpck_require__(32374); Object.defineProperty(exports, "AwsCrc32", ({ enumerable: true, get: function () { return aws_crc32_1.AwsCrc32; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 5066: /***/ ((module) => { /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global global, define, System, Reflect, Promise */ var __extends; var __assign; var __rest; var __decorate; var __param; var __metadata; var __awaiter; var __generator; var __exportStar; var __values; var __read; var __spread; var __spreadArrays; var __await; var __asyncGenerator; var __asyncDelegator; var __asyncValues; var __makeTemplateObject; var __importStar; var __importDefault; var __classPrivateFieldGet; var __classPrivateFieldSet; 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 (b.hasOwnProperty(p)) d[p] = b[p]; }; __extends = function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; __assign = Object.assign || function (t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; __rest = function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; __decorate = function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; __param = function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; __metadata = function (metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); }; __awaiter = function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; __generator = function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; __createBinding = function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; }; __exportStar = function (m, exports) { for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p]; }; __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; }; __spread = function () { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; }; __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; }; __await = function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }; __asyncGenerator = function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; __asyncDelegator = function (o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } }; __asyncValues = function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } }; __makeTemplateObject = function (cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; __importStar = function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; __importDefault = function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; __classPrivateFieldGet = function (receiver, privateMap) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return privateMap.get(receiver); }; __classPrivateFieldSet = function (receiver, privateMap, value) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to set private field on non-instance"); } privateMap.set(receiver, value); return value; }; exporter("__extends", __extends); exporter("__assign", __assign); exporter("__rest", __rest); exporter("__decorate", __decorate); exporter("__param", __param); exporter("__metadata", __metadata); exporter("__awaiter", __awaiter); exporter("__generator", __generator); exporter("__exportStar", __exportStar); exporter("__createBinding", __createBinding); exporter("__values", __values); exporter("__read", __read); exporter("__spread", __spread); exporter("__spreadArrays", __spreadArrays); exporter("__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); }); /***/ }), /***/ 50712: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getDecipherStream = void 0; // @ts-ignore const readable_stream_1 = __nccwpck_require__(51642); const material_management_node_1 = __nccwpck_require__(12563); const serialize_1 = __nccwpck_require__(26683); const verify_stream_1 = __nccwpck_require__(77860); const fromUtf8 = (input) => Buffer.from(input, 'utf8'); const aadUtility = (0, serialize_1.aadFactory)(fromUtf8); const PortableTransformWithType = readable_stream_1.Transform; const ioTick = async () => new Promise((resolve) => setImmediate(resolve)); const noop = () => { }; // eslint-disable-line @typescript-eslint/no-empty-function function getDecipherStream() { let decipherInfo; let decipherState = {}; let pathologicalDrain = noop; let frameComplete = false; return new (class DecipherStream extends PortableTransformWithType { constructor() { super(); this.on('pipe', (source) => { /* Precondition: The source must be a VerifyStream to emit the required events. */ (0, material_management_node_1.needs)(source instanceof verify_stream_1.VerifyStream, 'Unsupported source'); source .once('DecipherInfo', (info) => { decipherInfo = info; }) .on('BodyInfo', this._onBodyHeader) .on('AuthTag', (authTag, next) => { this._onAuthTag(authTag, next).catch((e) => this.emit('error', e)); }); }); } _onBodyHeader = ({ iv, contentLength, sequenceNumber, isFinalFrame, }) => { /* Precondition: decipherInfo must be set before BodyInfo is sent. */ (0, material_management_node_1.needs)(decipherInfo, 'Malformed State.'); /* Precondition: Ciphertext must not be flowing before a BodyHeader is processed. */ (0, material_management_node_1.needs)(!decipherState.decipher, 'Malformed State.'); const { messageId, contentType, getDecipher } = decipherInfo; const aadString = aadUtility.messageAADContentString({ contentType, isFinalFrame, }); const messageAAD = aadUtility.messageAAD(messageId, aadString, sequenceNumber, contentLength); const decipher = getDecipher(iv).setAAD(Buffer.from(messageAAD.buffer, messageAAD.byteOffset, messageAAD.byteLength)); const content = []; decipherState = { decipher, content, contentLength }; }; _transform(chunk, _encoding, callback) { /* Precondition: BodyHeader must be parsed before frame data. */ (0, material_management_node_1.needs)(decipherState.decipher, 'Malformed State.'); decipherState.contentLength -= chunk.length; /* Precondition: Only content should be transformed, so the lengths must always match. * The BodyHeader and AuthTag are striped in the VerifyStream and passed in * through events. This means that if I receive a chunk without having reset * the content accumulation events are out of order. Panic. */ (0, material_management_node_1.needs)(decipherState.contentLength >= 0, 'Lengths do not match'); const { content } = decipherState; content.push(chunk); if (decipherState.contentLength > 0) { // More data to this frame callback(); } else { // The frame is full, waiting for `AuthTag` // event to decrypt and forward the clear frame frameComplete = callback; } } _read(size) { /* The _onAuthTag decrypts and pushes the encrypted frame. * If this.push returns false then this stream * should wait until the destination stream calls read. * This means that _onAuthTag needs to wait for some * indeterminate time. I create a closure around * the resolution function for a promise that * is created in _onAuthTag. This way * here in _read (the implementation of read) * if a frame is being pushed, we can release * it. */ pathologicalDrain(); pathologicalDrain = noop; super._read(size); } _onAuthTag = async (authTag, next) => { const { decipher, content, contentLength } = decipherState; /* Precondition: _onAuthTag must be called only after a frame has been accumulated. * However there is an edge case. The final frame _can_ be zero length. * This means that _transform will never be called. */ (0, material_management_node_1.needs)(frameComplete || contentLength === 0, 'AuthTag before frame.'); /* Precondition UNTESTED: I must have received all content for this frame. * Both contentLength and frameComplete are private variables. * As such manipulating them separately outside of the _transform function * should not be possible. * I do not know of this condition would ever be false while the above is true. * But I do not want to remove the check as there may be a more complicated case * that makes this possible. * If such a case is found. * Write a test. */ (0, material_management_node_1.needs)(contentLength === 0, 'Lengths do not match'); // flush content from state. decipherState = {}; decipher.setAuthTag(authTag); /* In Node.js versions 10.9 and older will fail to decrypt if decipher.update is not called. * https://github.com/nodejs/node/pull/22538 fixes this. */ if (!content.length) decipher.update(Buffer.alloc(0)); const clear = []; for (const cipherChunk of content) { const clearChunk = decipher.update(cipherChunk); clear.push(clearChunk); await ioTick(); } // If the authTag is not valid this will throw const tail = decipher.final(); clear.push(tail); for (const clearChunk of clear) { if (!this.push(clearChunk)) { /* back pressure: if push returns false, wait until _read * has been called. */ await new Promise((resolve) => { pathologicalDrain = resolve; }); } } /* This frame is complete. * Need to notify the VerifyStream continue. * See the note in `AuthTag` for details. * The short answer is that for small frame sizes, * the "next" frame associated auth tag may be * parsed and send before the "current" is processed. * This will cause the auth tag event to fire before * any _transform events fire and a 'Lengths do not match' precondition to fail. */ next(); // This frame is complete. Notify _transform to continue, see needs above for more details if (frameComplete) frameComplete(); // reset for next frame. frameComplete = false; }; _destroy() { // It is possible to have to destroy the stream before // decipherInfo is set. Especially if the HeaderAuth // is not valid. decipherInfo && decipherInfo.dispose(); } })(); } exports.getDecipherStream = getDecipherStream; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVjaXBoZXJfc3RyZWFtLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL2RlY2lwaGVyX3N0cmVhbS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUEsb0VBQW9FO0FBQ3BFLHNDQUFzQzs7O0FBRXRDLGFBQWE7QUFDYixxREFBZ0U7QUFFaEUsbUZBSTZDO0FBQzdDLHFEQUErRDtBQUMvRCxtREFBOEM7QUFFOUMsTUFBTSxRQUFRLEdBQUcsQ0FBQyxLQUFhLEVBQUUsRUFBRSxDQUFDLE1BQU0sQ0FBQyxJQUFJLENBQUMsS0FBSyxFQUFFLE1BQU0sQ0FBQyxDQUFBO0F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BQUksQ0FBQyxJQUFJLENBQUMsSUFBSSxDQUFDLFVBQVUsQ0FBQyxFQUFFO29CQUMxQjs7dUJBRUc7b0JBQ0gsTUFBTSxJQUFJLE9BQU8sQ0FBQyxDQUFDLE9BQU8sRUFBRSxFQUFFO3dCQUM1QixpQkFBaUIsR0FBRyxPQUFPLENBQUE7b0JBQzdCLENBQUMsQ0FBQyxDQUFBO2lCQUNIO2FBQ0Y7WUFFRDs7Ozs7Ozs7ZUFRRztZQUNILElBQUksRUFBRSxDQUFBO1lBRU4sMEZBQTBGO1lBQzFGLElBQUksYUFBYTtnQkFBRSxhQUFhLEVBQUUsQ0FBQTtZQUNsQyx3QkFBd0I7WUFDeEIsYUFBYSxHQUFHLEtBQUssQ0FBQTtRQUN2QixDQUFDLENBQUE7UUFFRCxRQUFRO1lBQ04sc0RBQXNEO1lBQ3RELHFEQUFxRDtZQUNyRCxnQkFBZ0I7WUFDaEIsWUFBWSxJQUFJLFlBQVksQ0FBQyxPQUFPLEVBQUUsQ0FBQTtRQUN4QyxDQUFDO0tBQ0YsQ0FBQyxFQUFFLENBQUE7QUFDTixDQUFDO0FBM0tELDhDQTJLQyJ9 /***/ }), /***/ 40941: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports._decrypt = void 0; const decrypt_stream_1 = __nccwpck_require__(36900); // @ts-ignore const readable_stream_1 = __nccwpck_require__(51642); async function _decrypt(decryptParameters, cmm, ciphertext, { encoding, maxBodySize } = {}) { const stream = (0, decrypt_stream_1._decryptStream)(decryptParameters, cmm, { maxBodySize, }); const plaintext = []; let messageHeader = false; stream .once('MessageHeader', (header) => { messageHeader = header; }) .on('data', (chunk) => plaintext.push(chunk)); // This will check both Uint8Array|Buffer if (ciphertext instanceof Uint8Array) { stream.end(ciphertext); } else if (typeof ciphertext === 'string') { stream.end(Buffer.from(ciphertext, encoding)); } else if (ciphertext.readable) { ciphertext.pipe(stream); } else { throw new Error('Unsupported ciphertext format'); } await finishedAsync(stream); if (!messageHeader) throw new Error('Unknown format'); return { plaintext: Buffer.concat(plaintext), messageHeader, }; } exports._decrypt = _decrypt; async function finishedAsync(stream) { return new Promise((resolve, reject) => { (0, readable_stream_1.finished)(stream, (err) => (err ? reject(err) : resolve())); }); } //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVjcnlwdC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9kZWNyeXB0LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7QUFNdEMscURBQWlEO0FBR2pELGFBQWE7QUFDYixxREFBMEM7QUFjbkMsS0FBSyxVQUFVLFFBQVEsQ0FDNUIsaUJBQW9DLEVBQ3BDLEdBQXVDLEVBQ3ZDLFVBQTJFLEVBQzNFLEVBQUUsUUFBUSxFQUFFLFdBQVcsS0FBcUIsRUFBRTtJQUU5QyxNQUFNLE1BQU0sR0FBRyxJQUFBLCtCQUFjLEVBQUMsaUJBQWlCLEVBQUUsR0FBRyxFQUFFO1FBQ3BELFdBQVc7S0FDWixDQUFDLENBQUE7SUFFRixNQUFNLFNBQVMsR0FBYSxFQUFFLENBQUE7SUFDOUIsSUFBSSxhQUFhLEdBQTBCLEtBQUssQ0FBQTtJQUNoRCxNQUFNO1NBQ0gsSUFBSSxDQUFDLGVBQWUsRUFBRSxDQUFDLE1BQXFCLEVBQUUsRUFBRTtRQUMvQyxhQUFhLEdBQUcsTUFBTSxDQUFBO0lBQ3hCLENBQUMsQ0FBQztTQUNELEVBQUUsQ0FBQyxNQUFNLEVBQUUsQ0FBQyxLQUFhLEVBQUUsRUFBRSxDQUFDLFNBQVMsQ0FBQyxJQUFJLENBQUMsS0FBSyxDQUFDLENBQUMs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25FLENBQUMsQ0FBQyxDQUFBO0FBQ0osQ0FBQyJ9 /***/ }), /***/ 45075: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildDecrypt = void 0; const decrypt_stream_1 = __nccwpck_require__(36900); const decrypt_1 = __nccwpck_require__(40941); const material_management_node_1 = __nccwpck_require__(12563); function buildDecrypt(options = {}) { const { commitmentPolicy = material_management_node_1.CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT, maxEncryptedDataKeys = false, } = typeof options === 'string' ? { commitmentPolicy: options } : options; /* Precondition: node buildDecrypt needs a valid commitmentPolicy. */ (0, material_management_node_1.needs)(material_management_node_1.CommitmentPolicy[commitmentPolicy], 'Invalid commitment policy.'); /* Precondition: node buildDecrypt needs a valid maxEncryptedDataKeys. */ (0, material_management_node_1.needs)(maxEncryptedDataKeys === false || maxEncryptedDataKeys >= 1, 'Invalid maxEncryptedDataKeys value.'); const clientOptions = { commitmentPolicy, maxEncryptedDataKeys, }; return { decryptUnsignedMessageStream: decrypt_stream_1._decryptStream.bind({}, { signaturePolicy: material_management_node_1.SignaturePolicy.ALLOW_ENCRYPT_FORBID_DECRYPT, clientOptions, }), decryptStream: decrypt_stream_1._decryptStream.bind({}, { signaturePolicy: material_management_node_1.SignaturePolicy.ALLOW_ENCRYPT_ALLOW_DECRYPT, clientOptions, }), decrypt: decrypt_1._decrypt.bind({}, { signaturePolicy: material_management_node_1.SignaturePolicy.ALLOW_ENCRYPT_ALLOW_DECRYPT, clientOptions, }), }; } exports.buildDecrypt = buildDecrypt; // @ts-ignore const { decryptUnsignedMessageStream, decryptStream, decrypt } = buildDecrypt(); decryptUnsignedMessageStream({}); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVjcnlwdF9jbGllbnQuanMiLCJzb3V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VELGFBQWE7U0FDZCxDQUNGO1FBQ0QsT0FBTyxFQUFFLGtCQUFRLENBQUMsSUFBSSxDQUNwQixFQUFFLEVBQ0Y7WUFDRSxlQUFlLEVBQUUsMENBQWUsQ0FBQywyQkFBMkI7WUFDNUQsYUFBYTtTQUNkLENBQ0Y7S0FDRixDQUFBO0FBQ0gsQ0FBQztBQW5ERCxvQ0FtREM7QUFFRCxhQUFhO0FBQ2IsTUFBTSxFQUFFLDRCQUE0QixFQUFFLGFBQWEsRUFBRSxPQUFPLEVBQUUsR0FBRyxZQUFZLEVBQUUsQ0FBQTtBQUMvRSw0QkFBNEIsQ0FBQyxFQUFTLENBQUMsQ0FBQSJ9 /***/ }), /***/ 36900: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports._decryptStream = void 0; const material_management_node_1 = __nccwpck_require__(12563); const parse_header_stream_1 = __nccwpck_require__(90144); const verify_stream_1 = __nccwpck_require__(77860); const decipher_stream_1 = __nccwpck_require__(50712); const duplexify_1 = __importDefault(__nccwpck_require__(76599)); // @ts-ignore const readable_stream_1 = __nccwpck_require__(51642); function _decryptStream(decryptParameters, cmm, { maxBodySize } = {}) { /* If the cmm is a Keyring, wrap it with NodeDefaultCMM. */ cmm = cmm instanceof material_management_node_1.KeyringNode ? new material_management_node_1.NodeDefaultCryptographicMaterialsManager(cmm) : cmm; const parseHeaderStream = new parse_header_stream_1.ParseHeaderStream(decryptParameters.signaturePolicy, decryptParameters.clientOptions, cmm); const verifyStream = new verify_stream_1.VerifyStream({ maxBodySize }); const decipherStream = (0, decipher_stream_1.getDecipherStream)(); const stream = new duplexify_1.default(parseHeaderStream, decipherStream); /* pipeline will _either_ stream.destroy or the callback. * decipherStream uses destroy to dispose the material. * So I tack a pass though stream onto the end. */ (0, readable_stream_1.pipeline)(parseHeaderStream, verifyStream, decipherStream, new readable_stream_1.PassThrough(), (err) => { if (err) stream.emit('error', err); }); // Forward header events parseHeaderStream.once('MessageHeader', (header) => stream.emit('MessageHeader', header)); return stream; } exports._decryptStream = _decryptStream; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVjcnlwdF9zdHJlYW0uanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvZGVjcnlwdF9zdHJlYW0udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7Ozs7OztBQUV0QyxtRkFJNkM7QUFDN0MsK0RBQXlEO0FBQ3pELG1EQUE4QztBQUM5Qyx1REFBcUQ7QUFFckQsMERBQWlDO0FBR2pDLGFBQWE7QUFDYixxREFBdUQ7QUFFdkQsU0FBZ0IsY0FBYyxDQUM1QixpQkFBb0MsRUFDcEMsR0FBdUMsRUFDdkMsRUFBRSxXQUFXLEtBQTJCLEVBQUU7SUFFMUMsMkRBQTJEO0lBQzNELEdBQUc7UUFDRCxHQUFHLFlBQVksc0NBQVc7WUFDeEIsQ0FBQyxDQUFDLElBQUksbUVBQXdDLENBQUMsR0FBRyxDQUFDO1lBQ25ELENBQUMsQ0FBQyxHQUFHLENBQUE7SUFFVCxNQUFNLGlCQUFpQixHQUFHLElBQUksdUNBQWlCLENBQzdDLGlCQUFpQixDQUFDLGVBQWUsRUFDakMsaUJBQWlCLENBQUMsYUFBYSxFQUMvQixHQUFHLENBQ0osQ0FBQTtJQUNELE1BQU0sWUFBWSxHQUFHLElBQUksNEJBQVksQ0FBQyxFQUFFLFdBQVcsRUFBRSxDQUFDLENBQUE7SUFDdEQsTUFBTSxjQUFjLEdBQUcsSUFBQSxtQ0FBaUIsR0FBRSxDQUFBO0lBQzFDLE1BQU0sTUFBTSxHQUFHLElBQUksbUJBQVMsQ0FBQyxpQkFBaUIsRUFBRSxjQUFjLENBQUMsQ0FBQTtJQUUvRDs7O09BR0c7SUFDSCxJQUFBLDBCQUFRLEVBQ04saUJBQWlCLEVBQ2pCLFlBQVksRUFDWixjQUFjLEVBQ2QsSUFBSSw2QkFBVyxFQUFFLEVBQ2pCLENBQUMsR0FBVSxFQUFFLEVBQUU7UUFDYixJQUFJLEdBQUc7WUFBRSxNQUFNLENBQUMsSUFBSSxDQUFDLE9BQU8sRUFBRSxHQUFHLENBQUMsQ0FBQTtJQUNwQyxDQUFDLENBQ0YsQ0FBQTtJQUVELHdCQUF3QjtJQUN4QixpQkFBaUIsQ0FBQyxJQUFJLENBQUMsZUFBZSxFQUFFLENBQUMsTUFBTSxFQUFFLEVBQUUsQ0FDakQsTUFBTSxDQUFDLElBQUksQ0FBQyxlQUFlLEVBQUUsTUFBTSxDQUFDLENBQ3JDLENBQUE7SUFFRCxPQUFPLE1BQU0sQ0FBQTtBQUNmLENBQUM7QUF4Q0Qsd0NBd0NDIn0= /***/ }), /***/ 62355: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildDecrypt = void 0; var decrypt_client_1 = __nccwpck_require__(45075); Object.defineProperty(exports, "buildDecrypt", ({ enumerable: true, get: function () { return decrypt_client_1.buildDecrypt; } })); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7OztBQUV0QyxtREFBK0M7QUFBdEMsOEdBQUEsWUFBWSxPQUFBIn0= /***/ }), /***/ 90144: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ParseHeaderStream = void 0; // @ts-ignore const readable_stream_1 = __nccwpck_require__(51642); const material_management_node_1 = __nccwpck_require__(12563); const serialize_1 = __nccwpck_require__(26683); const toUtf8 = (input) => Buffer.from(input.buffer, input.byteOffset, input.byteLength).toString('utf8'); const deserialize = (0, serialize_1.deserializeFactory)(toUtf8, material_management_node_1.NodeAlgorithmSuite); const PortableTransformWithType = readable_stream_1.Transform; class ParseHeaderStream extends PortableTransformWithType { materialsManager; commitmentPolicy; signaturePolicy; maxEncryptedDataKeys; _headerState; constructor(signaturePolicy, { commitmentPolicy, maxEncryptedDataKeys }, cmm) { super(); /* Precondition: ParseHeaderStream needs a valid commitmentPolicy. */ (0, material_management_node_1.needs)(material_management_node_1.CommitmentPolicy[commitmentPolicy], 'Invalid commitment policy.'); /* Precondition: ParseHeaderStream needs a valid signaturePolicy. */ (0, material_management_node_1.needs)(material_management_node_1.SignaturePolicy[signaturePolicy], 'Invalid signature policy.'); // buildDecrypt defaults this to false for backwards compatibility, so this is satisfied /* Precondition: ParseHeaderStream needs a valid maxEncryptedDataKeys. */ (0, material_management_node_1.needs)(maxEncryptedDataKeys === false || maxEncryptedDataKeys >= 1, 'Invalid maxEncryptedDataKeys value.'); Object.defineProperty(this, 'materialsManager', { value: cmm, enumerable: true, }); Object.defineProperty(this, 'commitmentPolicy', { value: commitmentPolicy, enumerable: true, }); Object.defineProperty(this, 'maxEncryptedDataKeys', { value: maxEncryptedDataKeys, enumerable: true, }); this._headerState = { buffer: Buffer.alloc(0), headerParsed: false, }; Object.defineProperty(this, 'signaturePolicy', { value: signaturePolicy, enumerable: true, }); } _transform( // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types chunk, encoding, callback) { try { const { _headerState, commitmentPolicy, materialsManager, signaturePolicy, maxEncryptedDataKeys, } = this; const { buffer } = _headerState; const headerBuffer = Buffer.concat([buffer, chunk]); const headerInfo = deserialize.deserializeMessageHeader(headerBuffer, { maxEncryptedDataKeys, }); if (!headerInfo) { _headerState.buffer = headerBuffer; return callback(); } const { messageHeader, algorithmSuite } = headerInfo; const messageIDStr = Buffer.from(messageHeader.messageId).toString('hex'); /* Precondition: The parsed header algorithmSuite from ParseHeaderStream must be supported by the commitmentPolicy. */ material_management_node_1.CommitmentPolicySuites.isDecryptEnabled(commitmentPolicy, algorithmSuite, messageIDStr); /* Precondition: The parsed header algorithmSuite from ParseHeaderStream must be supported by the signaturePolicy. */ material_management_node_1.SignaturePolicySuites.isDecryptEnabled(signaturePolicy, algorithmSuite, messageIDStr); const { rawHeader, headerAuth } = headerInfo; const { headerIv, headerAuthTag, headerAuthLength } = headerAuth; const suite = new material_management_node_1.NodeAlgorithmSuite(algorithmSuite.id); const { messageId, encryptionContext, encryptedDataKeys } = messageHeader; materialsManager .decryptMaterials({ suite, encryptionContext, encryptedDataKeys }) .then((material) => { /* Precondition: The material algorithmSuite returned to ParseHeaderStream must be supported by the commitmentPolicy. */ material_management_node_1.CommitmentPolicySuites.isDecryptEnabled(commitmentPolicy, material.suite, messageIDStr); /* Precondition: The material algorithmSuite returned to ParseHeaderStream must be supported by the signaturePolicy. */ material_management_node_1.SignaturePolicySuites.isDecryptEnabled(signaturePolicy, material.suite, messageIDStr); _headerState.buffer = Buffer.alloc(0); // clear the Buffer... const { getDecipherInfo, getVerify, dispose } = (0, material_management_node_1.getDecryptionHelper)(material); const getDecipher = getDecipherInfo(messageId, /* This is sub-optimal. * Ideally I could pluck the `suiteData` * right off the header * and in such a way that may be undefined. * But that has other consequences * that are beyond the scope of this course. */ messageHeader.suiteData); const headerAuth = getDecipher(headerIv); headerAuth.setAAD(Buffer.from(rawHeader.buffer, rawHeader.byteOffset, rawHeader.byteLength)); headerAuth.setAuthTag(Buffer.from(headerAuthTag.buffer, headerAuthTag.byteOffset, headerAuthTag.byteLength)); headerAuth.update(Buffer.alloc(0)); headerAuth.final(); // will throw if invalid const verify = getVerify ? getVerify() : void 0; const verifyInfo = { headerInfo, getDecipher, verify, dispose, }; this.emit('VerifyInfo', verifyInfo); this.emit('MessageHeader', headerInfo.messageHeader); _headerState.headerParsed = true; // The header is parsed, pass control const readPos = rawHeader.byteLength + headerAuthLength; const tail = headerBuffer.slice(readPos); /* needs calls in downstream _transform streams will throw. * But streams are async. * So this error should be turned into an `.emit('error', ex)`. */ this._transform = (chunk, _enc, cb) => { try { cb(null, chunk); } catch (ex) { this.emit('error', ex); } }; // flush the tail. Stream control is now in the verify and decrypt streams return setImmediate(() => this._transform(tail, encoding, callback)); }) .catch((err) => callback(err)); } catch (ex) { /* Exceptional Postcondition: An error MUST be emitted or this would be an unhandled exception. */ this.emit('error', ex); } } _flush(callback) { /* Postcondition: A completed header MUST have been processed. * callback is an errBack function, * so it expects either an error OR undefined */ callback(this._headerState.headerParsed ? undefined : new Error('Incomplete Header')); } } exports.ParseHeaderStream = ParseHeaderStream; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicGFyc2VfaGVhZGVyX3N0cmVhbS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9wYXJzZV9oZWFkZXJfc3RyZWFtLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7QUFFdEMsYUFBYTtBQUNiLHFEQUFnRTtBQUVoRSxtRkFVNkM7QUFDN0MscURBQTJFO0FBRzNFLE1BQU0sTUFBTSxHQUFHLENBQUMsS0FBaUIsRUFBRSxFQUFFLENBQ25DLE1BQU0sQ0FBQyxJQUFJLENBQUMsS0FBSyxDQUFDLE1BQU0sRUFBRSxLQUFLLENBQUMsVUFBVSxFQUFFLEtBQUssQ0FBQyxVQUFVLENBQUMsQ0FBQyxRQUFRLENBQUMsTUFBT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tBQUssQ0FBQyxDQUFDLEdBQUcsRUFBRSxFQUFFLENBQUMsUUFBUSxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUE7U0FDakM7UUFBQyxPQUFPLEVBQUUsRUFBRTtZQUNYLGtHQUFrRztZQUNsRyxJQUFJLENBQUMsSUFBSSxDQUFDLE9BQU8sRUFBRSxFQUFFLENBQUMsQ0FBQTtTQUN2QjtJQUNILENBQUM7SUFFRCxNQUFNLENBQUMsUUFBK0I7UUFDcEM7OztXQUdHO1FBQ0gsUUFBUSxDQUNOLElBQUksQ0FBQyxZQUFZLENBQUMsWUFBWTtZQUM1QixDQUFDLENBQUMsU0FBUztZQUNYLENBQUMsQ0FBQyxJQUFJLEtBQUssQ0FBQyxtQkFBbUIsQ0FBQyxDQUNuQyxDQUFBO0lBQ0gsQ0FBQztDQUNGO0FBbk1ELDhDQW1NQyJ9 /***/ }), /***/ 77860: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.VerifyStream = void 0; // @ts-ignore const readable_stream_1 = __nccwpck_require__(51642); const material_management_node_1 = __nccwpck_require__(12563); const serialize_1 = __nccwpck_require__(26683); const parse_header_stream_1 = __nccwpck_require__(90144); const PortableTransformWithType = readable_stream_1.Transform; class VerifyStream extends PortableTransformWithType { _headerInfo; _verifyState = { buffer: Buffer.alloc(0), authTagBuffer: Buffer.alloc(0), signatureInfo: Buffer.alloc(0), sequenceNumber: 0, finalAuthTagReceived: false, }; _verify; _maxBodySize; constructor({ maxBodySize }) { super(); /* Precondition: VerifyStream requires maxBodySize must be falsey or a number. */ (0, material_management_node_1.needs)(!maxBodySize || typeof maxBodySize === 'number', 'Unsupported MaxBodySize.'); Object.defineProperty(this, '_maxBodySize', { value: maxBodySize, enumerable: true, }); this.on('pipe', (source) => { /* Precondition: The source must a ParseHeaderStream emit the required events. */ (0, material_management_node_1.needs)(source instanceof parse_header_stream_1.ParseHeaderStream, 'Unsupported source'); source.once('VerifyInfo', (verifyInfo) => { const { getDecipher, verify, headerInfo, dispose } = verifyInfo; const { messageId, contentType } = headerInfo.messageHeader; /* If I have a verify, the header needs to be flushed through. * I do it here for initialize the verifier before I even * add the element to the object. */ if (verify) { const { rawHeader, headerAuth, messageHeader } = headerInfo; const { headerIv, headerAuthTag } = headerAuth; verify.update(rawHeader); verify.update((0, serialize_1.serializeMessageHeaderAuth)({ headerIv, headerAuthTag, messageHeader, })); } Object.defineProperty(this, '_headerInfo', { value: headerInfo, enumerable: true, }); Object.defineProperty(this, '_verify', { value: verify, enumerable: true, }); const decipherInfo = { messageId: Buffer.from(messageId.buffer || messageId, messageId.byteOffset || 0, messageId.byteLength), contentType, getDecipher, dispose, }; this.emit('DecipherInfo', decipherInfo); }); }); } _transform(chunk, enc, callback) { /* Precondition: VerifyInfo must have initialized the stream. */ (0, material_management_node_1.needs)(this._headerInfo, 'VerifyStream not configured, VerifyInfo event not yet received.'); // BodyHeader const state = this._verifyState; const { currentFrame } = state; if (!currentFrame) { const { buffer } = state; const frameBuffer = Buffer.concat([buffer, chunk]); const frameHeader = (0, serialize_1.decodeBodyHeader)(frameBuffer, this._headerInfo, 0); if (!frameHeader) { // Need more data state.buffer = frameBuffer; return callback(); } /* Precondition: If maxBodySize was set I can not buffer more data than maxBodySize. * Before returning *any* cleartext, the stream **MUST** verify the decryption. * This means that I must buffer the message until the AuthTag is reached. */ (0, material_management_node_1.needs)(!this._maxBodySize || this._maxBodySize >= frameHeader.contentLength, 'maxBodySize exceeded.'); /* Keeping track of the sequence number myself. */ state.sequenceNumber += 1; /* Precondition: The sequence number is required to monotonically increase, starting from 1. * This is to avoid a bad actor from abusing the sequence number on un-signed algorithm suites. * If the frame size matched the data format (say NDJSON), * then the data could be significantly altered just by rearranging the frames. * Non-framed data returns a sequenceNumber of 1. */ (0, material_management_node_1.needs)(frameHeader.sequenceNumber === state.sequenceNumber, 'Encrypted body sequence out of order.'); if (this._verify) { this._verify.update(frameBuffer.slice(0, frameHeader.readPos)); } const tail = frameBuffer.slice(frameHeader.readPos); this.emit('BodyInfo', frameHeader); state.currentFrame = frameHeader; return setImmediate(() => this._transform(tail, enc, callback)); } // Content const { contentLength } = currentFrame; if (chunk.length && contentLength > 0) { if (contentLength > chunk.length) { currentFrame.contentLength -= chunk.length; this.push(chunk); return callback(); } else { const content = chunk.slice(0, contentLength); const tail = chunk.slice(content.length); this.push(content); currentFrame.contentLength = 0; return setImmediate(() => this._transform(tail, enc, callback)); } } // AuthTag const { tagLength } = currentFrame; const tagLengthBytes = tagLength / 8; const { authTagBuffer } = state; if (chunk.length && tagLengthBytes > authTagBuffer.length) { const left = tagLengthBytes - authTagBuffer.length; if (left > chunk.length) { state.authTagBuffer = Buffer.concat([authTagBuffer, chunk]); return callback(); } else { const finalAuthTagBuffer = Buffer.concat([authTagBuffer, chunk], tagLengthBytes); if (this._verify) { this._verify.update(finalAuthTagBuffer); } /* Reset state. * Ciphertext buffers and authTag buffers need to be cleared. */ state.buffer = Buffer.alloc(0); state.currentFrame = undefined; state.authTagBuffer = Buffer.alloc(0); /* After the final frame the file format is _much_ simpler. * Making sure the cascading if blocks fall to the signature can be tricky and brittle. * After the final frame, just moving on to concatenate the signature is much simpler. */ if (currentFrame.isFinalFrame) { /* Signal that the we are at the end of the ciphertext. * See decodeBodyHeader, non-framed will set isFinalFrame * for the single frame. */ this._verifyState.finalAuthTagReceived = true; /* Overwriting the _transform function. * Data flow control is now handled here. */ this._transform = (chunk, _enc, callback) => { if (chunk.length) { state.signatureInfo = Buffer.concat([state.signatureInfo, chunk]); } callback(); }; } const tail = chunk.slice(left); /* The decipher_stream uses the `AuthTag` event to flush the accumulated frame. * This is because ciphertext should never be returned until it is verified. * i.e. the auth tag checked. * This can create an issue if the chucks and frame size are small. * If the verify stream continues processing and sends the next auth tag, * before the current auth tag has been completed. * This is basically a back pressure issue. * Since the frame size, and consequently the high water mark, * can not be know when the stream is created, * the internal stream state would need to be modified. * I assert that a simple callback is a simpler way to handle this. */ const next = () => this._transform(tail, enc, callback); return this.emit('AuthTag', finalAuthTagBuffer, next); } } callback(); } push(chunk, encoding) { // Typescript???? this._verify instanceof Verify is better.... if (this._verify && chunk) { this._verify.update(chunk); } return super.push(chunk, encoding); } _flush(callback) { const { finalAuthTagReceived } = this._verifyState; /* Precondition: All ciphertext MUST have been received. * The verify stream has ended, * there will be no more data. * Therefore we MUST have reached the end. */ if (!finalAuthTagReceived) return callback(new Error('Incomplete message')); /* Check for early return (Postcondition): If there is no verify stream do not attempt to verify. */ if (!this._verify) return callback(); try { const { signatureInfo } = this._verifyState; /* Precondition: The signature must be well formed. */ const { buffer, byteOffset, byteLength } = (0, serialize_1.deserializeSignature)(signatureInfo); const signature = Buffer.from(buffer, byteOffset, byteLength); const isVerified = this._verify.awsCryptoVerify(signature); /* Postcondition: The signature must be valid. */ (0, material_management_node_1.needs)(isVerified, 'Invalid Signature'); callback(); } catch (e) { callback(e); } } } exports.VerifyStream = VerifyStream; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmVyaWZ5X3N0cmVhbS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy92ZXJpZnlfc3RyZWFtLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7QUFFdEMsYUFBYTtBQUNiLHFEQUFnRTtBQUVoRSxtRkFJNkM7QUFDN0MscURBTThCO0FBQzlCLCtEQUF5RDtBQUl6RCxNQUFNLHlCQUF5QixHQUFHLDJCQUVwQixDQUFBO0FBc0JkLE1BQWEsWUFBYSxTQUFRLHlCQUF5QjtJQUNqRCxXQUFXLENBQWE7SUFDeEIsWUFBWSxHQUFnQjtRQUNsQyxNQUFNLEVBQUUsTUFBTSxDQUFDLEtBQUssQ0FBQy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SSxDQUFDLE9BQU8sQ0FBQyxlQUFlLENBQUMsU0FBUyxDQUFDLENBQUE7WUFDMUQsaURBQWlEO1lBQ2pELElBQUEsZ0NBQUssRUFBQyxVQUFVLEVBQUUsbUJBQW1CLENBQUMsQ0FBQTtZQUN0QyxRQUFRLEVBQUUsQ0FBQTtTQUNYO1FBQUMsT0FBTyxDQUFDLEVBQUU7WUFDVixRQUFRLENBQUMsQ0FBQyxDQUFDLENBQUE7U0FDWjtJQUNILENBQUM7Q0FDRjtBQW5QRCxvQ0FtUEMifQ== /***/ }), /***/ 53340: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports._encrypt = void 0; const encrypt_stream_1 = __nccwpck_require__(79383); // @ts-ignore const readable_stream_1 = __nccwpck_require__(51642); async function _encrypt(clientOptions, cmm, plaintext, op = {}) { const { encoding } = op; if (plaintext instanceof Uint8Array) { op.plaintextLength = plaintext.byteLength; } else if (typeof plaintext === 'string') { plaintext = Buffer.from(plaintext, encoding); op.plaintextLength = plaintext.byteLength; } const stream = (0, encrypt_stream_1._encryptStream)(clientOptions, cmm, op); const result = []; let messageHeader = false; stream .once('MessageHeader', (header) => { messageHeader = header; }) .on('data', (chunk) => result.push(chunk)); // This will check both Uint8Array|Buffer if (plaintext instanceof Uint8Array) { stream.end(plaintext); } else if (plaintext.readable) { plaintext.pipe(stream); } else { throw new Error('Unsupported plaintext'); } await finishedAsync(stream); if (!messageHeader) throw new Error('Unknown format'); return { result: Buffer.concat(result), messageHeader, }; } exports._encrypt = _encrypt; async function finishedAsync(stream) { return new Promise((resolve, reject) => { (0, readable_stream_1.finished)(stream, (err) => (err ? reject(err) : resolve())); }); } //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW5jcnlwdC5qcyIsInNvdXJjZVJvb3QiOiIiLC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UFDLENBQUMsQ0FBQTtJQUVwRCx5Q0FBeUM7SUFDekMsSUFBSSxTQUFTLFlBQVksVUFBVSxFQUFFO1FBQ25DLE1BQU0sQ0FBQyxHQUFHLENBQUMsU0FBUyxDQUFDLENBQUE7S0FDdEI7U0FBTSxJQUFJLFNBQVMsQ0FBQyxRQUFRLEVBQUU7UUFDN0IsU0FBUyxDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsQ0FBQTtLQUN2QjtTQUFNO1FBQ0wsTUFBTSxJQUFJLEtBQUssQ0FBQyx1QkFBdUIsQ0FBQyxDQUFBO0tBQ3pDO0lBRUQsTUFBTSxhQUFhLENBQUMsTUFBTSxDQUFDLENBQUE7SUFDM0IsSUFBSSxDQUFDLGFBQWE7UUFBRSxNQUFNLElBQUksS0FBSyxDQUFDLGdCQUFnQixDQUFDLENBQUE7SUFFckQsT0FBTztRQUNMLE1BQU0sRUFBRSxNQUFNLENBQUMsTUFBTSxDQUFDLE1BQU0sQ0FBQztRQUM3QixhQUFhO0tBQ2QsQ0FBQTtBQUNILENBQUM7QUF2Q0QsNEJBdUNDO0FBRUQsS0FBSyxVQUFVLGFBQWEsQ0FBQyxNQUFjO0lBQ3pDLE9BQU8sSUFBSSxPQUFPLENBQU8sQ0FBQyxPQUFPLEVBQUUsTUFBTSxFQUFFLEVBQUU7UUFDM0MsSUFBQSwwQkFBUSxFQUFDLE1BQU0sRUFBRSxDQUFDLEdBQVUsRUFBRSxFQUFFLENBQUMsQ0FBQyxHQUFHLENBQUMsQ0FBQyxDQUFDLE1BQU0sQ0FBQyxHQUFHLENBQUMsQ0FBQyxDQUFDLENBQUMsT0FBTyxFQUFFLENBQUMsQ0FBQyxDQUFBO0lBQ25FLENBQUMsQ0FBQyxDQUFBO0FBQ0osQ0FBQyJ9 /***/ }), /***/ 35094: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildEncrypt = void 0; const encrypt_stream_1 = __nccwpck_require__(79383); const encrypt_1 = __nccwpck_require__(53340); const material_management_node_1 = __nccwpck_require__(12563); function buildEncrypt(options = {}) { const { commitmentPolicy = material_management_node_1.CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT, maxEncryptedDataKeys = false, } = typeof options === 'string' ? { commitmentPolicy: options } : options; /* Precondition: node buildEncrypt needs a valid commitmentPolicy. */ (0, material_management_node_1.needs)(material_management_node_1.CommitmentPolicy[commitmentPolicy], 'Invalid commitment policy.'); /* Precondition: node buildEncrypt needs a valid maxEncryptedDataKeys. */ (0, material_management_node_1.needs)(maxEncryptedDataKeys === false || maxEncryptedDataKeys >= 1, 'Invalid maxEncryptedDataKeys value.'); const clientOptions = { commitmentPolicy, maxEncryptedDataKeys, }; return { encryptStream: encrypt_stream_1._encryptStream.bind({}, clientOptions), encrypt: encrypt_1._encrypt.bind({}, clientOptions), }; } exports.buildEncrypt = buildEncrypt; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW5jcnlwdF9jbGllbnQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvZW5jcnlwdF9jbGllbnQudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7OztBQUV0QyxxREFBaUQ7QUFDakQsdUNBQW9DO0FBQ3BDLG1GQUk2QztBQVM3QyxTQUFnQixZQUFZLENBQzFCLFVBQXFELEVBQUU7SUFPdkQsTUFBTSxFQUNKLGdCQUFnQixHQUFHLDJDQUFnQixDQUFDLCtCQUErQixFQUNuRSxvQkFBb0IsR0FBRyxLQUFLLEdBQzdCLEdBQUcsT0FBTyxPQUFPLEtBQUssUUFBUSxDQUFDLENBQUMsQ0FBQyxFQUFFLGdCQUFnQixFQUFFLE9BQU8sRUFBRSxDQUFDLENBQUMsQ0FBQyxPQUFPLENBQUE7SUFFekUscUVBQXFFO0lBQ3JFLElBQUEsZ0NBQUssRUFBQywyQ0FBZ0IsQ0FBQyxnQkFBZ0IsQ0FBQyxFQUFFLDRCQUE0QixDQUFDLENBQUE7SUFDdkUseUVBQXlFO0lBQ3pFLElBQUEsZ0NBQUssRUFDSCxvQkFBb0IsS0FBSyxLQUFLLElBQUksb0JBQW9CLElBQUksQ0FBQyxFQUMzRCxxQ0FBcUMsQ0FDdEMsQ0FBQTtJQUVELE1BQU0sYUFBYSxHQUFrQjtRQUNuQyxnQkFBZ0I7UUFDaEIsb0JBQW9CO0tBQ3JCLENBQUE7SUFDRCxPQUFPO1FBQ0wsYUFBYSxFQUFFLCtCQUFjLENBQUMsSUFBSSxDQUFDLEVBQUUsRUFBRSxhQUFhLENBQUM7UUFDckQsT0FBTyxFQUFFLGtCQUFRLENBQUMsSUFBSSxDQUFDLEVBQUUsRUFBRSxhQUFhLENBQUM7S0FDMUMsQ0FBQTtBQUNILENBQUM7QUE3QkQsb0NBNkJDIn0= /***/ }), /***/ 79383: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getEncryptionInfo = exports._encryptStream = void 0; const material_management_node_1 = __nccwpck_require__(12563); const framed_encrypt_stream_1 = __nccwpck_require__(87185); const signature_stream_1 = __nccwpck_require__(28526); const duplexify_1 = __importDefault(__nccwpck_require__(76599)); const crypto_1 = __nccwpck_require__(6113); const serialize_1 = __nccwpck_require__(26683); // @ts-ignore const readable_stream_1 = __nccwpck_require__(51642); const fromUtf8 = (input) => Buffer.from(input, 'utf8'); const { serializeMessageHeader, headerAuthIv, buildMessageHeader } = (0, serialize_1.serializeFactory)(fromUtf8); /** * Takes a NodeDefaultCryptographicMaterialsManager or a KeyringNode that will * be wrapped in a NodeDefaultCryptographicMaterialsManager and returns a stream. * * @param commitmentPolicy * @param maxEncryptedDataKeys * @param cmm NodeMaterialsManager|KeyringNode * @param op EncryptStreamInput */ function _encryptStream({ commitmentPolicy, maxEncryptedDataKeys }, cmm, op = {}) { /* Precondition: encryptStream needs a valid commitmentPolicy. */ (0, material_management_node_1.needs)(material_management_node_1.CommitmentPolicy[commitmentPolicy], 'Invalid commitment policy.'); // buildEncrypt defaults this to false for backwards compatibility, so this is satisfied /* Precondition: encryptStream needs a valid maxEncryptedDataKeys. */ (0, material_management_node_1.needs)(maxEncryptedDataKeys === false || maxEncryptedDataKeys >= 1, 'Invalid maxEncryptedDataKeys value.'); const { suiteId, encryptionContext = {}, frameLength = serialize_1.FRAME_LENGTH, plaintextLength, } = op; /* Precondition: The frameLength must be less than the maximum frame size Node.js stream. */ (0, material_management_node_1.needs)(frameLength > 0 && serialize_1.Maximum.FRAME_SIZE >= frameLength, `frameLength out of bounds: 0 > frameLength >= ${serialize_1.Maximum.FRAME_SIZE}`); /* If the cmm is a Keyring, wrap it with NodeDefaultCryptographicMaterialsManager. */ cmm = cmm instanceof material_management_node_1.KeyringNode ? new material_management_node_1.NodeDefaultCryptographicMaterialsManager(cmm) : cmm; const suite = suiteId && new material_management_node_1.NodeAlgorithmSuite(suiteId); /* Precondition: Only request NodeEncryptionMaterial for algorithm suites supported in commitmentPolicy. */ material_management_node_1.CommitmentPolicySuites.isEncryptEnabled(commitmentPolicy, suite); const wrappingStream = new duplexify_1.default(); cmm .getEncryptionMaterials({ suite, encryptionContext, plaintextLength, commitmentPolicy, }) .then(async (material) => { /* Precondition: Only use NodeEncryptionMaterial for algorithm suites supported in commitmentPolicy. */ material_management_node_1.CommitmentPolicySuites.isEncryptEnabled(commitmentPolicy, material.suite); /* Precondition: _encryptStream encryption materials must not exceed maxEncryptedDataKeys */ (0, material_management_node_1.needs)(maxEncryptedDataKeys === false || material.encryptedDataKeys.length <= maxEncryptedDataKeys, 'maxEncryptedDataKeys exceeded.'); const { getCipher, messageHeader, rawHeader, dispose, getSigner } = getEncryptionInfo(material, frameLength); wrappingStream.emit('MessageHeader', messageHeader); const encryptStream = (0, framed_encrypt_stream_1.getFramedEncryptStream)(getCipher, messageHeader, dispose, { plaintextLength, suite: material.suite }); const signatureStream = new signature_stream_1.SignatureStream(getSigner); (0, readable_stream_1.pipeline)(encryptStream, signatureStream); wrappingStream.setReadable(signatureStream); // Flush the rawHeader through the signatureStream rawHeader.forEach((buff) => signatureStream.write(buff)); // @ts-ignore until readable-stream exports v3 types... wrappingStream.setWritable(encryptStream); }) .catch((err) => wrappingStream.emit('error', err)); return wrappingStream; } exports._encryptStream = _encryptStream; function getEncryptionInfo(material, frameLength) { const { getCipherInfo, dispose, getSigner } = (0, material_management_node_1.getEncryptHelper)(material); const { suite, encryptionContext, encryptedDataKeys } = material; const { ivLength, messageFormat } = material.suite; const versionString = material_management_node_1.MessageFormat[messageFormat]; const messageIdLength = parseInt(serialize_1.MessageIdLength[versionString], 10); /* Precondition UNTESTED: Node suites must result is some messageIdLength. */ (0, material_management_node_1.needs)(messageIdLength > 0, 'Algorithm suite has unknown message format.'); const messageId = (0, crypto_1.randomBytes)(messageIdLength); const { getCipher, keyCommitment } = getCipherInfo(messageId); const messageHeader = buildMessageHeader({ suite: suite, encryptedDataKeys, encryptionContext, messageId, frameLength, suiteData: keyCommitment, }); const { buffer, byteOffset, byteLength } = serializeMessageHeader(messageHeader); const headerBuffer = Buffer.from(buffer, byteOffset, byteLength); const headerIv = headerAuthIv(ivLength); const validateHeader = getCipher(headerIv); validateHeader.setAAD(headerBuffer); validateHeader.update(Buffer.alloc(0)); validateHeader.final(); const headerAuthTag = validateHeader.getAuthTag(); return { getCipher, dispose, getSigner, messageHeader, rawHeader: [ headerBuffer, (0, serialize_1.serializeMessageHeaderAuth)({ headerIv, headerAuthTag, messageHeader }), ], }; } exports.getEncryptionInfo = getEncryptionIn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xZQUFZLEdBQUcsTUFBTSxDQUFDLElBQUksQ0FBQyxNQUFNLEVBQUUsVUFBVSxFQUFFLFVBQVUsQ0FBQyxDQUFBO0lBQ2hFLE1BQU0sUUFBUSxHQUFHLFlBQVksQ0FBQyxRQUFRLENBQUMsQ0FBQTtJQUN2QyxNQUFNLGNBQWMsR0FBRyxTQUFTLENBQUMsUUFBUSxDQUFDLENBQUE7SUFDMUMsY0FBYyxDQUFDLE1BQU0sQ0FBQyxZQUFZLENBQUMsQ0FBQTtJQUNuQyxjQUFjLENBQUMsTUFBTSxDQUFDLE1BQU0sQ0FBQyxLQUFLLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQTtJQUN0QyxjQUFjLENBQUMsS0FBSyxFQUFFLENBQUE7SUFDdEIsTUFBTSxhQUFhLEdBQUcsY0FBYyxDQUFDLFVBQVUsRUFBRSxDQUFBO0lBRWpELE9BQU87UUFDTCxTQUFTO1FBQ1QsT0FBTztRQUNQLFNBQVM7UUFDVCxhQUFhO1FBQ2IsU0FBUyxFQUFFO1lBQ1QsWUFBWTtZQUNaLElBQUEsc0NBQTBCLEVBQUMsRUFBRSxRQUFRLEVBQUUsYUFBYSxFQUFFLGFBQWEsRUFBRSxDQUFDO1NBQ3ZFO0tBQ0YsQ0FBQTtBQUNILENBQUM7QUE3Q0QsOENBNkNDIn0= /***/ }), /***/ 87185: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getEncryptFrame = exports.getFramedEncryptStream = void 0; const serialize_1 = __nccwpck_require__(26683); // @ts-ignore const readable_stream_1 = __nccwpck_require__(51642); const material_management_node_1 = __nccwpck_require__(12563); const fromUtf8 = (input) => Buffer.from(input, 'utf8'); const serialize = (0, serialize_1.serializeFactory)(fromUtf8); const { finalFrameHeader, frameHeader } = serialize; const aadUtility = (0, serialize_1.aadFactory)(fromUtf8); const PortableTransformWithType = readable_stream_1.Transform; const ioTick = async () => new Promise((resolve) => setImmediate(resolve)); const noop = () => { }; // eslint-disable-line @typescript-eslint/no-empty-function function getFramedEncryptStream(getCipher, messageHeader, dispose, { plaintextLength, suite, }) { let accumulatingFrame = { contentLength: 0, content: [], sequenceNumber: 1, }; let pathologicalDrain = noop; const { frameLength } = messageHeader; /* Precondition: plaintextLength must be within bounds. * The Maximum.BYTES_PER_MESSAGE is set to be within Number.MAX_SAFE_INTEGER * See serialize/identifiers.ts enum Maximum for more details. */ (0, material_management_node_1.needs)(!plaintextLength || (plaintextLength >= 0 && serialize_1.Maximum.BYTES_PER_MESSAGE >= plaintextLength), 'plaintextLength out of bounds.'); /* Keeping the messageHeader, accumulatingFrame and pathologicalDrain private is the intention here. * It is already unlikely that these values could be touched in the current composition of streams, * but a different composition may change this. * Since we are handling the plain text here, it seems prudent to take extra measures. */ return new (class FramedEncryptStream extends PortableTransformWithType { _transform(chunk, encoding, callback) { const contentLeft = frameLength - accumulatingFrame.contentLength; /* Precondition: Must not process more than plaintextLength. * The plaintextLength is the MAXIMUM value that can be encrypted. */ (0, material_management_node_1.needs)(!plaintextLength || (plaintextLength -= chunk.length) >= 0, 'Encrypted data exceeded plaintextLength.'); /* Check for early return (Postcondition): Have not accumulated a frame. */ if (contentLeft > chunk.length) { // eat more accumulatingFrame.contentLength += chunk.length; accumulatingFrame.content.push(chunk); return callback(); } accumulatingFrame.contentLength += contentLeft; accumulatingFrame.content.push(chunk.slice(0, contentLeft)); // grab the tail const tail = chunk.slice(contentLeft); const encryptFrame = getEncryptFrame({ pendingFrame: accumulatingFrame, messageHeader, getCipher, isFinalFrame: false, suite, }); // Reset frame state for next frame const { sequenceNumber } = accumulatingFrame; accumulatingFrame = { contentLength: 0, content: [], sequenceNumber: sequenceNumber + 1, }; this._flushEncryptFrame(encryptFrame) .then(() => this._transform(tail, encoding, callback)) .catch(callback); } _flush(callback) { const encryptFrame = getEncryptFrame({ pendingFrame: accumulatingFrame, messageHeader, getCipher, isFinalFrame: true, suite, }); this._flushEncryptFrame(encryptFrame) .then(() => callback()) .catch(callback); } _destroy() { dispose(); } _read(size) { super._read(size); /* The _flushEncryptFrame encrypts and pushes the frame. * If this.push returns false then this stream * should wait until the destination stream calls read. * This means that _flushEncryptFrame needs to wait for some * indeterminate time. I create a closure around * the resolution function for a promise that * is created in _flushEncryptFrame. This way * here in _read (the implementation of read) * if a frame is being pushed, we can release * it. */ pathologicalDrain(); pathologicalDrain = noop; } async _flushEncryptFrame(encryptingFrame) { const { content, cipher, bodyHeader, isFinalFrame } = encryptingFrame; this.push(bodyHeader); let frameSize = 0; const cipherContent = []; for (const clearChunk of content) { const cipherText = cipher.update(clearChunk); frameSize += cipherText.length; cipherContent.push(cipherText); await ioTick(); } /* Finalize the cipher and handle any tail. */ const tail = cipher.final(); frameSize += tail.length; cipherContent.push(tail); /* Push the authTag onto the end. Yes, I am abusing the name. */ cipherContent.push(cipher.getAuthTag()); (0, material_management_node_1.needs)(frameSize === frameLength || (isFinalFrame && frameLength >= frameSize), 'Malformed frame'); for (const cipherText of cipherContent) { if (!this.push(cipherText)) { /* back pressure: if push returns false, wait until _read * has been called. */ await new Promise((resolve) => { pathologicalDrain = resolve; }); } } if (isFinalFrame) this.push(null); } })(); } exports.getFramedEncryptStream = getFramedEncryptStream; function getEncryptFrame(input) { const { pendingFrame, messageHeader, getCipher, isFinalFrame, suite } = input; const { sequenceNumber, contentLength, content } = pendingFrame; const { frameLength, contentType, messageId } = messageHeader; /* Precondition: The content length MUST correlate with the frameLength. * In the case of a regular frame, * the content length MUST strictly equal the frame length. * In the case of the final frame, * it MUST NOT be larger than the frame length. */ (0, material_management_node_1.needs)(frameLength === contentLength || (isFinalFrame && frameLength >= contentLength), `Malformed frame length and content length: ${JSON.stringify({ frameLength, contentLength, isFinalFrame, })}`); const frameIv = serialize.frameIv(suite.ivLength, sequenceNumber); const bodyHeader = Buffer.from(isFinalFrame ? finalFrameHeader(sequenceNumber, frameIv, contentLength) : frameHeader(sequenceNumber, frameIv)); const contentString = aadUtility.messageAADContentString({ contentType, isFinalFrame, }); const { buffer, byteOffset, byteLength } = aadUtility.messageAAD(messageId, contentString, sequenceNumber, contentLength); const cipher = getCipher(frameIv); cipher.setAAD(Buffer.from(buffer, byteOffset, byteLength)); return { content, cipher, bodyHeader, isFinalFrame }; } exports.getEncryptFrame = getEncryptFrame; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZnJhbWVkX2VuY3J5cHRfc3RyZWFtLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL2ZyYW1lZF9lbmNyeXB0X3N0cmVhbS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUEsb0VBQW9FO0FBQ3BFLHNDQUFzQzs7O0FBRXRDLHFEQUs4QjtBQUM5QixhQUFhO0FBQ2IscURBQWdFO0FBRWhFLG1GQUs2QztBQUU3QyxNQUFNLFFBQVEsR0FBRyxDQUFDLEtBQWEsRUFBRSxFQUFFLENBQUMsTUFBTSxDQUFDLElBQUksQ0FBQyxLQUFLLEVBQUUsTUFBTSxDQUFDLENBQUE7QUFDOUQsTUFBTSxTQUFTLEdBQUcsSUFBQSw0QkFBZ0IsRUFBQyxRQUFRLENBQUMsQ0FBQTtBQUM1QyxNQUFNLEVBQUUsZ0JBQWdCLEVBQUUsV0FBVyxFQUFFLEdBQUcsU0FBUyxDQUFBO0FBQ25ELE1BQU0sVUFBVSxHQUFHLElBQUEsc0JBQVUsRUFBQyxRQUFRLENBQUMsQ0FBQTtBQWV2QyxNQUFNLHlCQUF5QixHQUFHLDJCQUVwQixDQUFBO0FBRWQsTUFBTSxNQUFNLEdBQUcsS0FBSyxJQUFJLEVBQUUsQ0FBQyxJQUFJLE9BQU8sQ0FBQyxDQUFDLE9BQU8sRUFBRSxFQUFFLENBQUMsWUFBWSxDQUFDLE9BQU8sQ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0QsTUFBTSxNQUFNLEdBQUcsU0FBUyxDQUFDLE9BQU8sQ0FBQyxDQUFBO0lBQ2pDLE1BQU0sQ0FBQyxNQUFNLENBQUMsTUFBTSxDQUFDLElBQUksQ0FBQyxNQUFNLEVBQUUsVUFBVSxFQUFFLFVBQVUsQ0FBQyxDQUFDLENBQUE7SUFFMUQsT0FBTyxFQUFFLE9BQU8sRUFBRSxNQUFNLEVBQUUsVUFBVSxFQUFFLFlBQVksRUFBRSxDQUFBO0FBQ3RELENBQUM7QUF2Q0QsMENBdUNDIn0= /***/ }), /***/ 3096: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildEncrypt = void 0; var encrypt_client_1 = __nccwpck_require__(35094); Object.defineProperty(exports, "buildEncrypt", ({ enumerable: true, get: function () { return encrypt_client_1.buildEncrypt; } })); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7OztBQUV0QyxtREFBK0M7QUFBdEMsOEdBQUEsWUFBWSxPQUFBIn0= /***/ }), /***/ 28526: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SignatureStream = void 0; const stream_1 = __nccwpck_require__(12781); const serialize_1 = __nccwpck_require__(26683); class SignatureStream extends stream_1.Transform { _signer; constructor(getSigner) { super(); const value = getSigner && getSigner(); Object.defineProperty(this, '_signer', { value, enumerable: true }); } _transform(chunk, _encoding, callback) { // If we have a signer, push the data to it this._signer && this._signer.update(chunk); // forward the data on callback(null, chunk); } _flush(callback) { if (this._signer) { const signature = this._signer.awsCryptoSign(); this.push((0, serialize_1.serializeSignatureInfo)(signature)); } callback(); } } exports.SignatureStream = SignatureStream; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2lnbmF0dXJlX3N0cmVhbS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9zaWduYXR1cmVfc3RyZWFtLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7QUFFdEMsbUNBQWtDO0FBRWxDLHFEQUE4RDtBQUk5RCxNQUFhLGVBQWdCLFNBQVEsa0JBQVM7SUFDcEMsT0FBTyxDQUF3QjtJQUN2QyxZQUFZLFNBQXFCO1FBQy9CLEtBQUssRUFBRSxDQUFBO1FBQ1AsTUFBTSxLQUFLLEdBQUcsU0FBUyxJQUFJLFNBQVMsRUFBRSxDQUFBO1FBQ3RDLE1BQU0sQ0FBQyxjQUFjLENBQUMsSUFBSSxFQUFFLFNBQVMsRUFBRSxFQUFFLEtBQUssRUFBRSxVQUFVLEVBQUUsSUFBSSxFQUFFLENBQUMsQ0FBQTtJQUNyRSxDQUFDO0lBRUQsVUFBVSxDQUNSLEtBQVUsRUFDVixTQUFpQixFQUNqQixRQUF5RDtRQUV6RCwyQ0FBMkM7UUFDM0MsSUFBSSxDQUFDLE9BQU8sSUFBSSxJQUFJLENBQUMsT0FBTyxDQUFDLE1BQU0sQ0FBQyxLQUFLLENBQUMsQ0FBQTtRQUMxQyxzQkFBc0I7UUFDdEIsUUFBUSxDQUFDLElBQUksRUFBRSxLQUFLLENBQUMsQ0FBQTtJQUN2QixDQUFDO0lBRUQsTUFBTSxDQUFDLFFBQStCO1FBQ3BDLElBQUksSUFBSSxDQUFDLE9BQU8sRUFBRTtZQUNoQixNQUFNLFNBQVMsR0FBRyxJQUFJLENBQUMsT0FBTyxDQUFDLGFBQWEsRUFBRSxDQUFBO1lBQzlDLElBQUksQ0FBQyxJQUFJLENBQUMsSUFBQSxrQ0FBc0IsRUFBQyxTQUFTLENBQUMsQ0FBQyxDQUFBO1NBQzdDO1FBQ0QsUUFBUSxFQUFFLENBQUE7SUFDWixDQUFDO0NBQ0Y7QUExQkQsMENBMEJDIn0= /***/ }), /***/ 70535: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UnsupportedAlgorithm = exports.KeyLengthError = exports.HKDFError = void 0; class HKDFError extends Error { constructor(message) { super(message); Object.setPrototypeOf(this, HKDFError.prototype); } } exports.HKDFError = HKDFError; class KeyLengthError extends HKDFError { name = 'KeyLengthError'; constructor(maxLength, algorithm) { super('Can not derive keys larger than ' + maxLength + ' for algorithm:' + algorithm); Object.setPrototypeOf(this, KeyLengthError.prototype); } } exports.KeyLengthError = KeyLengthError; class UnsupportedAlgorithm extends HKDFError { name = 'UnsupportedAlgorithm'; constructor(algorithm) { super('Hash algorithm: ' + algorithm + ' is not an implemented algorithm'); Object.setPrototypeOf(this, UnsupportedAlgorithm.prototype); } } exports.UnsupportedAlgorithm = UnsupportedAlgorithm; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXJyb3JzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL2Vycm9ycy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUEsb0VBQW9FO0FBQ3BFLHNDQUFzQzs7O0FBRXRDLE1BQWEsU0FBVSxTQUFRLEtBQUs7SUFDbEMsWUFBWSxPQUFnQjtRQUMxQixLQUFLLENBQUMsT0FBTyxDQUFDLENBQUE7UUFDZCxNQUFNLENBQUMsY0FBYyxDQUFDLElBQUksRUFBRSxTQUFTLENBQUMsU0FBUyxDQUFDLENBQUE7SUFDbEQsQ0FBQztDQUNGO0FBTEQsOEJBS0M7QUFFRCxNQUFhLGNBQWUsU0FBUSxTQUFTO0lBQ3BDLElBQUksR0FBRyxnQkFBZ0IsQ0FBQTtJQUM5QixZQUFZLFNBQWlCLEVBQUUsU0FBaUI7UUFDOUMsS0FBSyxDQUNILGtDQUFrQztZQUNoQyxTQUFTO1lBQ1QsaUJBQWlCO1lBQ2pCLFNBQVMsQ0FDWixDQUFBO1FBQ0QsTUFBTSxDQUFDLGNBQWMsQ0FBQyxJQUFJLEVBQUUsY0FBYyxDQUFDLFNBQVMsQ0FBQyxDQUFBO0lBQ3ZELENBQUM7Q0FDRjtBQVhELHdDQVdDO0FBRUQsTUFBYSxvQkFBcUIsU0FBUSxTQUFTO0lBQzFDLElBQUksR0FBRyxzQkFBc0IsQ0FBQTtJQUNwQyxZQUFZLFNBQWlCO1FBQzNCLEtBQUssQ0FBQyxrQkFBa0IsR0FBRyxTQUFTLEdBQUcsa0NBQWtDLENBQUMsQ0FBQTtRQUMxRSxNQUFNLENBQUMsY0FBYyxDQUFDLElBQUksRUFBRSxvQkFBb0IsQ0FBQyxTQUFTLENBQUMsQ0FBQTtJQUM3RCxDQUFDO0NBQ0Y7QUFORCxvREFNQyJ9 /***/ }), /***/ 31430: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.HKDF = void 0; const crypto_1 = __nccwpck_require__(6113); const errors_1 = __nccwpck_require__(70535); /** * Factory function to curry the hash algorithm * * @param algorithm [String] The name of the hash algorithm to use * @return [Function] The extract function decorated with expand and verify functions */ function HKDF(algorithm = 'sha256') { // Check the length and support const hashLength = (function () { try { return (0, crypto_1.createHash)(algorithm).digest().length; } catch (ex) { throw new errors_1.UnsupportedAlgorithm(algorithm); } })(); // (<= 255*HashLen) from https://tools.ietf.org/html/rfc5869 const maxLength = 255 * hashLength; // decorate the return function extractExpand.extract = extract; extractExpand.expand = expand; return extractExpand; // implementation /** * Extracts a prk and returns a function to expand the given initial key * * @param ikm [String|Buffer] The initial key * @param salt [String|Buffer] Optional salt for the extraction * @return [Function] expand function with the extracted key curried onto it */ function extractExpand(ikm, salt) { const prk = extract(ikm, salt); return (length, info) => expand(prk, length, info); } /** * Extracts a prk and returns a function to expand the given initial key * * @param ikm [String|Buffer] The initial key * @param salt [String|Buffer] Optional salt for the extraction * @return [Buffer] the expanded key */ function extract(ikm, salt) { const _salt = salt || Buffer.alloc(hashLength, 0).toString(); return (0, crypto_1.createHmac)(algorithm, _salt).update(ikm).digest(); } /** * Expands a given key * * @param prk [Buffer] The key to expand from * @param length [Number] The length of the expanded key * @param info [Buffer] Data to bind the expanded key to application/context specific information * @return [Buffer] the expanded */ function expand(prk, length, info) { if (length > maxLength) { throw new errors_1.KeyLengthError(maxLength, algorithm); } info = info || Buffer.alloc(0); const N = Math.ceil(length / hashLength); const memo = []; /* L/length octets are returned from T(1)...T(N), and T(0) is definitionally empty/zero length. * Elide T(0) into the Buffer.alloc(0) case and then return L octets of T indexed 0...L-1. */ for (let i = 0; i < N; i++) { memo[i] = (0, crypto_1.createHmac)(algorithm, prk) .update(memo[i - 1] || Buffer.alloc(0)) .update(info) .update(Buffer.alloc(1, i + 1)) .digest(); } return Buffer.concat(memo, length); } } exports.HKDF = HKDF; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaGtkZi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9oa2RmLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7QUFFdEMsbUNBQStDO0FBQy9DLHFDQUErRDtBQUUvRDs7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FBTyxNQUFNLENBQUMsTUFBTSxDQUFDLElBQUksRUFBRSxNQUFNLENBQUMsQ0FBQTtJQUNwQyxDQUFDO0FBQ0gsQ0FBQztBQWhGRCxvQkFnRkMifQ== /***/ }), /***/ 52809: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 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__(31430), exports); __exportStar(__nccwpck_require__(70535), exports); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7Ozs7Ozs7Ozs7Ozs7Ozs7QUFFdEMseUNBQXNCO0FBQ3RCLDJDQUF3QiJ9 /***/ }), /***/ 29551: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 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__(7102), exports); __exportStar(__nccwpck_require__(43058), exports); __exportStar(__nccwpck_require__(9074), exports); __exportStar(__nccwpck_require__(4683), exports); __exportStar(__nccwpck_require__(588), exports); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7Ozs7Ozs7Ozs7Ozs7Ozs7QUFFdEMscURBQWtDO0FBQ2xDLHlEQUFzQztBQUN0QyxtRUFBZ0Q7QUFDaEQsc0VBQW1EO0FBQ25ELHlFQUFzRCJ9 /***/ }), /***/ 7102: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.KMS = exports.cacheClients = exports.excludeRegions = exports.limitRegions = exports.getClient = exports.cacheKmsClients = exports.getKmsClient = exports.KmsKeyringNode = void 0; const kms_keyring_1 = __nccwpck_require__(53243); Object.defineProperty(exports, "getClient", ({ enumerable: true, get: function () { return kms_keyring_1.getClient; } })); Object.defineProperty(exports, "limitRegions", ({ enumerable: true, get: function () { return kms_keyring_1.limitRegions; } })); Object.defineProperty(exports, "excludeRegions", ({ enumerable: true, get: function () { return kms_keyring_1.excludeRegions; } })); Object.defineProperty(exports, "cacheClients", ({ enumerable: true, get: function () { return kms_keyring_1.cacheClients; } })); const material_management_node_1 = __nccwpck_require__(12563); const client_kms_1 = __nccwpck_require__(86121); Object.defineProperty(exports, "KMS", ({ enumerable: true, get: function () { return client_kms_1.KMS; } })); const version_1 = __nccwpck_require__(41672); const getKmsClient = (0, kms_keyring_1.getClient)(client_kms_1.KMS, { customUserAgent: `AwsEncryptionSdkJavascriptNodejs/${version_1.version}`, }); exports.getKmsClient = getKmsClient; const cacheKmsClients = (0, kms_keyring_1.cacheClients)(getKmsClient); exports.cacheKmsClients = cacheKmsClients; class KmsKeyringNode extends (0, kms_keyring_1.KmsKeyringClass)(material_management_node_1.KeyringNode) { constructor({ clientProvider = cacheKmsClients, keyIds, generatorKeyId, grantTokens, discovery, } = {}) { super({ clientProvider, keyIds, generatorKeyId, grantTokens, discovery }); } } exports.KmsKeyringNode = KmsKeyringNode; (0, material_management_node_1.immutableClass)(KmsKeyringNode); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoia21zX2tleXJpbmdfbm9kZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9rbXNfa2V5cmluZ19ub2RlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7QUFFdEMseURBVWdDO0FBcUM5QiwwRkExQ0EsdUJBQVMsT0EwQ0E7QUFDVCw2RkExQ0EsMEJBQVksT0EwQ0E7QUFDWiwrRkExQ0EsNEJBQWMsT0EwQ0E7QUFDZCw2RkExQ0EsMEJBQVksT0EwQ0E7QUF2Q2QsbUZBSzZDO0FBQzdDLG9EQUEwRDtBQWtDeEQsb0ZBbENPLGdCQUFHLE9Ba0NQO0FBakNMLHVDQUFtQztBQUNuQyxNQUFNLFlBQVksR0FBRyxJQUFBLHVCQUFTLEVBQUMsZ0JBQUcsRUFBRTtJQUNsQyxlQUFlLEVBQUUsb0NBQW9DLGlCQUFPLEVBQUU7Q0FDL0QsQ0FBQyxDQUFBO0FBd0JBLG9DQUFZO0FBdkJkLE1BQU0sZUFBZSxHQUFHLElBQUEsMEJBQVksRUFBQyxZQUFZLENBQUMsQ0FBQTtBQXdCaEQsMENBQWU7QUFsQmpCLE1BQWEsY0FBZSxTQUFRLElBQUEsNkJBQWUsRUFHakQsc0NBQW1DLENBQUM7SUFDcEMsWUFBWSxFQUNWLGNBQWMsR0FBRyxlQUFlLEVBQ2hDLE1BQU0sRUFDTixjQUFjLEVBQ2QsV0FBVyxFQUNYLFNBQVMsTUFDYyxFQUFFO1FBQ3pCLEtBQUssQ0FBQyxFQUFFLGNBQWMsRUFBRSxNQUFNLEVBQUUsY0FBYyxFQUFFLFdBQVcsRUFBRSxTQUFTLEVBQUUsQ0FBQyxDQUFBO0lBQzNFLENBQUM7Q0FDRjtBQWJELHdDQWFDO0FBQ0QsSUFBQSx5Q0FBYyxFQUFDLGNBQWMsQ0FBQyxDQUFBIn0= /***/ }), /***/ 9074: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AwsKmsMrkAwareSymmetricDiscoveryKeyringNode = void 0; const kms_keyring_1 = __nccwpck_require__(53243); const material_management_node_1 = __nccwpck_require__(12563); exports.AwsKmsMrkAwareSymmetricDiscoveryKeyringNode = (0, kms_keyring_1.AwsKmsMrkAwareSymmetricDiscoveryKeyringClass)(material_management_node_1.KeyringNode); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoia21zX21ya19kaXNjb3Zlcnlfa2V5cmluZ19ub2RlLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL2ttc19tcmtfZGlzY292ZXJ5X2tleXJpbmdfbm9kZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUEsb0VBQW9FO0FBQ3BFLHNDQUFzQzs7O0FBRXRDLHlEQUlnQztBQUNoQyxtRkFJNkM7QUFLaEMsUUFBQSwyQ0FBMkMsR0FDdEQsSUFBQSwwREFBNEMsRUFHMUMsc0NBQW1DLENBQUMsQ0FBQSJ9 /***/ }), /***/ 588: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildAwsKmsMrkAwareDiscoveryMultiKeyringNode = void 0; const kms_keyring_1 = __nccwpck_require__(53243); const material_management_1 = __nccwpck_require__(77519); const _1 = __nccwpck_require__(29551); const kms_mrk_discovery_keyring_node_1 = __nccwpck_require__(9074); exports.buildAwsKmsMrkAwareDiscoveryMultiKeyringNode = (0, kms_keyring_1.getAwsKmsMrkAwareDiscoveryMultiKeyringBuilder)(kms_mrk_discovery_keyring_node_1.AwsKmsMrkAwareSymmetricDiscoveryKeyringNode, material_management_1.MultiKeyringNode, _1.getKmsClient); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoia21zX21ya19kaXNjb3ZlcnlfbXVsdGlfa2V5cmluZ19ub2RlLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL2ttc19tcmtfZGlzY292ZXJ5X211bHRpX2tleXJpbmdfbm9kZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUEsb0VBQW9FO0FBQ3BFLHNDQUFzQzs7O0FBRXRDLHlEQUlnQztBQUNoQyx5RUFHd0M7QUFDeEMsd0JBQWdDO0FBQ2hDLHFGQUE4RjtBQVlqRixRQUFBLDRDQUE0QyxHQUN2RCxJQUFBLDJEQUE2QyxFQUczQyw0RUFBMkMsRUFBRSxzQ0FBZ0IsRUFBRSxlQUFZLENBQUMsQ0FBQSJ9 /***/ }), /***/ 43058: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AwsKmsMrkAwareSymmetricKeyringNode = void 0; const kms_keyring_1 = __nccwpck_require__(53243); const material_management_node_1 = __nccwpck_require__(12563); exports.AwsKmsMrkAwareSymmetricKeyringNode = (0, kms_keyring_1.AwsKmsMrkAwareSymmetricKeyringClass)(material_management_node_1.KeyringNode); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoia21zX21ya19rZXlyaW5nX25vZGUuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMva21zX21ya19rZXlyaW5nX25vZGUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7OztBQUV0Qyx5REFJZ0M7QUFDaEMsbUZBSTZDO0FBS2hDLFFBQUEsa0NBQWtDLEdBQzdDLElBQUEsaURBQW1DLEVBQ2pDLHNDQUFtQyxDQUNwQyxDQUFBIn0= /***/ }), /***/ 4683: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildAwsKmsMrkAwareStrictMultiKeyringNode = void 0; const kms_keyring_1 = __nccwpck_require__(53243); const material_management_node_1 = __nccwpck_require__(12563); const _1 = __nccwpck_require__(29551); const kms_mrk_keyring_node_1 = __nccwpck_require__(43058); exports.buildAwsKmsMrkAwareStrictMultiKeyringNode = (0, kms_keyring_1.getAwsKmsMrkAwareStrictMultiKeyringBuilder)(kms_mrk_keyring_node_1.AwsKmsMrkAwareSymmetricKeyringNode, material_management_node_1.MultiKeyringNode, _1.getKmsClient); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoia21zX21ya19zdHJpY3RfbXVsdGlfa2V5cmluZ19ub2RlLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL2ttc19tcmtfc3RyaWN0X211bHRpX2tleXJpbmdfbm9kZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUEsb0VBQW9FO0FBQ3BFLHNDQUFzQzs7O0FBRXRDLHlEQUdnQztBQUVoQyxtRkFHNkM7QUFDN0Msd0JBQWdDO0FBQ2hDLGlFQUEyRTtBQVM5RCxRQUFBLHlDQUF5QyxHQUNwRCxJQUFBLHdEQUEwQyxFQUd4Qyx5REFBa0MsRUFBRSwyQ0FBZ0IsRUFBRSxlQUFZLENBQUMsQ0FBQSJ9 /***/ }), /***/ 41672: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.version = void 0; // Generated by genversion. exports.version = '4.0.0'; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmVyc2lvbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy92ZXJzaW9uLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7OztBQUFBLDJCQUEyQjtBQUNkLFFBQUEsT0FBTyxHQUFHLE9BQU8sQ0FBQSJ9 /***/ }), /***/ 70798: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.constructArnInOtherRegion = exports.mrkAwareAwsKmsKeyIdCompare = exports.isMultiRegionAwsKmsIdentifier = exports.isMultiRegionAwsKmsArn = exports.validAwsKmsIdentifier = exports.parseAwsKmsResource = exports.getRegionFromIdentifier = exports.parseAwsKmsKeyArn = exports.KMS_SERVICE = void 0; const material_management_1 = __nccwpck_require__(77519); /* See: https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-kms * regex to match: 'resourceType/resourceId' || 'resourceType' * This is complicated because the `split(':')`. * The valid resourceType resourceId delimiters are `/`, `:`. * This means if the delimiter is a `:` it will be split out, * when splitting the whole arn. */ exports.KMS_SERVICE = 'kms'; const ARN_PREFIX = 'arn'; const KEY_RESOURCE_TYPE = 'key'; const ALIAS_RESOURCE_TYPE = 'alias'; const MRK_RESOURCE_ID_PREFIX = 'mrk-'; const VALID_RESOURCE_TYPES = [KEY_RESOURCE_TYPE, ALIAS_RESOURCE_TYPE]; /** * Returns a parsed ARN if a valid AWS KMS Key ARN. * If the request is a valid resource the function * will return false. * However if the ARN is malformed this function throws an error, */ function parseAwsKmsKeyArn(kmsKeyArn) { /* Precondition: A KMS Key Id must be a non-null string. */ (0, material_management_1.needs)(kmsKeyArn && typeof kmsKeyArn === 'string', 'KMS key arn must be a non-null string.'); const parts = kmsKeyArn.split(':'); /* Check for early return (Postcondition): A valid ARN has 6 parts. */ if (parts.length === 1) { /* Exceptional Postcondition: Only a valid AWS KMS resource. * This may result in this function being called twice. * However this is the most correct behavior. */ parseAwsKmsResource(kmsKeyArn); return false; } /* See: https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-kms * arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012 * arn:aws:kms:us-east-1:123456789012:alias/example-alias */ const [arnLiteral, partition, service, region = '', account = '', resource = '',] = parts; const [resourceType, ...resourceSection] = resource.split('/'); //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 //# The resource section MUST be non-empty and MUST be split by a //# single "/" any additional "/" are included in the resource id const resourceId = resourceSection.join('/'); /* If this is a valid AWS KMS Key ARN, return the parsed ARN */ (0, material_management_1.needs)( //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 //# MUST start with string "arn" arnLiteral === ARN_PREFIX && //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 //# The partition MUST be a non-empty partition && //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 //# The service MUST be the string "kms" service === exports.KMS_SERVICE && //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 //# The region MUST be a non-empty string region && //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 //# The account MUST be a non-empty string account && //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 //# The resource type MUST be either "alias" or "key" VALID_RESOURCE_TYPES.includes(resourceType) && //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 //# The resource id MUST be a non-empty string resourceId, 'Malformed arn.'); return { Partition: partition, Region: region, AccountId: account, ResourceType: resourceType, ResourceId: resourceId, }; } exports.parseAwsKmsKeyArn = parseAwsKmsKeyArn; function getRegionFromIdentifier(kmsKeyIdentifier) { const awsKmsKeyArn = parseAwsKmsKeyArn(kmsKeyIdentifier); return awsKmsKeyArn ? awsKmsKeyArn.Region : ''; } exports.getRegionFromIdentifier = getRegionFromIdentifier; function parseAwsKmsResource(resource) { /* Precondition: An AWS KMS resource can not have a `:`. * That would make it an ARNlike. */ (0, material_management_1.needs)(resource.split(':').length === 1, 'Malformed resource.'); /* `/` is a valid values in an AWS KMS Alias name. */ const [head, ...tail] = resource.split('/'); /* Precondition: A raw identifer is only an alias or a key. */ (0, material_management_1.needs)(head === ALIAS_RESOURCE_TYPE || !tail.length, 'Malformed resource.'); const [resourceType, resourceId] = head === ALIAS_RESOURCE_TYPE ? [ALIAS_RESOURCE_TYPE, tail.join('/')] : [KEY_RESOURCE_TYPE, head]; return { ResourceType: resourceType, ResourceId: resourceId, }; } exports.parseAwsKmsResource = parseAwsKmsResource; function validAwsKmsIdentifier(kmsKeyIdentifier) { return (parseAwsKmsKeyArn(kmsKeyIdentifier) || parseAwsKmsResource(kmsKeyIdentifier)); } exports.validAwsKmsIdentifier = validAwsKmsIdentifier; //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.8 //# This function MUST take a single AWS KMS ARN function isMultiRegionAwsKmsArn(kmsIdentifier) { //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.8 //# If the input is an invalid AWS KMS ARN this function MUST error. const awsKmsKeyArn = typeof kmsIdentifier === 'string' ? parseAwsKmsKeyArn(kmsIdentifier) : kmsIdentifier; /* Precondition: The kmsIdentifier must be an ARN. */ (0, material_management_1.needs)(awsKmsKeyArn, 'AWS KMS identifier is not an ARN'); const { ResourceType, ResourceId } = awsKmsKeyArn; //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.8 //# If resource type is "alias", this is an AWS KMS alias ARN and MUST //# return false. // //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.8 //# If resource type is "key" and resource ID starts with //# "mrk-", this is a AWS KMS multi-Region key ARN and MUST return true. // //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.8 //# If resource type is "key" and resource ID does not start with "mrk-", //# this is a (single-region) AWS KMS key ARN and MUST return false. return (ResourceType === KEY_RESOURCE_TYPE && ResourceId.startsWith(MRK_RESOURCE_ID_PREFIX)); } exports.isMultiRegionAwsKmsArn = isMultiRegionAwsKmsArn; //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.9 //# This function MUST take a single AWS KMS identifier function isMultiRegionAwsKmsIdentifier(kmsIdentifier) { //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.9 //# If the input starts with "arn:", this MUST return the output of //# identifying an an AWS KMS multi-Region ARN (aws-kms-key- //# arn.md#identifying-an-an-aws-kms-multi-region-arn) called with this //# input. if (kmsIdentifier.startsWith('arn:')) { return isMultiRegionAwsKmsArn(kmsIdentifier); } else if (kmsIdentifier.startsWith('alias/')) { //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.9 //# If the input starts with "alias/", this an AWS KMS alias and //# not a multi-Region key id and MUST return false. return false; } else if (kmsIdentifier.startsWith(MRK_RESOURCE_ID_PREFIX)) { //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.9 //# If the input starts //# with "mrk-", this is a multi-Region key id and MUST return true. return true; } //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.9 //# If //# the input does not start with any of the above, this is not a multi- //# Region key id and MUST return false. return false; } exports.isMultiRegionAwsKmsIdentifier = isMultiRegionAwsKmsIdentifier; /* Returns a boolean representing whether two AWS KMS Key IDs should be considered equal. * For everything except MRK-indicating ARNs, this is a direct comparison. * For MRK-indicating ARNs, this is a comparison of every ARN component except region. * Throws an error if the IDs are not explicitly equal and at least one of the IDs * is not a valid AWS KMS Key ARN or alias name. */ //= compliance/framework/aws-kms/aws-kms-mrk-match-for-decrypt.txt#2.5 //# The caller MUST provide: function mrkAwareAwsKmsKeyIdCompare(keyId1, keyId2) { //= compliance/framework/aws-kms/aws-kms-mrk-match-for-decrypt.txt#2.5 //# If both identifiers are identical, this function MUST return "true". if (keyId1 === keyId2) return true; //= compliance/framework/aws-kms/aws-kms-mrk-match-for-decrypt.txt#2.5 //# Otherwise if either input is not identified as a multi-Region key //# (aws-kms-key-arn.md#identifying-an-aws-kms-multi-region-key), then //# this function MUST return "false". const arn1 = parseAwsKmsKeyArn(keyId1); const arn2 = parseAwsKmsKeyArn(keyId2); if (!arn1 || !arn2) return false; if (!isMultiRegionAwsKmsArn(arn1) || !isMultiRegionAwsKmsArn(arn2)) return false; //= compliance/framework/aws-kms/aws-kms-mrk-match-for-decrypt.txt#2.5 //# Otherwise if both inputs are //# identified as a multi-Region keys (aws-kms-key-arn.md#identifying-an- //# aws-kms-multi-region-key), this function MUST return the result of //# comparing the "partition", "service", "accountId", "resourceType", //# and "resource" parts of both ARN inputs. return (arn1.Partition === arn2.Partition && arn1.AccountId === arn2.AccountId && arn1.ResourceType === arn2.ResourceType && arn1.ResourceId === arn2.ResourceId); } exports.mrkAwareAwsKmsKeyIdCompare = mrkAwareAwsKmsKeyIdCompare; /* Manually construct a new MRK ARN that looks like the old ARN except the region is replaced by a new region. * Throws an error if the input parsed ARN is not an MRK */ function constructArnInOtherRegion(parsedArn, region) { /* Precondition: Only reconstruct a multi region ARN. */ (0, material_management_1.needs)(isMultiRegionAwsKmsArn(parsedArn), 'Cannot attempt to construct an ARN in a new region from an non-MRK ARN.'); const { Partition, AccountId, ResourceType, ResourceId } = parsedArn; return [ ARN_PREFIX, Partition, exports.KMS_SERVICE, region, AccountId, ResourceType + '/' + ResourceId, ].join(':'); } exports.constructArnInOtherRegion = constructArnInOtherRegion; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXJuX3BhcnNpbmcuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvYXJuX3BhcnNpbmcudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7OztBQUV0Qyx5RUFBdUQ7QUFFdkQ7Ozs7OztHQU1HO0FBQ1UsUUFBQSxXQUFXLEdBQUcsS0FBSyxDQUFBO0FBVWhDLE1BQU0sVUFBVSxHQUFHLEtBQUssQ0FBQTtBQUN4QixNQUFNLGlCQUFpQixHQUFHLEtBQUssQ0FBQTtBQUMvQixNQUFNLG1CQUFtQixHQUFHLE9BQU8sQ0FBQTtBQUNuQyxNQUFNLHNCQUFzQixHQUFHLE1BQU0sQ0FBQTtBQUVyQyxNQUFNLG9CQUFvQixHQUFHLENBQUMsaUJBQWlCLEVBQUUsbUJBQW1CLENBQUMsQ0FBQTtBQUVyRTs7Ozs7R0FLRztBQUNILFNBQWdCLGlCQUFpQixDQUMvQixTQUFpQjtJQUVqQiwyREFBMkQ7SUFDM0QsSUFBQSwyQkFBSyxFQUNILFNBQVMsSUFBSSxPQUFPLFNBQVMsS0FBSyxRQUFRLEVBQzFDLHdDQUF3QyxDQUN6QyxDQUFBO0lBRUQsTUFBTSxLQUFLLEdBQUcsU0FBUyxDQUFDLEtB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0wsVUFBVTtRQUNWLFNBQVM7UUFDVCxtQkFBVztRQUNYLE1BQU07UUFDTixTQUFTO1FBQ1QsWUFBWSxHQUFHLEdBQUcsR0FBRyxVQUFVO0tBQ2hDLENBQUMsSUFBSSxDQUFDLEdBQUcsQ0FBQyxDQUFBO0FBQ2IsQ0FBQztBQWxCRCw4REFrQkMifQ== /***/ }), /***/ 47633: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.awsKmsMrkAreUnique = void 0; const arn_parsing_1 = __nccwpck_require__(70798); //= compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5 //# The caller MUST provide: function awsKmsMrkAreUnique(awsKmsIdentifers) { const multiRegionKeys = awsKmsIdentifers.filter((i) => (0, arn_parsing_1.isMultiRegionAwsKmsIdentifier)(i)); //= compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5 //# If the list does not contain any multi-Region keys (aws-kms-key- //# arn.md#identifying-an-aws-kms-multi-region-key) this function MUST //# exit successfully. if (!multiRegionKeys.length) return; const multiRegionKeyIds = multiRegionKeys.map((mrk) => { const arn = (0, arn_parsing_1.parseAwsKmsKeyArn)(mrk); return arn ? arn.ResourceId : mrk; }); //= compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5 //# If there are zero duplicate resource ids between the multi-region //# keys, this function MUST exit successfully if (new Set(multiRegionKeyIds).size === multiRegionKeys.length) return; //= compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5 //# If any duplicate multi-region resource ids exist, this function MUST //# yield an error that includes all identifiers with duplicate resource //# ids not only the first duplicate found. const duplicateMultiRegionIdentifiers = multiRegionKeyIds .map((mrk, i, a) => { if (a.indexOf(mrk) !== a.lastIndexOf(mrk)) return multiRegionKeys[i]; /* Postcondition: Remove non-duplicate multi-Region keys. */ return false; }) .filter((dup) => dup) .join(','); throw new Error(`Related multi-Region keys: ${duplicateMultiRegionIdentifiers} are not allowed.`); } exports.awsKmsMrkAreUnique = awsKmsMrkAreUnique; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXdzX2ttc19tcmtfYXJlX3VuaXF1ZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9hd3Nfa21zX21ya19hcmVfdW5pcXVlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7QUFFdEMsK0NBQWdGO0FBRWhGLCtEQUErRDtBQUMvRCw0QkFBNEI7QUFDNUIsU0FBZ0Isa0JBQWtCLENBQUMsZ0JBQTBCO0lBQzNELE1BQU0sZUFBZSxHQUFHLGdCQUFnQixDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsRUFBRSxFQUFFLENBQ3BELElBQUEsMkNBQTZCLEVBQUMsQ0FBQyxDQUFDLENBQ2pDLENBQUE7SUFFRCwrREFBK0Q7SUFDL0Qsb0VBQW9FO0lBQ3BFLHNFQUFzRTtJQUN0RSxzQkFBc0I7SUFDdEIsSUFBSSxDQUFDLGVBQWUsQ0FBQyxNQUFNO1FBQUUsT0FBTTtJQUVuQyxNQUFNLGlCQUFpQixHQUFHLGVBQWUsQ0FBQyxHQUFHLENBQUMsQ0FBQyxHQUFHLEVBQUUsRUFBRTtRQUNwRCxNQUFNLEdBQUcsR0FBRyxJQUFBLCtCQUFpQixFQUFDLEdBQUcsQ0FBQyxDQUFBO1FBQ2xDLE9BQU8sR0FBRyxDQUFDLENBQUMsQ0FBQyxHQUFHLENBQUMsVUFBVSxDQUFDLENBQUMsQ0FBQyxHQUFHLENBQUE7SUFDbkMsQ0FBQyxDQUFDLENBQUE7SUFDRiwrREFBK0Q7SUFDL0QscUVBQXFFO0lBQ3JFLDhDQUE4QztJQUM5QyxJQUFJLElBQUksR0FBRyxDQUFDLGlCQUFpQixDQUFDLENBQUMsSUFBSSxLQUFLLGVBQWUsQ0FBQyxNQUFNO1FBQUUsT0FBTTtJQUV0RSwrREFBK0Q7SUFDL0Qsd0VBQXdFO0lBQ3hFLHdFQUF3RTtJQUN4RSwyQ0FBMkM7SUFDM0MsTUFBTSwrQkFBK0IsR0FBRyxpQkFBaUI7U0FDdEQsR0FBRyxDQUFDLENBQUMsR0FBRyxFQUFFLENBQUMsRUFBRSxDQUFDLEVBQUUsRUFBRTtRQUNqQixJQUFJLENBQUMsQ0FBQyxPQUFPLENBQUMsR0FBRyxDQUFDLEtBQUssQ0FBQyxDQUFDLFdBQVcsQ0FBQyxHQUFHLENBQUM7WUFBRSxPQUFPLGVBQWUsQ0FBQyxDQUFDLENBQUMsQ0FBQTtRQUNwRSw0REFBNEQ7UUFDNUQsT0FBTyxLQUFLLENBQUE7SUFDZCxDQUFDLENBQUM7U0FDRCxNQUFNLENBQUMsQ0FBQyxHQUFHLEVBQUUsRUFBRSxDQUFDLEdBQUcsQ0FBQztTQUNwQixJQUFJLENBQUMsR0FBRyxDQUFDLENBQUE7SUFFWixNQUFNLElBQUksS0FBSyxDQUNiLDhCQUE4QiwrQkFBK0IsbUJBQW1CLENBQ2pGLENBQUE7QUFDSCxDQUFDO0FBcENELGdEQW9DQyJ9 /***/ }), /***/ 2309: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.kmsResponseToEncryptedDataKey = exports.decrypt = exports.encrypt = exports.generateDataKey = exports.KMS_PROVIDER_ID = void 0; const arn_parsing_1 = __nccwpck_require__(70798); const material_management_1 = __nccwpck_require__(77519); exports.KMS_PROVIDER_ID = 'aws-kms'; async function generateDataKey(clientProvider, NumberOfBytes, KeyId, EncryptionContext, GrantTokens) { const client = typeof clientProvider === 'function' ? clientProvider((0, arn_parsing_1.getRegionFromIdentifier)(KeyId)) : clientProvider; /* Check for early return (Postcondition): clientProvider did not return a client for generateDataKey. */ if (!client) return false; const v2vsV3Response = client.generateDataKey({ KeyId, GrantTokens, NumberOfBytes, EncryptionContext, }); const v2vsV3Promise = 'promise' in v2vsV3Response ? v2vsV3Response.promise() : v2vsV3Response; const dataKey = await v2vsV3Promise; return safeGenerateDataKey(dataKey); } exports.generateDataKey = generateDataKey; async function encrypt(clientProvider, Plaintext, KeyId, EncryptionContext, GrantTokens) { const client = typeof clientProvider === 'function' ? clientProvider((0, arn_parsing_1.getRegionFromIdentifier)(KeyId)) : clientProvider; /* Check for early return (Postcondition): clientProvider did not return a client for encrypt. */ if (!client) return false; const v2vsV3Response = client.encrypt({ KeyId, Plaintext, EncryptionContext, GrantTokens, }); const v2vsV3Promise = 'promise' in v2vsV3Response ? v2vsV3Response.promise() : v2vsV3Response; const kmsEDK = await v2vsV3Promise; return safeEncryptOutput(kmsEDK); } exports.encrypt = encrypt; async function decrypt(clientProvider, { providerId, providerInfo, encryptedDataKey }, EncryptionContext, GrantTokens) { /* Precondition: The EDK must be a KMS edk. */ (0, material_management_1.needs)(providerId === exports.KMS_PROVIDER_ID, 'Unsupported providerId'); const client = typeof clientProvider === 'function' ? clientProvider((0, arn_parsing_1.getRegionFromIdentifier)(providerInfo)) : clientProvider; /* Check for early return (Postcondition): clientProvider did not return a client for decrypt. */ if (!client) return false; /* The AWS KMS KeyId *must* be set. */ const v2vsV3Response = client.decrypt({ KeyId: providerInfo, CiphertextBlob: encryptedDataKey, EncryptionContext, GrantTokens, }); const v2vsV3Promise = 'promise' in v2vsV3Response ? v2vsV3Response.promise() : v2vsV3Response; const dataKey = await v2vsV3Promise; return safeDecryptOutput(dataKey); } exports.decrypt = decrypt; function kmsResponseToEncryptedDataKey({ KeyId: providerInfo, CiphertextBlob: encryptedDataKey, }) { return new material_management_1.EncryptedDataKey({ providerId: exports.KMS_PROVIDER_ID, providerInfo, encryptedDataKey, }); } exports.kmsResponseToEncryptedDataKey = kmsResponseToEncryptedDataKey; function safeGenerateDataKey(dataKey) { /* Postcondition: KMS must return serializable generate data key. */ (0, material_management_1.needs)(typeof dataKey.KeyId === 'string' && dataKey.Plaintext instanceof Uint8Array && dataKey.CiphertextBlob instanceof Uint8Array, 'Malformed KMS response.'); return safePlaintext(dataKey); } function safeEncryptOutput(dataKey) { /* Postcondition: KMS must return serializable encrypted data key. */ (0, material_management_1.needs)(typeof dataKey.KeyId === 'string' && dataKey.CiphertextBlob instanceof Uint8Array, 'Malformed KMS response.'); return dataKey; } function safeDecryptOutput(dataKey) { /* Postcondition: KMS must return usable decrypted key. */ (0, material_management_1.needs)(typeof dataKey.KeyId === 'string' && dataKey.Plaintext instanceof Uint8Array, 'Malformed KMS response.'); return safePlaintext(dataKey); } function safePlaintext(dataKey) { /* The KMS Client *may* return a Buffer that is not isolated. * i.e. the byteOffset !== 0. * This means that the unencrypted data key is possibly accessible to someone else. * If this is the node shared Buffer, then other code within this process _could_ find this secret. * Copy Plaintext to an isolated ArrayBuffer and zero the Plaintext. * This means that this function will *always* zero out the value returned to it from the KMS client. * While this is safe to do here, copying this code somewhere else may produce unexpected results. */ const { Plaintext } = dataKey; dataKey.Plaintext = new Uint8Array(Plaintext); Plaintext.fill(0); return dataKey; } //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaGVscGVycy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9oZWxwZXJzLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7QUFZdEMsK0NBQXVEO0FBQ3ZELHlFQUl3QztBQUUzQixRQUFBLGVBQWUsR0FBRyxTQUFTLENBQUE7QUFFakMsS0FBSyxVQUFVLGVBQWUsQ0FDbkMsY0FBa0QsRUFDbEQsYUFBcUIsRUFDckIsS0FBYSxFQ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FpQixDQUFDLE9BQXdCO0lBQ2pELDBEQUEwRDtJQUMxRCxJQUFBLDJCQUFLLEVBQ0gsT0FBTyxPQUFPLENBQUMsS0FBSyxLQUFLLFFBQVE7UUFDL0IsT0FBTyxDQUFDLFNBQVMsWUFBWSxVQUFVLEVBQ3pDLHlCQUF5QixDQUMxQixDQUFBO0lBRUQsT0FBTyxhQUFhLENBQ2xCLE9BQWtDLENBQ1IsQ0FBQTtBQUM5QixDQUFDO0FBRUQsU0FBUyxhQUFhLENBQ3BCLE9BQWtFO0lBRWxFOzs7Ozs7O09BT0c7SUFDSCxNQUFNLEVBQUUsU0FBUyxFQUFFLEdBQUcsT0FBTyxDQUFBO0lBQzdCLE9BQU8sQ0FBQyxTQUFTLEdBQUcsSUFBSSxVQUFVLENBQUMsU0FBUyxDQUFDLENBQUE7SUFDN0MsU0FBUyxDQUFDLElBQUksQ0FBQyxDQUFDLENBQUMsQ0FBQTtJQUNqQixPQUFPLE9BQU8sQ0FBQTtBQUNoQixDQUFDIn0= /***/ }), /***/ 53243: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 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__(86624), exports); __exportStar(__nccwpck_require__(68982), exports); __exportStar(__nccwpck_require__(36764), exports); __exportStar(__nccwpck_require__(11214), exports); __exportStar(__nccwpck_require__(2309), exports); __exportStar(__nccwpck_require__(97571), exports); __exportStar(__nccwpck_require__(24603), exports); __exportStar(__nccwpck_require__(88663), exports); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7Ozs7Ozs7Ozs7Ozs7Ozs7QUFFdEMsd0RBQXFDO0FBQ3JDLGdEQUE2QjtBQUM3QixvREFBaUM7QUFDakMsOERBQTJDO0FBQzNDLDRDQUF5QjtBQUN6Qiw0REFBeUM7QUFDekMsaUVBQThDO0FBQzlDLG9FQUFpRCJ9 /***/ }), /***/ 86624: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.deferCache = exports.cacheClients = exports.excludeRegions = exports.limitRegions = exports.getClient = void 0; const material_management_1 = __nccwpck_require__(77519); function getClient(KMSClient, defaultConfig) { return function getKmsClient(region) { /* a KMS alias is supported. These do not have a region * in this case, the Encryption SDK should find the default region * or the default region needs to be supplied to this function */ const config = (region ? { ...defaultConfig, region } : { ...defaultConfig }); const client = new KMSClient(config); /* Postcondition: A region must be configured. * The AWS SDK has a process for determining the default region. * A user can configure a default region by setting it in `defaultConfig` * But KMS requires a region to operate. */ // @ts-ignore the V3 client has set the config to protected, reasonable, but I need to know... (0, material_management_1.needs)(client.config.region, 'A region is required'); return client; }; } exports.getClient = getClient; function limitRegions(regions, getClient) { /* Precondition: limitRegions requires that region be a string. */ (0, material_management_1.needs)(regions.every((r) => !!r && typeof r === 'string'), 'Can only limit on region strings'); return (region) => { if (!regions.includes(region)) return false; return getClient(region); }; } exports.limitRegions = limitRegions; function excludeRegions(regions, getClient) { /* Precondition: excludeRegions requires region be a string. */ (0, material_management_1.needs)(regions.every((r) => !!r && typeof r === 'string'), 'Can only exclude on region strings'); return (region) => { if (regions.includes(region)) return false; return getClient(region); }; } exports.excludeRegions = excludeRegions; function cacheClients(getClient) { const clientsCache = {}; return (region) => { // Do not cache until KMS has been responded in the given region if (!Object.prototype.hasOwnProperty.call(clientsCache, region)) return deferCache(clientsCache, region, getClient(region)); return clientsCache[region]; }; } exports.cacheClients = cacheClients; /* It is possible that a malicious user can attempt a local resource * DOS by sending ciphertext with a large number of spurious regions. * This will fill the cache with regions and exhaust resources. * To avoid this, a call succeeds in contacting KMS. * This does *not* mean that this call is successful, * only that the region is backed by a functional KMS service. */ function deferCache(clientsCache, region, client) { /* Check for early return (Postcondition): No client, then I cache false and move on. */ if (!client) { clientsCache[region] = false; return false; } const { encrypt, decrypt, generateDataKey } = client; return ['encrypt', 'decrypt', 'generateDataKey'].reduce(wrapOperation, client); /* Wrap each of the operations to cache the client on response */ function wrapOperation(client, name) { const original = client[name]; client[name] = async function wrappedOperation(args) { // @ts-ignore (there should be a TypeScript solution for this) const v2vsV3Response = original.call(client, args); const v2vsV3Promise = 'promise' in v2vsV3Response ? v2vsV3Response.promise() : v2vsV3Response; return v2vsV3Promise .then((response) => { clientsCache[region] = Object.assign(client, { encrypt, decrypt, generateDataKey, }); return response; }) .catch(async (e) => { /* Errors from a KMS contact mean that the region is "live". * As such the client can be cached because the problem is not with the client per se, * but with the request made. */ if (e.$metadata && e.$metadata.httpStatusCode) { clientsCache[region] = Object.assign(client, { encrypt, decrypt, generateDataKey, }); } // The request was not successful return Promise.reject(e); }); }; return client; } } exports.deferCache = deferCache; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoia21zX2NsaWVudF9zdXBwbGllci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy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FBZTtpQkFDaEIsQ0FBQyxDQUFBO2dCQUNGLE9BQU8sUUFBUSxDQUFBO1lBQ2pCLENBQUMsQ0FBQztpQkFDRCxLQUFLLENBQUMsS0FBSyxFQUFFLENBQU0sRUFBRSxFQUFFO2dCQUN0Qjs7O21CQUdHO2dCQUNILElBQUksQ0FBQyxDQUFDLFNBQVMsSUFBSSxDQUFDLENBQUMsU0FBUyxDQUFDLGNBQWMsRUFBRTtvQkFDN0MsWUFBWSxDQUFDLE1BQU0sQ0FBQyxHQUFHLE1BQU0sQ0FBQyxNQUFNLENBQUMsTUFBTSxFQUFFO3dCQUMzQyxPQUFPO3dCQUNQLE9BQU87d0JBQ1AsZUFBZTtxQkFDaEIsQ0FBQyxDQUFBO2lCQUNIO2dCQUNELGlDQUFpQztnQkFDakMsT0FBTyxPQUFPLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUFBO1lBQzFCLENBQUMsQ0FBQyxDQUFBO1FBQ04sQ0FBQyxDQUFBO1FBQ0QsT0FBTyxNQUFNLENBQUE7SUFDZixDQUFDO0FBQ0gsQ0FBQztBQXpERCxnQ0F5REMifQ== /***/ }), /***/ 68982: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.KmsKeyringClass = void 0; const material_management_1 = __nccwpck_require__(77519); const helpers_1 = __nccwpck_require__(2309); const arn_parsing_1 = __nccwpck_require__(70798); function KmsKeyringClass(BaseKeyring) { class KmsKeyring extends BaseKeyring { constructor({ clientProvider, generatorKeyId, keyIds = [], grantTokens, discovery, discoveryFilter, }) { super(); /* Precondition: This is an abstract class. (But TypeScript does not have a clean way to model this) */ (0, material_management_1.needs)(this.constructor !== KmsKeyring, 'new KmsKeyring is not allowed'); /* Precondition: A noop KmsKeyring is not allowed. */ (0, material_management_1.needs)(!(!discovery && !generatorKeyId && !keyIds.length), 'Noop keyring is not allowed: Set a keyId or discovery'); /* Precondition: A keyring can be either a Discovery or have keyIds configured. */ (0, material_management_1.needs)(!(discovery && (generatorKeyId || keyIds.length)), 'A keyring can be either a Discovery or have keyIds configured.'); /* Precondition: Discovery filter can only be configured in discovery mode. */ (0, material_management_1.needs)(discovery || (!discovery && !discoveryFilter), 'Account and partition decrypt filtering are only supported when discovery === true'); /* Precondition: A Discovery filter *must* be able to match something. * I am not going to wait to tell you * that no CMK can match an empty account list. * e.g. [], [''], '' are not valid. */ (0, material_management_1.needs)(!discoveryFilter || (discoveryFilter.accountIDs && discoveryFilter.accountIDs.length && !!discoveryFilter.partition && discoveryFilter.accountIDs.every((a) => typeof a === 'string' && !!a)), 'A discovery filter must be able to match something.'); /* Precondition: All KMS key identifiers must be valid. */ (0, material_management_1.needs)(!generatorKeyId || (0, arn_parsing_1.validAwsKmsIdentifier)(generatorKeyId), 'Malformed arn.'); (0, material_management_1.needs)(keyIds.every((keyArn) => (0, arn_parsing_1.validAwsKmsIdentifier)(keyArn)), 'Malformed arn.'); /* Precondition: clientProvider needs to be a callable function. */ (0, material_management_1.needs)(typeof clientProvider === 'function', 'Missing clientProvider'); (0, material_management_1.readOnlyProperty)(this, 'clientProvider', clientProvider); (0, material_management_1.readOnlyProperty)(this, 'keyIds', Object.freeze(keyIds.slice())); (0, material_management_1.readOnlyProperty)(this, 'generatorKeyId', generatorKeyId); (0, material_management_1.readOnlyProperty)(this, 'grantTokens', grantTokens); (0, material_management_1.readOnlyProperty)(this, 'isDiscovery', !!discovery); (0, material_management_1.readOnlyProperty)(this, 'discoveryFilter', discoveryFilter ? Object.freeze({ ...discoveryFilter, accountIDs: Object.freeze(discoveryFilter.accountIDs), }) : discoveryFilter); } /* Keyrings *must* preserve the order of EDK's. The generatorKeyId is the first on this list. */ async _onEncrypt(material) { /* Check for early return (Postcondition): Discovery Keyrings do not encrypt. */ if (this.isDiscovery) return material; const keyIds = this.keyIds.slice(); const { clientProvider, generatorKeyId, grantTokens } = this; if (generatorKeyId && !material.hasUnencryptedDataKey) { const dataKey = await (0, helpers_1.generateDataKey)(clientProvider, material.suite.keyLengthBytes, generatorKeyId, material.encryptionContext, grantTokens); /* Precondition: A generatorKeyId must generate if we do not have an unencrypted data key. * Client supplier is allowed to return undefined if, for example, user wants to exclude particular * regions. But if we are here it means that user configured keyring with a KMS key that was * incompatible with the client supplier in use. */ if (!dataKey) throw new Error('Generator KMS key did not generate a data key'); const flags = material_management_1.KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY | material_management_1.KeyringTraceFlag.WRAPPING_KEY_SIGNED_ENC_CTX | material_management_1.KeyringTraceFlag.WRAPPING_KEY_ENCRYPTED_DATA_KEY; const trace = { keyNamespace: helpers_1.KMS_PROVIDER_ID, keyName: dataKey.KeyId, flags, }; material /* Postcondition: The generated unencryptedDataKey length must match the algorithm specification. * See cryptographic_materials as setUnencryptedDataKey will throw in this case. */ .setUnencryptedDataKey(dataKey.Plaintext, trace) .addEncryptedDataKey((0, helpers_1.kmsResponseToEncryptedDataKey)(dataKey), material_management_1.KeyringTraceFlag.WRAPPING_KEY_ENCRYPTED_DATA_KEY | material_management_1.KeyringTraceFlag.WRAPPING_KEY_SIGNED_ENC_CTX); } else if (generatorKeyId) { keyIds.unshift(generatorKeyId); } /* Precondition: If a generator does not exist, an unencryptedDataKey *must* already exist. * Furthermore *only* CMK's explicitly designated as generators can generate data keys. * See cryptographic_materials as getUnencryptedDataKey will throw in this case. */ const unencryptedDataKey = (0, material_management_1.unwrapDataKey)(material.getUnencryptedDataKey()); const flags = material_management_1.KeyringTraceFlag.WRAPPING_KEY_ENCRYPTED_DATA_KEY | material_management_1.KeyringTraceFlag.WRAPPING_KEY_SIGNED_ENC_CTX; for (const kmsKey of keyIds) { const kmsEDK = await (0, helpers_1.encrypt)(clientProvider, unencryptedDataKey, kmsKey, material.encryptionContext, grantTokens); /* clientProvider may not return a client, in this case there is not an EDK to add */ if (kmsEDK) material.addEncryptedDataKey((0, helpers_1.kmsResponseToEncryptedDataKey)(kmsEDK), flags); } return material; } async _onDecrypt(material, encryptedDataKeys) { const keyIds = this.keyIds.slice(); const { clientProvider, generatorKeyId, grantTokens } = this; if (generatorKeyId) keyIds.unshift(generatorKeyId); /* If there are no key IDs in the list, keyring is in "discovery" mode and will attempt KMS calls with * every ARN it comes across in the message. If there are key IDs in the list, it will cross check the * ARN it reads with that list before attempting KMS calls. Note that if caller provided key IDs in * anything other than a CMK ARN format, the Encryption SDK will not attempt to decrypt those data keys, because * the EDK data format always specifies the CMK with the full (non-alias) ARN. */ const decryptableEDKs = encryptedDataKeys.filter(filterEDKs(keyIds, this)); const cmkErrors = []; for (const edk of decryptableEDKs) { let dataKey = false; try { dataKey = await (0, helpers_1.decrypt)(clientProvider, edk, material.encryptionContext, grantTokens); } catch (e) { /* Failures onDecrypt should not short-circuit the process * If the caller does not have access they may have access * through another Keyring. */ cmkErrors.push({ errPlus: e }); } /* Check for early return (Postcondition): clientProvider may not return a client. */ if (!dataKey) continue; /* Postcondition: The KeyId from KMS must match the encoded KeyID. */ (0, material_management_1.needs)(dataKey.KeyId === edk.providerInfo, 'KMS Decryption key does not match the requested key id.'); const flags = material_management_1.KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY | material_management_1.KeyringTraceFlag.WRAPPING_KEY_VERIFIED_ENC_CTX; const trace = { keyNamespace: helpers_1.KMS_PROVIDER_ID, keyName: dataKey.KeyId, flags, }; /* Postcondition: The decrypted unencryptedDataKey length must match the algorithm specification. * See cryptographic_materials as setUnencryptedDataKey will throw in this case. */ material.setUnencryptedDataKey(dataKey.Plaintext, trace); return material; } /* Postcondition: A CMK must provide a valid data key or KMS must not have raised any errors. * If I have a data key, * decrypt errors can be ignored. * However, if I was unable to decrypt a data key AND I have errors, * these errors should bubble up. * Otherwise, the only error customers will see is that * the material does not have an unencrypted data key. * So I return a concatenated Error message */ (0, material_management_1.needs)(material.hasValidKey() || (!material.hasValidKey() && !cmkErrors.length), cmkErrors.reduce((m, e, i) => `${m} Error #${i + 1} \n ${e.errPlus.stack} \n`, 'Unable to decrypt data key and one or more KMS CMKs had an error. \n ')); return material; } } (0, material_management_1.immutableClass)(KmsKeyring); return KmsKeyring; } exports.KmsKeyringClass = KmsKeyringClass; function filterEDKs(keyIds, { isDiscovery, discoveryFilter }) { return function filter({ providerId, providerInfo }) { /* Check for early return (Postcondition): Only AWS KMS EDK should be attempted. */ if (providerId !== helpers_1.KMS_PROVIDER_ID) return false; /* Discovery keyrings can not have keyIds configured, * and non-discovery keyrings must have keyIds configured. */ if (isDiscovery) { /* Check for early return (Postcondition): There is no discoveryFilter to further condition discovery. */ if (!discoveryFilter) return true; const parsedArn = (0, arn_parsing_1.parseAwsKmsKeyArn)(providerInfo); /* Postcondition: Provider info is a well formed AWS KMS ARN. */ (0, material_management_1.needs)(parsedArn, 'Malformed arn in provider info.'); /* If the providerInfo is an invalid ARN this will throw. * But, this function is also used to extract regions * from an CMK to generate a regional client. * This means it will NOT throw for something * that looks like a bare alias or key id. * However, these constructions will not have an account or partition. */ const { AccountId, Partition } = parsedArn; /* Postcondition: The account and partition *must* match the discovery filter. * Since we are offering a runtime discovery of CMKs * it is best to have some form of filter on this. * The providerInfo is a CMK ARN and will have the account and partition. * By offering these levers customers can easily bound * the CMKs to ones they control without knowing the CMKs * when the AWS KMS Keyring is instantiated. */ return (discoveryFilter.partition === Partition && discoveryFilter.accountIDs.some((a) => a === AccountId)); } else { /* Postcondition: The EDK CMK (providerInfo) *must* match a configured CMK. */ return keyIds.includes(providerInfo); } }; } //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoia21zX2tleXJpbmcuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMva21zX2tleXJpbmcudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7OztBQUl0Qyx5RUF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lBQVksRUFBb0I7UUFDbkUsbUZBQW1GO1FBQ25GLElBQUksVUFBVSxLQUFLLHlCQUFlO1lBQUUsT0FBTyxLQUFLLENBQUE7UUFDaEQ7O1dBRUc7UUFDSCxJQUFJLFdBQVcsRUFBRTtZQUNmLHlHQUF5RztZQUN6RyxJQUFJLENBQUMsZUFBZTtnQkFBRSxPQUFPLElBQUksQ0FBQTtZQUVqQyxNQUFNLFNBQVMsR0FBRyxJQUFBLCtCQUFpQixFQUFDLFlBQVksQ0FBQyxDQUFBO1lBQ2pELGdFQUFnRTtZQUNoRSxJQUFBLDJCQUFLLEVBQUMsU0FBUyxFQUFFLGlDQUFpQyxDQUFDLENBQUE7WUFDbkQ7Ozs7OztlQU1HO1lBQ0gsTUFBTSxFQUFFLFNBQVMsRUFBRSxTQUFTLEVBQUUsR0FBRyxTQUFTLENBQUE7WUFDMUM7Ozs7Ozs7ZUFPRztZQUNILE9BQU8sQ0FDTCxlQUFlLENBQUMsU0FBUyxLQUFLLFNBQVM7Z0JBQ3ZDLGVBQWUsQ0FBQyxVQUFVLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQyxFQUFFLEVBQUUsQ0FBQyxDQUFDLEtBQUssU0FBUyxDQUFDLENBQ3hELENBQUE7U0FDRjthQUFNO1lBQ0wsOEVBQThFO1lBQzlFLE9BQU8sTUFBTSxDQUFDLFFBQVEsQ0FBQyxZQUFZLENBQUMsQ0FBQTtTQUNyQztJQUNILENBQUMsQ0FBQTtBQUNILENBQUMifQ== /***/ }), /***/ 11214: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AwsKmsMrkAwareSymmetricDiscoveryKeyringClass = void 0; const material_management_1 = __nccwpck_require__(77519); const arn_parsing_1 = __nccwpck_require__(70798); const helpers_1 = __nccwpck_require__(2309); function AwsKmsMrkAwareSymmetricDiscoveryKeyringClass(BaseKeyring) { class AwsKmsMrkAwareSymmetricDiscoveryKeyring //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.5 //# MUST implement that AWS Encryption SDK Keyring interface (../keyring- //# interface.md#interface) extends BaseKeyring { //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.6 //# On initialization the caller MUST provide: constructor({ client, grantTokens, discoveryFilter, }) { super(); //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.6 //# The keyring MUST know what Region the AWS KMS client is in. // //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.6 //# It //# SHOULD obtain this information directly from the client as opposed to //# having an additional parameter. // //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.6 //# However if it can not, then it MUST //# NOT create the client itself. // //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.6 //# It SHOULD have a Region parameter and //# SHOULD try to identify mismatched configurations. // // @ts-ignore the V3 client has set the config to protected const clientRegion = client.config.region; (0, material_management_1.needs)(clientRegion, 'Client must be configured to a region.'); /* Precondition: The AwsKmsMrkAwareSymmetricDiscoveryKeyring Discovery filter *must* be able to match something. * I am not going to wait to tell you * that no CMK can match an empty account list. * e.g. [], [''], '' are not valid. */ (0, material_management_1.needs)(!discoveryFilter || (discoveryFilter.accountIDs && discoveryFilter.accountIDs.length && !!discoveryFilter.partition && discoveryFilter.accountIDs.every((a) => typeof a === 'string' && !!a)), 'A discovery filter must be able to match something.'); (0, material_management_1.readOnlyProperty)(this, 'client', client); // AWS SDK v3 stores the clientRegion behind an async function if (typeof clientRegion == 'function') { /* Postcondition: Store the AWS SDK V3 region promise as the clientRegion. * This information MUST be communicated to OnDecrypt. * If a caller creates a keyring, * and then calls OnDecrypt all in synchronous code * then the v3 region will not have been able to resolve. * If clientRegion was null, * then the keyring would filter out all EDKs * because the region does not match. */ this.clientRegion = clientRegion().then((region) => { /* Postcondition: Resolve the AWS SDK V3 region promise and update clientRegion. */ (0, material_management_1.readOnlyProperty)(this, 'clientRegion', region); /* Postcondition: Resolve the promise with the value set. */ return region; }); } else { (0, material_management_1.readOnlyProperty)(this, 'clientRegion', clientRegion); } (0, material_management_1.readOnlyProperty)(this, 'grantTokens', grantTokens); (0, material_management_1.readOnlyProperty)(this, 'discoveryFilter', discoveryFilter ? Object.freeze({ ...discoveryFilter, accountIDs: Object.freeze(discoveryFilter.accountIDs), }) : discoveryFilter); } async _onEncrypt() { //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.7 //# This function MUST fail. throw new Error('AwsKmsMrkAwareSymmetricDiscoveryKeyring cannot be used to encrypt'); } //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8 //# OnDecrypt MUST take decryption materials (structures.md#decryption- //# materials) and a list of encrypted data keys //# (structures.md#encrypted-data-key) as input. async _onDecrypt(material, encryptedDataKeys) { //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8 //# If the decryption materials (structures.md#decryption-materials) //# already contained a valid plaintext data key OnDecrypt MUST //# immediately return the unmodified decryption materials //# (structures.md#decryption-materials). if (material.hasValidKey()) return material; // See the constructor, this is to support both AWS SDK v2 and v3. (0, material_management_1.needs)(typeof this.clientRegion === 'string' || /* Precondition: AWS SDK V3 region promise MUST have resolved to a string. * In the constructor the region promise resolves * to the same value that is then set. */ // @ts-ignore typeof (await this.clientRegion) == 'string', 'clientRegion MUST be a string.'); const { client, grantTokens, clientRegion } = this; //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8 //# The set of encrypted data keys MUST first be filtered to match this //# keyring's configuration. const decryptableEDKs = encryptedDataKeys.filter(filterEDKs(this)); const cmkErrors = []; //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8 //# For each encrypted data key in the filtered set, one at a time, the //# OnDecrypt MUST attempt to decrypt the data key. for (const edk of decryptableEDKs) { //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8 //# Otherwise it MUST //# be the provider info. let keyId = edk.providerInfo; //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8 //# * "KeyId": If the provider info's resource type is "key" and its //# resource is a multi-Region key then a new ARN MUST be created //# where the region part MUST equal the AWS KMS client region and //# every other part MUST equal the provider info. const keyArn = (0, arn_parsing_1.parseAwsKmsKeyArn)(edk.providerInfo); (0, material_management_1.needs)(keyArn, 'Unexpected EDK ProviderInfo for AWS KMS EDK'); if ((0, arn_parsing_1.isMultiRegionAwsKmsArn)(keyArn)) { keyId = (0, arn_parsing_1.constructArnInOtherRegion)(keyArn, clientRegion); } let dataKey = false; try { //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8 //# When calling AWS KMS Decrypt //# (https://docs.aws.amazon.com/kms/latest/APIReference/ //# API_Decrypt.html), the keyring MUST call with a request constructed //# as follows: dataKey = await (0, helpers_1.decrypt)( //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8 //# To attempt to decrypt a particular encrypted data key //# (structures.md#encrypted-data-key), OnDecrypt MUST call AWS KMS //# Decrypt (https://docs.aws.amazon.com/kms/latest/APIReference/ //# API_Decrypt.html) with the configured AWS KMS client. client, { providerId: edk.providerId, providerInfo: keyId, encryptedDataKey: edk.encryptedDataKey, }, material.encryptionContext, grantTokens); /* This should be impossible given that decrypt only returns false if the client supplier does * or if the providerId is not "aws-kms", which we have already filtered out */ if (!dataKey) continue; //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8 //# * The "KeyId" field in the response MUST equal the requested "KeyId" (0, material_management_1.needs)(dataKey.KeyId === keyId, 'KMS Decryption key does not match the requested key id.'); const flags = material_management_1.KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY | material_management_1.KeyringTraceFlag.WRAPPING_KEY_VERIFIED_ENC_CTX; const trace = { keyNamespace: helpers_1.KMS_PROVIDER_ID, keyName: dataKey.KeyId, flags, }; //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8 //# * The length of the response's "Plaintext" MUST equal the key //# derivation input length (algorithm-suites.md#key-derivation-input- //# length) specified by the algorithm suite (algorithm-suites.md) //# included in the input decryption materials //# (structures.md#decryption-materials). // //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8 //# Since the response does satisfies these requirements then OnDecrypt //# MUST do the following with the response: // // setUnencryptedDataKey will throw if the plaintext does not match the algorithm suite requirements. material.setUnencryptedDataKey(dataKey.Plaintext, trace); return material; } catch (e) { //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8 //# If the response does not satisfies these requirements then an error //# is collected and the next encrypted data key in the filtered set MUST //# be attempted. cmkErrors.push({ errPlus: e }); } } //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8 //# If OnDecrypt fails to successfully decrypt any encrypted data key //# (structures.md#encrypted-data-key), then it MUST yield an error that //# includes all collected errors. (0, material_management_1.needs)(material.hasValidKey(), [ `Unable to decrypt data key${!decryptableEDKs.length ? ': No EDKs supplied' : ''}.`, ...cmkErrors.map((e, i) => `Error #${i + 1} \n${e.errPlus.stack}`), ].join('\n')); return material; } } (0, material_management_1.immutableClass)(AwsKmsMrkAwareSymmetricDiscoveryKeyring); return AwsKmsMrkAwareSymmetricDiscoveryKeyring; } exports.AwsKmsMrkAwareSymmetricDiscoveryKeyringClass = AwsKmsMrkAwareSymmetricDiscoveryKeyringClass; function filterEDKs({ discoveryFilter, clientRegion, }) { return function filter({ providerId, providerInfo }) { //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8 //# * Its provider ID MUST exactly match the value "aws-kms". if (providerId !== helpers_1.KMS_PROVIDER_ID) return false; //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8 //# * The provider info MUST be a valid AWS KMS ARN (aws-kms-key- //# arn.md#a-valid-aws-kms-arn) with a resource type of "key" or //# OnDecrypt MUST fail. const edkArn = (0, arn_parsing_1.parseAwsKmsKeyArn)(providerInfo); (0, material_management_1.needs)(edkArn && edkArn.ResourceType === 'key', 'Unexpected EDK ProviderInfo for AWS KMS EDK'); const { AccountId: account, Partition: partition, Region: edkRegion, } = edkArn; //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8 //# * If the provider info is not identified as a multi-Region key (aws- //# kms-key-arn.md#identifying-an-aws-kms-multi-region-key), then the //# provider info's Region MUST match the AWS KMS client region. if (!(0, arn_parsing_1.isMultiRegionAwsKmsArn)(edkArn) && clientRegion !== edkRegion) { return false; } //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8 //# * If a discovery filter is configured, its partition and the //# provider info partition MUST match. // //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8 //# * If a discovery filter is configured, its set of accounts MUST //# contain the provider info account. return (!discoveryFilter || (discoveryFilter.partition === partition && discoveryFilter.accountIDs.includes(account))); }; } //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoia21zX21ya19kaXNjb3Zlcnlfa2V5cmluZy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9rbXNfbXJrX2Rpc2NvdmVyeV9rZXlyaW5nLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7QUFFdEMseUVBYXdDO0FBQ3hDLCtDQUlzQjtB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vQ0FBc0IsRUFBQyxNQUFNLENBQUMsSUFBSSxZQUFZLEtBQUssU0FBUyxFQUFFO1lBQ2pFLE9BQU8sS0FBSyxDQUFBO1NBQ2I7UUFFRCw2RkFBNkY7UUFDN0YsaUVBQWlFO1FBQ2pFLHVDQUF1QztRQUN2QyxFQUFFO1FBQ0YsNkZBQTZGO1FBQzdGLG9FQUFvRTtRQUNwRSxzQ0FBc0M7UUFDdEMsT0FBTyxDQUNMLENBQUMsZUFBZTtZQUNoQixDQUFDLGVBQWUsQ0FBQyxTQUFTLEtBQUssU0FBUztnQkFDdEMsZUFBZSxDQUFDLFVBQVUsQ0FBQyxRQUFRLENBQUMsT0FBTyxDQUFDLENBQUMsQ0FDaEQsQ0FBQTtJQUNILENBQUMsQ0FBQTtBQUNILENBQUMifQ== /***/ }), /***/ 88663: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getAwsKmsMrkAwareDiscoveryMultiKeyringBuilder = void 0; const material_management_1 = __nccwpck_require__(77519); function getAwsKmsMrkAwareDiscoveryMultiKeyringBuilder(MrkAwareDiscoveryKeyring, MultiKeyring, defaultClientProvider) { //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 //# The caller MUST provide: return function buildAwsKmsMrkAwareDiscoveryMultiKeyringNode({ regions, discoveryFilter, //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 //# If a regional client supplier is not passed, //# then a default MUST be created that takes a region string and //# generates a default AWS SDK client for the given region. clientProvider = defaultClientProvider, grantTokens, }) { //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 //# If an empty set of Region is provided this function MUST fail. (0, material_management_1.needs)(regions.length, 'Configured regions must contain at least one region.'); //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 //# If //# any element of the set of regions is null or an empty string this //# function MUST fail. (0, material_management_1.needs)(regions.every((region) => typeof region === 'string' && !!region), 'Configured regions must not contain a null or empty string as a region.'); const children = regions //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 //# A set of AWS KMS clients MUST be created by calling regional client //# supplier for each region in the input set of regions. .map(clientProvider) //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 //# Then a set of AWS KMS MRK Aware Symmetric Region Discovery Keyring //# (aws-kms-mrk-aware-symmetric-region-discovery-keyring.md) MUST be //# created for each AWS KMS client by initializing each keyring with .map((client) => { /* Postcondition: If the configured clientProvider is not able to create a client for a defined region, throw an error. */ (0, material_management_1.needs)(client, 'Configured clientProvider is unable to create a client for a configured region.'); return new MrkAwareDiscoveryKeyring({ client, discoveryFilter, grantTokens, }); }); //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 //# Then a Multi-Keyring (../multi-keyring.md#inputs) MUST be initialize //# by using this set of discovery keyrings as the child keyrings //# (../multi-keyring.md#child-keyrings). // //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 //# This Multi-Keyring MUST be //# this functions output. return new MultiKeyring({ children }); }; } exports.getAwsKmsMrkAwareDiscoveryMultiKeyringBuilder = getAwsKmsMrkAwareDiscoveryMultiKeyringBuilder; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoia21zX21ya19kaXNjb3ZlcnlfbXVsdGlfa2V5cmluZy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9rbXNfbXJrX2Rpc2NvdmVyeV9tdWx0aV9rZXlyaW5nLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7QUFFdEMseUVBS3dDO0FBdUJ4QyxTQUFnQiw2Q0FBNkMsQ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Q0FBQyxDQUFBO1FBQ0osQ0FBQyxDQUFDLENBQUE7UUFFTix5RUFBeUU7UUFDekUsd0VBQXdFO1FBQ3hFLGlFQUFpRTtRQUNqRSx5Q0FBeUM7UUFDekMsRUFBRTtRQUNGLHlFQUF5RTtRQUN6RSw4QkFBOEI7UUFDOUIsMEJBQTBCO1FBQzFCLE9BQU8sSUFBSSxZQUFZLENBQUMsRUFBRSxRQUFRLEVBQUUsQ0FBQyxDQUFBO0lBQ3ZDLENBQUMsQ0FBQTtBQUNILENBQUM7QUF2RUQsc0dBdUVDIn0= /***/ }), /***/ 36764: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AwsKmsMrkAwareSymmetricKeyringClass = void 0; const material_management_1 = __nccwpck_require__(77519); const helpers_1 = __nccwpck_require__(2309); const arn_parsing_1 = __nccwpck_require__(70798); function AwsKmsMrkAwareSymmetricKeyringClass(BaseKeyring) { class AwsKmsMrkAwareSymmetricKeyring //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.5 //# MUST implement the AWS Encryption SDK Keyring interface (../keyring- //# interface.md#interface) extends BaseKeyring { keyId; client; grantTokens; //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.6 //# On initialization the caller MUST provide: constructor({ client, keyId, grantTokens, }) { super(); //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.6 //# The AWS KMS key identifier MUST NOT be null or empty. (0, material_management_1.needs)(keyId && typeof keyId === 'string', 'An AWS KMS key identifier is required.'); //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.6 //# The AWS KMS //# key identifier MUST be a valid identifier (aws-kms-key-arn.md#a- //# valid-aws-kms-identifier). (0, material_management_1.needs)((0, arn_parsing_1.validAwsKmsIdentifier)(keyId), `Key id ${keyId} is not a valid identifier.`); //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.6 //# The AWS KMS //# SDK client MUST NOT be null. (0, material_management_1.needs)(!!client, 'An AWS SDK client is required'); (0, material_management_1.readOnlyProperty)(this, 'client', client); (0, material_management_1.readOnlyProperty)(this, 'keyId', keyId); (0, material_management_1.readOnlyProperty)(this, 'grantTokens', grantTokens); } //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7 //# OnEncrypt MUST take encryption materials (structures.md#encryption- //# materials) as input. async _onEncrypt(material) { const { client, keyId, grantTokens } = this; //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7 //# If the input encryption materials (structures.md#encryption- //# materials) do not contain a plaintext data key OnEncrypt MUST attempt //# to generate a new plaintext data key by calling AWS KMS //# GenerateDataKey (https://docs.aws.amazon.com/kms/latest/APIReference/ //# API_GenerateDataKey.html). if (!material.hasUnencryptedDataKey) { //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7 //# The keyring MUST call //# AWS KMS GenerateDataKeys with a request constructed as follows: // //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7 //# If the call to AWS KMS GenerateDataKey //# (https://docs.aws.amazon.com/kms/latest/APIReference/ //# API_GenerateDataKey.html) does not succeed, OnEncrypt MUST NOT modify //# the encryption materials (structures.md#encryption-materials) and //# MUST fail. const dataKey = await (0, helpers_1.generateDataKey)( //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7 //# If the keyring calls AWS KMS GenerateDataKeys, it MUST use the //# configured AWS KMS client to make the call. client, material.suite.keyLengthBytes, keyId, material.encryptionContext, grantTokens); /* This should be impossible given that generateDataKey only returns false if the client supplier does. */ (0, material_management_1.needs)(dataKey, 'Generator KMS key did not generate a data key'); //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7 //# The Generate Data Key response's "KeyId" MUST be A valid AWS //# KMS key ARN (aws-kms-key-arn.md#identifying-an-aws-kms-multi-region- //# key). (0, material_management_1.needs)((0, arn_parsing_1.parseAwsKmsKeyArn)(dataKey.KeyId), 'Malformed arn.'); const flags = material_management_1.KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY | material_management_1.KeyringTraceFlag.WRAPPING_KEY_SIGNED_ENC_CTX | material_management_1.KeyringTraceFlag.WRAPPING_KEY_ENCRYPTED_DATA_KEY; const trace = { keyNamespace: helpers_1.KMS_PROVIDER_ID, keyName: dataKey.KeyId, flags, }; //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7 //# If verified, //# OnEncrypt MUST do the following with the response from AWS KMS //# GenerateDataKey (https://docs.aws.amazon.com/kms/latest/APIReference/ //# API_GenerateDataKey.html): material //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7 //# If the Generate Data Key call succeeds, OnEncrypt MUST verify that //# the response "Plaintext" length matches the specification of the //# algorithm suite (algorithm-suites.md)'s Key Derivation Input Length //# field. // // setUnencryptedDataKey will throw if the plaintext does not match the algorithm suite requirements. .setUnencryptedDataKey(dataKey.Plaintext, trace) .addEncryptedDataKey((0, helpers_1.kmsResponseToEncryptedDataKey)(dataKey), material_management_1.KeyringTraceFlag.WRAPPING_KEY_ENCRYPTED_DATA_KEY | material_management_1.KeyringTraceFlag.WRAPPING_KEY_SIGNED_ENC_CTX); //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7 //# * OnEncrypt MUST output the modified encryption materials //# (structures.md#encryption-materials) return material; } else { //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7 //# Given a plaintext data key in the encryption materials //# (structures.md#encryption-materials), OnEncrypt MUST attempt to //# encrypt the plaintext data key using the configured AWS KMS key //# identifier. const unencryptedDataKey = (0, material_management_1.unwrapDataKey)(material.getUnencryptedDataKey()); const flags = material_management_1.KeyringTraceFlag.WRAPPING_KEY_ENCRYPTED_DATA_KEY | material_management_1.KeyringTraceFlag.WRAPPING_KEY_SIGNED_ENC_CTX; //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7 //# If the call to AWS KMS Encrypt //# (https://docs.aws.amazon.com/kms/latest/APIReference/ //# API_Encrypt.html) does not succeed, OnEncrypt MUST fail. // //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7 //# The keyring //# MUST AWS KMS Encrypt call with a request constructed as follows: const kmsEDK = await (0, helpers_1.encrypt)( //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7 //# The keyring MUST call AWS KMS Encrypt //# (https://docs.aws.amazon.com/kms/latest/APIReference/ //# API_Encrypt.html) using the configured AWS KMS client. client, unencryptedDataKey, keyId, material.encryptionContext, grantTokens); /* This should be impossible given that encrypt only returns false if the client supplier does. */ (0, material_management_1.needs)(kmsEDK, 'AwsKmsMrkAwareSymmetricKeyring failed to encrypt data key'); //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7 //# If the Encrypt call succeeds The response's "KeyId" MUST be A valid //# AWS KMS key ARN (aws-kms-key-arn.md#identifying-an-aws-kms-multi- //# region-key). (0, material_management_1.needs)((0, arn_parsing_1.parseAwsKmsKeyArn)(kmsEDK.KeyId), 'Malformed arn.'); //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7 //# If verified, OnEncrypt MUST do the following with the response from //# AWS KMS Encrypt (https://docs.aws.amazon.com/kms/latest/APIReference/ //# API_Encrypt.html): material.addEncryptedDataKey((0, helpers_1.kmsResponseToEncryptedDataKey)(kmsEDK), flags); //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7 //# If all Encrypt calls succeed, OnEncrypt MUST output the modified //# encryption materials (structures.md#encryption-materials). return material; } } //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8 //# OnDecrypt MUST take decryption materials (structures.md#decryption- //# materials) and a list of encrypted data keys //# (structures.md#encrypted-data-key) as input. async _onDecrypt(material, encryptedDataKeys) { //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8 //# If the decryption materials (structures.md#decryption-materials) //# already contained a valid plaintext data key OnDecrypt MUST //# immediately return the unmodified decryption materials //# (structures.md#decryption-materials). if (material.hasValidKey()) return material; const { client, keyId, grantTokens } = this; //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8 //# The set of encrypted data keys MUST first be filtered to match this //# keyring's configuration. const decryptableEDKs = encryptedDataKeys.filter(filterEDKs(keyId)); const cmkErrors = []; //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8 //# For each encrypted data key in the filtered set, one at a time, the //# OnDecrypt MUST attempt to decrypt the data key. for (const edk of decryptableEDKs) { const { providerId, encryptedDataKey } = edk; try { //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8 //# When calling AWS KMS Decrypt //# (https://docs.aws.amazon.com/kms/latest/APIReference/ //# API_Decrypt.html), the keyring MUST call with a request constructed //# as follows: const dataKey = await (0, helpers_1.decrypt)( //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8 //# To attempt to decrypt a particular encrypted data key //# (structures.md#encrypted-data-key), OnDecrypt MUST call AWS KMS //# Decrypt (https://docs.aws.amazon.com/kms/latest/APIReference/ //# API_Decrypt.html) with the configured AWS KMS client. client, // For MRKs the key identifier MUST be the configured key identifer. { providerId, encryptedDataKey, providerInfo: this.keyId }, material.encryptionContext, grantTokens); /* This should be impossible given that decrypt only returns false if the client supplier does * or if the providerId is not "aws-kms", which we have already filtered out */ (0, material_management_1.needs)(dataKey, 'decrypt did not return a data key.'); //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8 //# * The "KeyId" field in the response MUST equal the configured AWS //# KMS key identifier. (0, material_management_1.needs)(dataKey.KeyId === this.keyId, 'KMS Decryption key does not match the requested key id.'); const flags = material_management_1.KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY | material_management_1.KeyringTraceFlag.WRAPPING_KEY_VERIFIED_ENC_CTX; const trace = { keyNamespace: helpers_1.KMS_PROVIDER_ID, keyName: dataKey.KeyId, flags, }; //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8 //# If the response does satisfies these requirements then OnDecrypt MUST //# do the following with the response: // //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8 //# * The length of the response's "Plaintext" MUST equal the key //# derivation input length (algorithm-suites.md#key-derivation-input- //# length) specified by the algorithm suite (algorithm-suites.md) //# included in the input decryption materials //# (structures.md#decryption-materials). // // setUnencryptedDataKey will throw if the plaintext does not match the algorithm suite requirements. material.setUnencryptedDataKey(dataKey.Plaintext, trace); return material; } catch (e) { //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8 //# If this attempt //# results in an error, then these errors MUST be collected. // //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8 //# If the response does not satisfies these requirements then an error //# MUST be collected and the next encrypted data key in the filtered set //# MUST be attempted. cmkErrors.push({ errPlus: e }); } } //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8 //# If OnDecrypt fails to successfully decrypt any encrypted data key //# (structures.md#encrypted-data-key), then it MUST yield an error that //# includes all the collected errors. (0, material_management_1.needs)(material.hasValidKey(), [ `Unable to decrypt data key${!decryptableEDKs.length ? ': No EDKs supplied' : ''}.`, ...cmkErrors.map((e, i) => `Error #${i + 1} \n${e.errPlus.stack}`), ].join('\n')); return material; } } (0, material_management_1.immutableClass)(AwsKmsMrkAwareSymmetricKeyring); return AwsKmsMrkAwareSymmetricKeyring; } exports.AwsKmsMrkAwareSymmetricKeyringClass = AwsKmsMrkAwareSymmetricKeyringClass; function filterEDKs(keyringKeyId) { return function filter({ providerId, providerInfo }) { //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8 //# * Its provider ID MUST exactly match the value "aws-kms". if (providerId !== helpers_1.KMS_PROVIDER_ID) return false; //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8 //# * The provider info MUST be a valid AWS KMS ARN (aws-kms-key- //# arn.md#a-valid-aws-kms-arn) with a resource type of "key" or //# OnDecrypt MUST fail. const arnInfo = (0, arn_parsing_1.parseAwsKmsKeyArn)(providerInfo); (0, material_management_1.needs)(arnInfo && arnInfo.ResourceType === 'key', 'Unexpected EDK ProviderInfo for AWS KMS EDK'); //= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8 //# * The the function AWS KMS MRK Match for Decrypt (aws-kms-mrk-match- //# for-decrypt.md#implementation) called with the configured AWS KMS //# key identifier and the provider info MUST return "true". return (0, arn_parsing_1.mrkAwareAwsKmsKeyIdCompare)(keyringKeyId, providerInfo); }; } //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoia21zX21ya19rZXlyaW5nLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL2ttc19tcmtfa2V5cmluZy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUEsb0VBQW9FO0FBQ3BFLHNDQUFzQzs7O0FBR3RDLHlFQWN3QztBQUN4Qyx1Q0FNa0I7QUFDbEIsK0NBSXNCO0FBaUN0QixTQUFnQixtQ0FBbUMsQ0FJakQsV0FBZ0M7SUFFaEMsTUFBTSw4QkFBOEI7SUFDbEMsNEVBQTRFO0lBQzVFLHdFQUF3RTtJQUN4RSwyQkFBMkI7SUFDM0IsU0FBUSxXQUFXO1FBR1osS0FBSyxDQUFTO1FBQ2QsTUFBTSxDQUFTO1FBQ2YsV0FBVyxDQUFXO1FBRTdCLDRFQUE0RTtRQUM1RSw4Q0FBOEM7UU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0gsQ0FBQyJ9 /***/ }), /***/ 24603: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.identifier2ClientBuilder = exports.getAwsKmsMrkAwareStrictMultiKeyringBuilder = void 0; const material_management_1 = __nccwpck_require__(77519); const arn_parsing_1 = __nccwpck_require__(70798); const aws_kms_mrk_are_unique_1 = __nccwpck_require__(47633); function getAwsKmsMrkAwareStrictMultiKeyringBuilder(MrkAwareKeyring, MultiKeyring, defaultClientProvider) { //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 //# The caller MUST provide: return function buildAwsKmsMrkAwareStrictMultiKeyring({ generatorKeyId, keyIds = [], //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 //# If //# a regional client supplier is not passed, then a default MUST be //# created that takes a region string and generates a default AWS SDK //# client for the given region. clientProvider = defaultClientProvider, grantTokens, } = {}) { const identifier2Client = identifier2ClientBuilder(clientProvider); const allIdentifiers = generatorKeyId ? [generatorKeyId, ...keyIds] : keyIds; //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 //# At least one non-null or non-empty string AWS //# KMS key identifiers exists in the input this function MUST fail. // //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 //# If any of the AWS KMS key identifiers is null or an empty string this //# function MUST fail. (0, material_management_1.needs)(allIdentifiers.length && allIdentifiers.every((key) => typeof key === 'string' && key !== ''), 'Noop keyring is not allowed: Set a generatorKeyId or at least one keyId.'); //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 //# All //# AWS KMS identifiers are passed to Assert AWS KMS MRK are unique (aws- //# kms-mrk-are-unique.md#Implementation) and the function MUST return //# success otherwise this MUST fail. (0, aws_kms_mrk_are_unique_1.awsKmsMrkAreUnique)(allIdentifiers); //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 //# If there is a generator input then the generator keyring MUST be a //# AWS KMS MRK Aware Symmetric Keyring (aws-kms-mrk-aware-symmetric- //# keyring.md) initialized with const generator = generatorKeyId ? new MrkAwareKeyring({ //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 //# * The AWS KMS client that MUST be created by the regional client //# supplier when called with the region part of the generator ARN or //# a signal for the AWS SDK to select the default region. client: identifier2Client(generatorKeyId), keyId: generatorKeyId, grantTokens, }) : undefined; //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 //# If there is a set of child identifiers then a set of AWS KMS MRK //# Aware Symmetric Keyring (aws-kms-mrk-aware-symmetric-keyring.md) MUST //# be created for each AWS KMS key identifier by initialized each //# keyring with const children = keyIds.map((keyId) => { return new MrkAwareKeyring({ //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 //# * The AWS KMS client that MUST be created by the regional client //# supplier when called with the region part of the AWS KMS key //# identifier or a signal for the AWS SDK to select the default //# region. client: identifier2Client(keyId), keyId, grantTokens, }); }); //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 //# Then a Multi-Keyring (../multi-keyring.md#inputs) MUST be initialize //# by using this generator keyring as the generator keyring (../multi- //# keyring.md#generator-keyring) and this set of child keyrings as the //# child keyrings (../multi-keyring.md#child-keyrings). // //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 //# This Multi- //# Keyring MUST be this functions output. return new MultiKeyring({ generator, children, }); }; } exports.getAwsKmsMrkAwareStrictMultiKeyringBuilder = getAwsKmsMrkAwareStrictMultiKeyringBuilder; function identifier2ClientBuilder(clientProvider) { return function identifier2Client(identifier) { //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 //# NOTE: The AWS Encryption SDK SHOULD NOT attempt to evaluate its own //# default region. const region = (0, arn_parsing_1.getRegionFromIdentifier)(identifier); const client = clientProvider(region); /* Postcondition: If the configured clientProvider is not able to create a client for a defined generator key, throw an error. */ (0, material_management_1.needs)(client, `Configured clientProvider is unable to create a client for configured ${identifier}.`); return client; }; } exports.identifier2ClientBuilder = identifier2ClientBuilder; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoia21zX21ya19zdHJpY3RfbXVsdGlfa2V5cmluZy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9rbXNfbXJrX3N0cmljdF9tdWx0aV9rZXlyaW5nLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7QUFFdEMseUVBS3dDO0FBR3hDLCtDQUF1RDtBQUN2RCxxRUFBNkQ7QUFrQjdELFNBQWdCLDBDQUEwQyxDQUl4RCxlQUFvRSxFQUNwRSxZQUFzQyxFQUN0QyxxQkFBZ0Q7SUFFaEQseUVBQXlFO0lBQ3pFLDRCQUE0QjtJQUM1QixPQUFPLFNBQVMscUNBQXFDLENBQUMsRUFDcEQsY0FBYyxFQUNkLE1BQU0sR0FBRyxFQUFFO0lBQ1gseUVBQXlFO0lBQ3pFLE1BQU07SUFDTixvRUFBb0U7SUFDcEUsc0VBQXNFO0lBQ3RFLGdDQUFnQztJQUNoQyxjQUFjLEdBQUcscUJBQXFCLEVBQ3RDLFdBQVcsTUFDc0MsRUFBRTtRQUNuRCxNQUFNLGlCQUFpQixHQUFHLHdCQUF3QixDQUFDLGNBQWMsQ0FBQyxDQUFBO1FBRWxFLE1BQU0sY0FBYyxHQUFHLGNBQWMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxjQUFjLEVBQUUsR0FBRyxNQUFNLENBQUMsQ0FBQyxDQUFDLENBQUMsTUFBTSxDQUFBO1FBRTVFLHlFQUF5RTtRQUN6RSxpREFBaUQ7UUFDakQsb0VBQW9FO1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sZ0VBQWdFO2dCQUNoRSxXQUFXO2dCQUNYLE1BQU0sRUFBRSxpQkFBaUIsQ0FBQyxLQUFLLENBQUM7Z0JBQ2hDLEtBQUs7Z0JBQ0wsV0FBVzthQUNaLENBQUMsQ0FBQTtRQUNKLENBQUMsQ0FDRixDQUFBO1FBRUQseUVBQXlFO1FBQ3pFLHdFQUF3RTtRQUN4RSx1RUFBdUU7UUFDdkUsdUVBQXVFO1FBQ3ZFLHdEQUF3RDtRQUN4RCxFQUFFO1FBQ0YseUVBQXlFO1FBQ3pFLGVBQWU7UUFDZiwwQ0FBMEM7UUFDMUMsT0FBTyxJQUFJLFlBQVksQ0FBQztZQUN0QixTQUFTO1lBQ1QsUUFBUTtTQUNULENBQUMsQ0FBQTtJQUNKLENBQUMsQ0FBQTtBQUNILENBQUM7QUEvRkQsZ0dBK0ZDO0FBRUQsU0FBZ0Isd0JBQXdCLENBQ3RDLGNBQXlDO0lBRXpDLE9BQU8sU0FBUyxpQkFBaUIsQ0FBQyxVQUFrQjtRQUNsRCx5RUFBeUU7UUFDekUsdUVBQXVFO1FBQ3ZFLG1CQUFtQjtRQUNuQixNQUFNLE1BQU0sR0FBRyxJQUFBLHFDQUF1QixFQUFDLFVBQVUsQ0FBQyxDQUFBO1FBQ2xELE1BQU0sTUFBTSxHQUFHLGNBQWMsQ0FBQyxNQUFNLENBQUMsQ0FBQTtRQUNyQyxpSUFBaUk7UUFDakksSUFBQSwyQkFBSyxFQUNILE1BQU0sRUFDTix5RUFBeUUsVUFBVSxHQUFHLENBQ3ZGLENBQUE7UUFDRCxPQUFPLE1BQU0sQ0FBQTtJQUNmLENBQUMsQ0FBQTtBQUNILENBQUM7QUFoQkQsNERBZ0JDIn0= /***/ }), /***/ 97571: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.decomposeAwsKmsKeyArn = exports.regionFromKmsKeyArn = void 0; const material_management_1 = __nccwpck_require__(77519); /* See: https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-kms * regex to match: 'resourceType/resourceId' || 'resourceType' * This is complicated because the `split(':')`. * The valid resourceType resourceId delimiters are `/`, `:`. * This means if the delimiter is a `:` it will be split out, * when splitting the whole arn. */ const aliasOrKeyResourceType = /^(alias|key)(\/.*)*$/; /* Maintaining function for backwards compatibility. */ /** * @deprecated Because decomposeAwsKmsKeyArn is incorrect, * use parseAwsKmsIdentifier or parseAwsKmsKeyArn. */ function regionFromKmsKeyArn(kmsKeyArn) { const { region } = decomposeAwsKmsKeyArn(kmsKeyArn); return region; } exports.regionFromKmsKeyArn = regionFromKmsKeyArn; /** * @deprecated This function incorrectly requires `key/12345678-1234-1234-1234-123456789012` * AWS KMS requires that a raw key id be `12345678-1234-1234-1234-123456789012` */ function decomposeAwsKmsKeyArn(kmsKeyArn) { /* Precondition: A KMS key arn must be a string. */ (0, material_management_1.needs)(typeof kmsKeyArn === 'string', 'KMS key arn must be a string.'); /* See: https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-kms * arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012 * arn:aws:kms:us-east-1:123456789012:alias/example-alias */ const [arnLiteral, partition, service, region = '', account = ''] = kmsKeyArn.split(':'); /* Postcondition: The ARN must be well formed. * The arn and kms section have defined values, * but the aws section does not. * It is also possible to have a key or alias. * In this case the partition, service, region * will be empty. * In this case the arnLiteral should look like an alias. */ (0, material_management_1.needs)((arnLiteral === 'arn' && partition && service === 'kms' && region) || /* Partition may or may not have a value. * If the resourceType delimiter is /, * it will not have a value. * However if the delimiter is : it will * because of the split(':') */ (!service && !region && arnLiteral.match(aliasOrKeyResourceType)), 'Malformed arn.'); return { partition, region, account }; } exports.decomposeAwsKmsKeyArn = decomposeAwsKmsKeyArn; //# sourceMappingURL=data:application/json;base64,eyJ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BSSxDQUFDLE1BQU0sSUFBSSxVQUFVLENBQUMsS0FBSyxDQUFDLHNCQUFzQixDQUFDLENBQUMsRUFDbkUsZ0JBQWdCLENBQ2pCLENBQUE7SUFFRCxPQUFPLEVBQUUsU0FBUyxFQUFFLE1BQU0sRUFBRSxPQUFPLEVBQUUsQ0FBQTtBQUN2QyxDQUFDO0FBcENELHNEQW9DQyJ9 /***/ }), /***/ 12563: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 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.MessageFormat = exports.SignaturePolicy = exports.SignaturePolicySuites = exports.CommitmentPolicySuites = exports.CommitmentPolicy = exports.unwrapDataKey = exports.readOnlyProperty = exports.frozenClass = exports.immutableClass = exports.immutableBaseClass = exports.MultiKeyringNode = exports.KeyringNode = exports.NotSupported = exports.needs = exports.KeyringTraceFlag = exports.EncryptedDataKey = exports.AlgorithmSuiteIdentifier = exports.NodeAlgorithmSuite = exports.NodeEncryptionMaterial = exports.NodeDecryptionMaterial = exports.getDecryptionHelper = exports.getEncryptHelper = void 0; __exportStar(__nccwpck_require__(28197), exports); var material_helpers_1 = __nccwpck_require__(81398); Object.defineProperty(exports, "getEncryptHelper", ({ enumerable: true, get: function () { return material_helpers_1.getEncryptHelper; } })); Object.defineProperty(exports, "getDecryptionHelper", ({ enumerable: true, get: function () { return material_helpers_1.getDecryptionHelper; } })); var material_management_1 = __nccwpck_require__(77519); Object.defineProperty(exports, "NodeDecryptionMaterial", ({ enumerable: true, get: function () { return material_management_1.NodeDecryptionMaterial; } })); Object.defineProperty(exports, "NodeEncryptionMaterial", ({ enumerable: true, get: function () { return material_management_1.NodeEncryptionMaterial; } })); Object.defineProperty(exports, "NodeAlgorithmSuite", ({ enumerable: true, get: function () { return material_management_1.NodeAlgorithmSuite; } })); Object.defineProperty(exports, "AlgorithmSuiteIdentifier", ({ enumerable: true, get: function () { return material_management_1.AlgorithmSuiteIdentifier; } })); Object.defineProperty(exports, "EncryptedDataKey", ({ enumerable: true, get: function () { return material_management_1.EncryptedDataKey; } })); Object.defineProperty(exports, "KeyringTraceFlag", ({ enumerable: true, get: function () { return material_management_1.KeyringTraceFlag; } })); Object.defineProperty(exports, "needs", ({ enumerable: true, get: function () { return material_management_1.needs; } })); Object.defineProperty(exports, "NotSupported", ({ enumerable: true, get: function () { return material_management_1.NotSupported; } })); Object.defineProperty(exports, "KeyringNode", ({ enumerable: true, get: function () { return material_management_1.KeyringNode; } })); Object.defineProperty(exports, "MultiKeyringNode", ({ enumerable: true, get: function () { return material_management_1.MultiKeyringNode; } })); Object.defineProperty(exports, "immutableBaseClass", ({ enumerable: true, get: function () { return material_management_1.immutableBaseClass; } })); Object.defineProperty(exports, "immutableClass", ({ enumerable: true, get: function () { return material_management_1.immutableClass; } })); Object.defineProperty(exports, "frozenClass", ({ enumerable: true, get: function () { return material_management_1.frozenClass; } })); Object.defineProperty(exports, "readOnlyProperty", ({ enumerable: true, get: function () { return material_management_1.readOnlyProperty; } })); Object.defineProperty(exports, "unwrapDataKey", ({ enumerable: true, get: function () { return material_management_1.unwrapDataKey; } })); Object.defineProperty(exports, "CommitmentPolicy", ({ enumerable: true, get: function () { return material_management_1.CommitmentPolicy; } })); Object.defineProperty(exports, "CommitmentPolicySuites", ({ enumerable: true, get: function () { return material_management_1.CommitmentPolicySuites; } })); Object.defineProperty(exports, "SignaturePolicySuites", ({ enumerable: true, get: function () { return material_management_1.SignaturePolicySuites; } })); Object.defineProperty(exports, "SignaturePolicy", ({ enumerable: true, get: function () { return material_management_1.SignaturePolicy; } })); Object.defineProperty(exports, "MessageFormat", ({ enumerable: true, get: function () { return material_management_1.MessageFormat; } })); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7Ozs7Ozs7Ozs7Ozs7Ozs7O0FBRXRDLHlFQUFzRDtBQUN0RCx1REFTMkI7QUFSekIsb0hBQUEsZ0JBQWdCLE9BQUE7QUFDaEIsdUhBQUEsbUJBQW1CLE9BQUE7QUFRckIsdUVBMkJ3QztBQTFCdEMsNkhBQUEsc0JBQXNCLE9BQUE7QUFDdEIsNkhBQUEsc0JBQXNCLE9BQUE7QUFDdEIseUhBQUEsa0JBQWtCLE9BQUE7QUFDbEIsK0hBQUEsd0JBQXdCLE9BQUE7QUFFeEIsdUhBQUEsZ0JBQWdCLE9BQUE7QUFFaEIsdUhBQUEsZ0JBQWdCLE9BQUE7QUFDaEIsNEdBQUEsS0FBSyxPQUFBO0FBQ0wsbUhBQUEsWUFBWSxPQUFBO0FBQ1osa0hBQUEsV0FBVyxPQUFBO0FBQ1gsdUhBQUEsZ0JBQWdCLE9BQUE7QUFDaEIseUhBQUEsa0JBQWtCLE9BQUE7QUFDbEIscUhBQUEsY0FBYyxPQUFBO0FBQ2Qsa0hBQUEsV0FBVyxPQUFBO0FBQ1gsdUhBQUEsZ0JBQWdCLE9BQUE7QUFFaEIsb0hBQUEsYUFBYSxPQUFBO0FBRWIsdUhBQUEsZ0JBQWdCLE9BQUE7QUFDaEIsNkhBQUEsc0JBQXNCLE9BQUE7QUFDdEIsNEhBQUEscUJBQXFCLE9BQUE7QUFDckIsc0hBQUEsZUFBZSxPQUFBO0FBQ2Ysb0hBQUEsYUFBYSxPQUFBIn0= /***/ }), /***/ 81398: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.nodeKdf = exports.curryCryptoStream = exports.getDecryptionHelper = exports.getEncryptHelper = void 0; const material_management_1 = __nccwpck_require__(77519); const crypto_1 = __nccwpck_require__(6113); const hkdf_node_1 = __nccwpck_require__(52809); const serialize_1 = __nccwpck_require__(26683); const kdfIndex = Object.freeze({ sha256: (0, hkdf_node_1.HKDF)('sha256'), sha384: (0, hkdf_node_1.HKDF)('sha384'), sha512: (0, hkdf_node_1.HKDF)('sha512'), }); const getEncryptHelper = (material) => { /* Precondition: NodeEncryptionMaterial must have a valid data key. */ (0, material_management_1.needs)(material.hasValidKey(), 'Material has no unencrypted data key.'); const { signatureHash } = material.suite; /* Conditional types can not narrow the return type :( * Function overloads "works" but then I can not export * the function and have eslint be happy (Multiple exports of name) */ const getCipherInfo = curryCryptoStream(material, crypto_1.createCipheriv); return Object.freeze({ getCipherInfo, getSigner: signatureHash ? getSigner : undefined, dispose, }); function getSigner() { /* Precondition: The NodeEncryptionMaterial must have not been zeroed. * hasUnencryptedDataKey will check that the unencrypted data key has been set * *and* that it has not been zeroed. At this point it must have been set * because the KDF function operated on it. So at this point * we are protecting that someone has zeroed out the material * because the Encrypt process has been complete. */ (0, material_management_1.needs)(material.hasUnencryptedDataKey, 'Unencrypted data key has been zeroed.'); if (!signatureHash) throw new Error('Material does not support signature.'); const { signatureKey } = material; if (!signatureKey) throw new Error('Material does not support signature.'); const { privateKey } = signatureKey; if (typeof privateKey !== 'string') throw new Error('Material does not support signature.'); const signer = Object.assign((0, crypto_1.createSign)(signatureHash), // don't export the private key if we don't have to { awsCryptoSign: () => signer.sign(privateKey) }); return signer; } function dispose() { material.zeroUnencryptedDataKey(); } }; exports.getEncryptHelper = getEncryptHelper; const getDecryptionHelper = (material) => { /* Precondition: NodeDecryptionMaterial must have a valid data key. */ (0, material_management_1.needs)(material.hasValidKey(), 'Material has no unencrypted data key.'); const { signatureHash } = material.suite; /* Conditional types can not narrow the return type :( * Function overloads "works" but then I can not export * the function and have eslint be happy (Multiple exports of name) */ const getDecipherInfo = curryCryptoStream(material, crypto_1.createDecipheriv); return Object.freeze({ getDecipherInfo, getVerify: signatureHash ? getVerify : undefined, dispose, }); function getVerify() { if (!signatureHash) throw new Error('Material does not support signature.'); const { verificationKey } = material; if (!verificationKey) throw new Error('Material does not support signature.'); const verify = Object.assign((0, crypto_1.createVerify)(signatureHash), // explicitly bind the public key for this material { awsCryptoVerify: (signature) => // As typescript gets better typing // We should consider either generics or // 2 different verificationKeys for Node and WebCrypto verify.verify(verificationKey.publicKey, signature), }); return verify; } function dispose() { material.zeroUnencryptedDataKey(); } }; exports.getDecryptionHelper = getDecryptionHelper; function curryCryptoStream(material, createCryptoIvStream) { const { encryption: cipherName, ivLength } = material.suite; const isEncrypt = material instanceof material_management_1.NodeEncryptionMaterial; /* Precondition: material must be either NodeEncryptionMaterial or NodeDecryptionMaterial. * */ (0, material_management_1.needs)(isEncrypt ? crypto_1.createCipheriv === createCryptoIvStream : material instanceof material_management_1.NodeDecryptionMaterial ? crypto_1.createDecipheriv === createCryptoIvStream : false, 'Unsupported cryptographic material.'); return (messageId, commitKey) => { const { derivedKey, keyCommitment } = nodeKdf(material, messageId, commitKey); return (isEncrypt ? { getCipher: createCryptoStream, keyCommitment } : createCryptoStream); function createCryptoStream(iv) { /* Precondition: The length of the IV must match the NodeAlgorithmSuite specification. */ (0, material_management_1.needs)(iv.byteLength === ivLength, 'Iv length does not match algorithm suite specification'); /* Precondition: The material must have not been zeroed. * hasUnencryptedDataKey will check that the unencrypted data key has been set * *and* that it has not been zeroed. At this point it must have been set * because the KDF function operated on it. So at this point * we are protecting that someone has zeroed out the material * because the Encrypt process has been complete. */ (0, material_management_1.needs)(material.hasUnencryptedDataKey, 'Unencrypted data key has been zeroed.'); /* createDecipheriv is incorrectly typed in @types/node. It should take key: CipherKey, not key: BinaryLike. * Also, the check above ensures * that _createCryptoStream is not false. * But TypeScript does not believe me. * For any complicated code, * you should defer to the checker, * but here I'm going to assert * it is simple enough. */ return createCryptoIvStream(cipherName, derivedKey, iv); } }; } exports.curryCryptoStream = curryCryptoStream; function nodeKdf(material, nonce, commitKey) { const dataKey = material.getUnencryptedDataKey(); const { kdf, kdfHash, keyLengthBytes, commitmentLength, saltLengthBytes, commitment, id: suiteId, } = material.suite; /* Check for early return (Postcondition): No Node.js KDF, just return the unencrypted data key. */ if (!kdf && !kdfHash) { /* Postcondition: Non-KDF algorithm suites *must* not have a commitment. */ (0, material_management_1.needs)(!commitKey, 'Commitment not supported.'); return { derivedKey: dataKey }; } /* Precondition: Valid HKDF values must exist for Node.js. */ (0, material_management_1.needs)(kdf === 'HKDF' && kdfHash && kdfIndex[kdfHash] && nonce instanceof Uint8Array, 'Invalid HKDF values.'); /* The unwrap is done once we *know* that a KDF is required. * If we unwrapped before everything will work, * but we may be creating new copies of the unencrypted data key (export). */ const { buffer: dkBuffer, byteOffset: dkByteOffset, byteLength: dkByteLength, } = (0, material_management_1.unwrapDataKey)(dataKey); if (commitment === 'NONE') { /* Postcondition: Non-committing Node algorithm suites *must* not have a commitment. */ (0, material_management_1.needs)(!commitKey, 'Commitment not supported.'); const toExtract = Buffer.from(dkBuffer, dkByteOffset, dkByteLength); const { buffer, byteOffset, byteLength } = (0, serialize_1.kdfInfo)(suiteId, nonce); const infoBuff = Buffer.from(buffer, byteOffset, byteLength); const derivedBytes = kdfIndex[kdfHash](toExtract)(keyLengthBytes, infoBuff); const derivedKey = (0, material_management_1.wrapWithKeyObjectIfSupported)(derivedBytes); return { derivedKey }; } /* Precondition UNTESTED: Committing suites must define expected values. */ (0, material_management_1.needs)(commitment === 'KEY' && commitmentLength && saltLengthBytes, 'Malformed suite data.'); /* Precondition: For committing algorithms, the nonce *must* be 256 bit. * i.e. It must target a V2 message format. */ (0, material_management_1.needs)(nonce.byteLength === saltLengthBytes, 'Nonce is not the correct length for committed algorithm suite.'); const toExtract = Buffer.from(dkBuffer, dkByteOffset, dkByteLength); const expand = kdfIndex[kdfHash](toExtract, nonce); const { keyLabel, commitLabel } = (0, serialize_1.kdfCommitKeyInfo)(material.suite); const keyCommitment = expand(commitmentLength / 8, commitLabel); const isDecrypt = material instanceof material_management_1.NodeDecryptionMaterial; /* Precondition: If material is NodeDecryptionMaterial the key commitments *must* match. * This is also the preferred location to check, * because then the decryption key is never even derived. */ (0, material_management_1.needs)((isDecrypt && commitKey && (0, crypto_1.timingSafeEqual)(keyCommitment, commitKey)) || (!isDecrypt && !commitKey), isDecrypt ? 'Commitment does not match.' : 'Invalid arguments.'); const derivedBytes = expand(keyLengthBytes, keyLabel); const derivedKey = (0, material_management_1.wrapWithKeyObjectIfSupported)(derivedBytes); return { derivedKey, keyCommitment }; } exports.nodeKdf = nodeKdf; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWF0ZXJpYWxfaGVscGVycy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9tYXRlcmlhbF9oZWxwZXJzLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7QUFFdEMseUVBUXdDO0FBQ3hDLG1DQU1lO0FBQ2YscURBQTRDO0FBQzVDLHFEQUFpRTtBQWtCakUsTUFBTSxRQUFRLEdBQWEsTUFBTSxDQUFDLE1BQU0sQ0FBQztJQUN2QyxNQUFNLEVBQUUsSUFBQSxnQkFBSSxFQUFDLFFBQW9CLENBQUM7SUFDbEMsTUFBTSxFQUFFLElBQUEsZ0JBQUksRUFBQyx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UFBSSxJQUFBLHdCQUFlLEVBQUMsYUFBYSxFQUFFLFNBQVMsQ0FBQyxDQUFDO1FBQ25FLENBQUMsQ0FBQyxTQUFTLElBQUksQ0FBQyxTQUFTLENBQUMsRUFDNUIsU0FBUyxDQUFDLENBQUMsQ0FBQyw0QkFBNEIsQ0FBQyxDQUFDLENBQUMsb0JBQW9CLENBQ2hFLENBQUE7SUFFRCxNQUFNLFlBQVksR0FBRyxNQUFNLENBQUMsY0FBYyxFQUFFLFFBQVEsQ0FBQyxDQUFBO0lBQ3JELE1BQU0sVUFBVSxHQUFHLElBQUEsa0RBQTRCLEVBQUMsWUFBWSxDQUFDLENBQUE7SUFDN0QsT0FBTyxFQUFFLFVBQVUsRUFBRSxhQUFhLEVBQUUsQ0FBQTtBQUN0QyxDQUFDO0FBL0ZELDBCQStGQyJ9 /***/ }), /***/ 28197: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NodeDefaultCryptographicMaterialsManager = void 0; const material_management_1 = __nccwpck_require__(77519); const serialize_1 = __nccwpck_require__(26683); const crypto_1 = __nccwpck_require__(6113); /** * The NodeDefaultCryptographicMaterialsManager is a specific implementation of the CryptographicMaterialsManager. * New cryptography materials managers SHOULD extend from NodeMaterialsManager. * Users should never need to create an instance of a NodeDefaultCryptographicMaterialsManager. */ class NodeDefaultCryptographicMaterialsManager { constructor(keyring) { /* Precondition: keyrings must be a KeyringNode. */ (0, material_management_1.needs)(keyring instanceof material_management_1.KeyringNode, 'Unsupported type.'); (0, material_management_1.readOnlyProperty)(this, 'keyring', keyring); } async getEncryptionMaterials({ suite, encryptionContext, commitmentPolicy, }) { suite = suite || new material_management_1.NodeAlgorithmSuite(material_management_1.CommitmentPolicySuites[commitmentPolicy].defaultAlgorithmSuite); /* Precondition: NodeDefaultCryptographicMaterialsManager must reserve the ENCODED_SIGNER_KEY constant from @aws-crypto/serialize. * A CryptographicMaterialsManager can change entries to the encryptionContext * but changing these values has consequences. * The DefaultCryptographicMaterialsManager uses the value in the encryption context to store public signing key. * If the caller is using this value in their encryption context the Default CMM is probably not the CMM they want to use. */ (0, material_management_1.needs)(!Object.prototype.hasOwnProperty.call(encryptionContext, serialize_1.ENCODED_SIGNER_KEY), `Reserved encryptionContext value ${serialize_1.ENCODED_SIGNER_KEY} not allowed.`); const material = await this.keyring.onEncrypt(this._initializeEncryptionMaterial(suite, encryptionContext)); /* Postcondition: The NodeEncryptionMaterial must contain a valid dataKey. * This verifies that the data key matches the algorithm suite specification * and that the unencrypted data key is non-NULL. * See: cryptographic_materials.ts, `getUnencryptedDataKey` */ (0, material_management_1.needs)(material.getUnencryptedDataKey(), 'Unencrypted data key is invalid.'); /* Postcondition: The NodeEncryptionMaterial must contain at least 1 EncryptedDataKey. */ (0, material_management_1.needs)(material.encryptedDataKeys.length, 'No EncryptedDataKeys: the ciphertext can never be decrypted.'); return material; } async decryptMaterials({ suite, encryptedDataKeys, encryptionContext, }) { const material = await this.keyring.onDecrypt(this._initializeDecryptionMaterial(suite, encryptionContext), encryptedDataKeys.slice()); /* Postcondition: The NodeDecryptionMaterial must contain a valid dataKey. * See: cryptographic_materials.ts, `getUnencryptedDataKey` also verifies * that the unencrypted data key has not been manipulated, * that the data key matches the algorithm suite specification * and that the unencrypted data key is non-NULL. */ (0, material_management_1.needs)(material.getUnencryptedDataKey(), 'Unencrypted data key is invalid.'); return material; } _initializeEncryptionMaterial(suite, encryptionContext) { const { signatureCurve: namedCurve } = suite; /* Check for early return (Postcondition): The algorithm suite specification must support a signatureCurve to generate a ECDH key. */ if (!namedCurve) return new material_management_1.NodeEncryptionMaterial(suite, encryptionContext); const ecdh = (0, crypto_1.createECDH)(namedCurve); ecdh.generateKeys(); // @ts-ignore I want a compressed buffer. const compressPoint = ecdh.getPublicKey(undefined, 'compressed'); const privateKey = ecdh.getPrivateKey(); const signatureKey = new material_management_1.SignatureKey(privateKey, new Uint8Array(compressPoint), suite); return new material_management_1.NodeEncryptionMaterial(suite, { ...encryptionContext, [serialize_1.ENCODED_SIGNER_KEY]: compressPoint.toString('base64'), }).setSignatureKey(signatureKey); } _initializeDecryptionMaterial(suite, encryptionContext) { const { signatureCurve: namedCurve } = suite; if (!namedCurve) { /* Precondition: NodeDefaultCryptographicMaterialsManager The context must not contain a public key for a non-signing algorithm suite. */ (0, material_management_1.needs)(!Object.prototype.hasOwnProperty.call(encryptionContext, serialize_1.ENCODED_SIGNER_KEY), 'Encryption context contains public verification key for unsigned algorithm suite.'); /* Check for early return (Postcondition): The algorithm suite specification must support a signatureCurve to load a signature key. */ return new material_management_1.NodeDecryptionMaterial(suite, encryptionContext); } /* Precondition: NodeDefaultCryptographicMaterialsManager If the algorithm suite specification requires a signatureCurve a context must exist. */ if (!encryptionContext) throw new Error('Encryption context does not contain required public key.'); const { [serialize_1.ENCODED_SIGNER_KEY]: compressPoint } = encryptionContext; /* Precondition: NodeDefaultCryptographicMaterialsManager The context must contain the public key. */ (0, material_management_1.needs)(compressPoint, 'Context does not contain required public key.'); const publicKeyBytes = material_management_1.VerificationKey.decodeCompressPoint(Buffer.from(compressPoint, 'base64'), suite); return new material_management_1.NodeDecryptionMaterial(suite, encryptionContext).setVerificationKey(new material_management_1.VerificationKey(publicKeyBytes, suite)); } } exports.NodeDefaultCryptographicMaterialsManager = NodeDefaultCryptographicMaterialsManager; (0, material_management_1.immutableClass)(NodeDefaultCryptographicMaterialsManager); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibm9kZV9jcnlwdG9ncmFwaGljX21hdGVyaWFsc19tYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL25vZGVfY3J5cHRvZ3JhcGhpY19tYXRlcmlhbHNfbWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0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xFQUFFLCtDQUErQyxDQUFDLENBQUE7UUFFckUsTUFBTSxjQUFjLEdBQUcscUNBQWUsQ0FBQyxtQkFBbUIsQ0FDeEQsTUFBTSxDQUFDLElBQUksQ0FBQyxhQUFhLEVBQUUsUUFBUSxDQUFDLEVBQ3BDLEtBQUssQ0FDTixDQUFBO1FBRUQsT0FBTyxJQUFJLDRDQUFzQixDQUMvQixLQUFLLEVBQ0wsaUJBQWlCLENBQ2xCLENBQUMsa0JBQWtCLENBQUMsSUFBSSxxQ0FBZSxDQUFDLGNBQWMsRUFBRSxLQUFLLENBQUMsQ0FBQyxDQUFBO0lBQ2xFLENBQUM7Q0FDRjtBQS9JRCw0RkErSUM7QUFDRCxJQUFBLG9DQUFjLEVBQUMsd0NBQXdDLENBQUMsQ0FBQSJ9 /***/ }), /***/ 79993: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AlgorithmSuite = exports.MessageFormat = exports.CommitmentPolicySuites = exports.CommittingAlgorithmSuiteIdentifier = exports.NonCommittingAlgorithmSuiteIdentifier = exports.SignaturePolicySuites = exports.NonSigningAlgorithmSuiteIdentifier = exports.SignaturePolicy = exports.CommitmentPolicy = exports.AlgorithmSuiteIdentifier = void 0; /* * This file contains information about particular algorithm suites used * within the encryption SDK. In most cases, end-users don't need to * manipulate this structure, but it can occasionally be needed for more * advanced use cases, such as writing keyrings. * * Here we describe the overall shape of the Algorithm Suites used by the AWS Encryption * SDK for JavaScript. Specific details for Node.js and WebCrypto can be found * in the respective files */ const immutable_class_1 = __nccwpck_require__(32746); const needs_1 = __nccwpck_require__(91846); /* References to https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/algorithms-reference.html * These define the possible parameters for algorithm specifications that correspond * to the Node.js or WebCrypto environment. * These parameters are composed into an algorithm suite specification for each * environment in the respective files. */ var AlgorithmSuiteIdentifier; (function (AlgorithmSuiteIdentifier) { AlgorithmSuiteIdentifier[AlgorithmSuiteIdentifier["ALG_AES128_GCM_IV12_TAG16"] = 20] = "ALG_AES128_GCM_IV12_TAG16"; AlgorithmSuiteIdentifier[AlgorithmSuiteIdentifier["ALG_AES192_GCM_IV12_TAG16"] = 70] = "ALG_AES192_GCM_IV12_TAG16"; AlgorithmSuiteIdentifier[AlgorithmSuiteIdentifier["ALG_AES256_GCM_IV12_TAG16"] = 120] = "ALG_AES256_GCM_IV12_TAG16"; AlgorithmSuiteIdentifier[AlgorithmSuiteIdentifier["ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256"] = 276] = "ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256"; AlgorithmSuiteIdentifier[AlgorithmSuiteIdentifier["ALG_AES192_GCM_IV12_TAG16_HKDF_SHA256"] = 326] = "ALG_AES192_GCM_IV12_TAG16_HKDF_SHA256"; AlgorithmSuiteIdentifier[AlgorithmSuiteIdentifier["ALG_AES256_GCM_IV12_TAG16_HKDF_SHA256"] = 376] = "ALG_AES256_GCM_IV12_TAG16_HKDF_SHA256"; AlgorithmSuiteIdentifier[AlgorithmSuiteIdentifier["ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256"] = 532] = "ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256"; AlgorithmSuiteIdentifier[AlgorithmSuiteIdentifier["ALG_AES192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384"] = 838] = "ALG_AES192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384"; AlgorithmSuiteIdentifier[AlgorithmSuiteIdentifier["ALG_AES256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384"] = 888] = "ALG_AES256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384"; AlgorithmSuiteIdentifier[AlgorithmSuiteIdentifier["ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY"] = 1144] = "ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY"; AlgorithmSuiteIdentifier[AlgorithmSuiteIdentifier["ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY_ECDSA_P384"] = 1400] = "ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY_ECDSA_P384"; })(AlgorithmSuiteIdentifier = exports.AlgorithmSuiteIdentifier || (exports.AlgorithmSuiteIdentifier = {})); Object.freeze(AlgorithmSuiteIdentifier); var CommitmentPolicy; (function (CommitmentPolicy) { CommitmentPolicy["FORBID_ENCRYPT_ALLOW_DECRYPT"] = "FORBID_ENCRYPT_ALLOW_DECRYPT"; CommitmentPolicy["REQUIRE_ENCRYPT_ALLOW_DECRYPT"] = "REQUIRE_ENCRYPT_ALLOW_DECRYPT"; CommitmentPolicy["REQUIRE_ENCRYPT_REQUIRE_DECRYPT"] = "REQUIRE_ENCRYPT_REQUIRE_DECRYPT"; })(CommitmentPolicy = exports.CommitmentPolicy || (exports.CommitmentPolicy = {})); Object.freeze(CommitmentPolicy); var SignaturePolicy; (function (SignaturePolicy) { SignaturePolicy["ALLOW_ENCRYPT_ALLOW_DECRYPT"] = "ALLOW_ENCRYPT_ALLOW_DECRYPT"; SignaturePolicy["ALLOW_ENCRYPT_FORBID_DECRYPT"] = "ALLOW_ENCRYPT_FORBID_DECRYPT"; })(SignaturePolicy = exports.SignaturePolicy || (exports.SignaturePolicy = {})); Object.freeze(SignaturePolicy); exports.NonSigningAlgorithmSuiteIdentifier = (() => { const { ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256, ALG_AES192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, ALG_AES256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY_ECDSA_P384, // Both the name side above, and the id side below [0x0214]: NAME_ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256, [0x0346]: NAME_ALG_AES192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, [0x0378]: NAME_ALG_AES256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, [0x0578]: NAME_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY_ECDSA_P384, ...NonSigningAlgorithmSuiteIdentifier } = AlgorithmSuiteIdentifier; return NonSigningAlgorithmSuiteIdentifier; })(); exports.SignaturePolicySuites = Object.freeze({ isDecryptEnabled(signaturePolicy, suite, messageId) { const id = suite.id || suite; const name = suite.name || AlgorithmSuiteIdentifier[id]; let decryption_client_name = 'decryptStream'; let signature_description = 'signed'; if (signaturePolicy === SignaturePolicy.ALLOW_ENCRYPT_FORBID_DECRYPT) { decryption_client_name = 'decryptUnsignedMessageStream'; signature_description = 'un-signed'; } /* Precondition: Only handle DecryptionMaterial for algorithm suites supported in signaturePolicy. */ (0, needs_1.needs)(this[signaturePolicy].decryptEnabledSuites[id], `Configuration conflict. ` + `Cannot process message with ID ${messageId} ` + `due to client method ${decryption_client_name} ` + `requiring only ${signature_description} messages. ` + `Algorithm ID was ${name}. ` + `See: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#digital-sigs`); }, [SignaturePolicy.ALLOW_ENCRYPT_ALLOW_DECRYPT]: Object.freeze({ decryptEnabledSuites: AlgorithmSuiteIdentifier, defaultAlgorithmSuite: AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY_ECDSA_P384, }), [SignaturePolicy.ALLOW_ENCRYPT_FORBID_DECRYPT]: Object.freeze({ decryptEnabledSuites: exports.NonSigningAlgorithmSuiteIdentifier, defaultAlgorithmSuite: AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY, }), }); exports.NonCommittingAlgorithmSuiteIdentifier = (() => { const { ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY, ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY_ECDSA_P384, // Both the name side above, and the id side below [0x0478]: NAME_ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY, [0x0578]: NAME_ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY_ECDSA_P384, ...NonCommittingAlgorithmSuiteIdentifier } = AlgorithmSuiteIdentifier; return NonCommittingAlgorithmSuiteIdentifier; })(); exports.CommittingAlgorithmSuiteIdentifier = (() => { const { ALG_AES128_GCM_IV12_TAG16, ALG_AES192_GCM_IV12_TAG16, ALG_AES256_GCM_IV12_TAG16, ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256, ALG_AES192_GCM_IV12_TAG16_HKDF_SHA256, ALG_AES256_GCM_IV12_TAG16_HKDF_SHA256, ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256, ALG_AES192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, ALG_AES256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, // Both the name side above, and the id side below [0x0014]: NAME_ALG_AES128_GCM_IV12_TAG16, [0x0046]: NAME_ALG_AES192_GCM_IV12_TAG16, [0x0078]: NAME_ALG_AES256_GCM_IV12_TAG16, [0x0114]: NAME_ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256, [0x0146]: NAME_ALG_AES192_GCM_IV12_TAG16_HKDF_SHA256, [0x0178]: NAME_ALG_AES256_GCM_IV12_TAG16_HKDF_SHA256, [0x0214]: NAME_ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256, [0x0346]: NAME_ALG_AES192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, [0x0378]: NAME_ALG_AES256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, ...CommittingAlgorithmSuiteIdentifier } = AlgorithmSuiteIdentifier; return CommittingAlgorithmSuiteIdentifier; })(); exports.CommitmentPolicySuites = Object.freeze({ isEncryptEnabled(commitmentPolicy, suite) { if (!suite) return; const id = suite.id || suite; const name = suite.name || AlgorithmSuiteIdentifier[id]; /* Precondition: Only handle EncryptionMaterial for algorithm suites supported in commitmentPolicy. */ (0, needs_1.needs)(this[commitmentPolicy].encryptEnabledSuites[id], `Configuration conflict. ` + `Cannot encrypt due to CommitmentPolicy ${commitmentPolicy} ` + `requiring only non-committed messages. ` + `Algorithm ID was ${name}. ` + `See: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/troubleshooting-migration.html`); }, isDecryptEnabled(commitmentPolicy, suite, messageId) { const id = suite.id || suite; const name = suite.name || AlgorithmSuiteIdentifier[id]; /* Precondition: Only handle DecryptionMaterial for algorithm suites supported in commitmentPolicy. */ (0, needs_1.needs)(this[commitmentPolicy].decryptEnabledSuites[id], `Configuration conflict. ` + `Cannot process message with ID ${messageId} ` + `due to CommitmentPolicy ${commitmentPolicy} ` + `requiring only committed messages. ` + `Algorithm ID was ${name}. ` + `See: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/troubleshooting-migration.html`); }, [CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT]: Object.freeze({ encryptEnabledSuites: exports.NonCommittingAlgorithmSuiteIdentifier, decryptEnabledSuites: AlgorithmSuiteIdentifier, defaultAlgorithmSuite: exports.NonCommittingAlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, }), [CommitmentPolicy.REQUIRE_ENCRYPT_ALLOW_DECRYPT]: Object.freeze({ encryptEnabledSuites: exports.CommittingAlgorithmSuiteIdentifier, decryptEnabledSuites: AlgorithmSuiteIdentifier, defaultAlgorithmSuite: exports.CommittingAlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY_ECDSA_P384, }), [CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT]: Object.freeze({ encryptEnabledSuites: exports.CommittingAlgorithmSuiteIdentifier, decryptEnabledSuites: exports.CommittingAlgorithmSuiteIdentifier, defaultAlgorithmSuite: exports.CommittingAlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY_ECDSA_P384, }), }); var MessageFormat; (function (MessageFormat) { MessageFormat[MessageFormat["V1"] = 1] = "V1"; MessageFormat[MessageFormat["V2"] = 2] = "V2"; })(MessageFormat = exports.MessageFormat || (exports.MessageFormat = {})); Object.freeze(MessageFormat); class AlgorithmSuite { constructor(suiteValues) { (0, needs_1.needs)(this.constructor !== AlgorithmSuite, 'new AlgorithmSuite is not allowed'); /* Precondition: A algorithm suite specification must be passed. */ (0, needs_1.needs)(suiteValues, 'Algorithm specification not set.'); /* Precondition: The Algorithm Suite Identifier must exist. */ (0, needs_1.needs)(AlgorithmSuiteIdentifier[suiteValues.id], 'No suite by that identifier exists.'); Object.assign(this, suiteValues); (0, immutable_class_1.readOnlyProperty)(this, 'keyLengthBytes', this.keyLength / 8); (0, immutable_class_1.readOnlyProperty)(this, 'name', AlgorithmSuiteIdentifier[this.id]); } } exports.AlgorithmSuite = AlgorithmSuite; (0, immutable_class_1.immutableClass)(AlgorithmSuite); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYWxnb3JpdGhtX3N1aXRlcy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9hbGdvcml0aG1fc3VpdGVzLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7QUFFdEM7Ozs7Ozs7OztHQVNHO0FBRUgsdURBQW9FO0FBQ3BFLG1DQUErQjtBQUUvQjs7Ozs7R0FLRztBQUNILElBQVksd0JBWVg7QUFaRCxXQUFZLHdCQUF3QjtJQUNsQyxrSEFBb0MsQ0FBQTtJQUNwQyxrSEFBb0MsQ0FBQTtJQUNwQyxtSEFBb0MsQ0FBQTtJQUNwQ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SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.cloneMaterial = void 0; const cryptographic_material_1 = __nccwpck_require__(91301); const node_algorithms_1 = __nccwpck_require__(79966); const needs_1 = __nccwpck_require__(91846); function cloneMaterial(source) { const { suite, encryptionContext } = source; const clone = (suite instanceof node_algorithms_1.NodeAlgorithmSuite ? source instanceof cryptographic_material_1.NodeEncryptionMaterial ? new cryptographic_material_1.NodeEncryptionMaterial(suite, encryptionContext) : new cryptographic_material_1.NodeDecryptionMaterial(suite, encryptionContext) : source instanceof cryptographic_material_1.WebCryptoEncryptionMaterial ? new cryptographic_material_1.WebCryptoEncryptionMaterial(suite, encryptionContext) : new cryptographic_material_1.WebCryptoDecryptionMaterial(suite, encryptionContext)); /* The setTrace _must_ be the first trace, * If the material is an EncryptionMaterial * then the data key *must* have been generated. * If the material is DecryptionMaterial * then the data key *must* have been decrypted. * i.e. the required flags are: * WRAPPING_KEY_GENERATED_DATA_KEY, WRAPPING_KEY_DECRYPTED_DATA_KEY * These are controlled by the material itself. * Furthermore, subsequent trace entries, * *must* be in the same order as the added encrypted data keys. * See cryptographic_materials.ts `decorateCryptographicMaterial`, `decorateWebCryptoMaterial`. */ const [setTrace, ...traces] = source.keyringTrace.slice(); if (source.hasUnencryptedDataKey) { const udk = cloneUnencryptedDataKey(source.getUnencryptedDataKey()); clone.setUnencryptedDataKey(udk, setTrace); } if (source.hasCryptoKey) { const cryptoKey = source.getCryptoKey(); clone.setCryptoKey(cryptoKey, setTrace); } if ((0, cryptographic_material_1.isEncryptionMaterial)(source) && (0, cryptographic_material_1.isEncryptionMaterial)(clone)) { const encryptedDataKeys = source.encryptedDataKeys; /* Precondition: For each encrypted data key, there must be a trace. */ (0, needs_1.needs)(encryptedDataKeys.length === traces.length, 'KeyringTrace length does not match encrypted data keys.'); encryptedDataKeys.forEach((edk, i) => { const { providerInfo, providerId } = edk; const { keyNamespace, keyName, flags } = traces[i]; /* Precondition: The traces must be in the same order as the encrypted data keys. */ (0, needs_1.needs)(keyName === providerInfo && keyNamespace === providerId, 'Keyring trace does not match encrypted data key.'); clone.addEncryptedDataKey(edk, flags); }); if (source.suite.signatureCurve && source.signatureKey) { clone.setSignatureKey(source.signatureKey); } } else if ((0, cryptographic_material_1.isDecryptionMaterial)(source) && (0, cryptographic_material_1.isDecryptionMaterial)(clone)) { /* Precondition: On Decrypt there must not be any additional traces other than the setTrace. */ (0, needs_1.needs)(!traces.length, 'Only 1 trace is valid on DecryptionMaterials.'); if (source.suite.signatureCurve && source.verificationKey) { clone.setVerificationKey(source.verificationKey); } } else { throw new Error('Material mismatch'); } return clone; } exports.cloneMaterial = cloneMaterial; function cloneUnencryptedDataKey(dataKey) { if (dataKey instanceof Uint8Array) { return new Uint8Array(dataKey); } return dataKey; } //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY2xvbmVfY3J5cHRvZ3JhcGhpY19tYXRlcmlhbC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9jbG9uZV9jcnlwdG9ncmFwaGljX21hdGVyaWFsLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7QUFFdEMscUVBT2lDO0FBQ2pDLHVEQUFzRDtBQUV0RCxtQ0FBK0I7QUFRL0IsU0FBZ0IsYUFBYSxDQUFxQixNQUFTO0lBQ3pELE1BQU0sRUFBRSxLQUFLLEVBQUUsaUJBQWlCLEVBQUUsR0FBRyxNQUFNLENBQUE7SUFFM0MsTUFBTSxLQUFLLEdBQUcsQ0FDWixLQUFLLFlBQVksb0NBQWtCO1FBQ2pDLENBQUMsQ0FBQyxNQUFNLFlBQVksK0NBQXNCO1lBQ3hDLENBQUMsQ0FBQyxJQUFJLCtDQUFzQixDQUFDLEtBQUssRUFBRSxpQkFBaUIsQ0FBQztZQUN0RCxDQUFDLENBQUMsSU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FBQ0wsTUFBTSxJQUFJLEtBQUssQ0FBQyxtQkFBbUIsQ0FBQyxDQUFBO0tBQ3JDO0lBRUQsT0FBTyxLQUFLLENBQUE7QUFDZCxDQUFDO0FBckVELHNDQXFFQztBQUVELFNBQVMsdUJBQXVCLENBQUMsT0FBc0M7SUFDckUsSUFBSSxPQUFPLFlBQVksVUFBVSxFQUFFO1FBQ2pDLE9BQU8sSUFBSSxVQUFVLENBQUMsT0FBTyxDQUFDLENBQUE7S0FDL0I7SUFDRCxPQUFPLE9BQU8sQ0FBQTtBQUNoQixDQUFDIn0= /***/ }), /***/ 91301: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.wrapWithKeyObjectIfSupported = exports.unwrapDataKey = exports.subtleFunctionForMaterial = exports.keyUsageForMaterial = exports.isValidCryptoKey = exports.isCryptoKey = exports.decorateWebCryptoMaterial = exports.decorateDecryptionMaterial = exports.decorateEncryptionMaterial = exports.decorateCryptographicMaterial = exports.isDecryptionMaterial = exports.isEncryptionMaterial = exports.WebCryptoDecryptionMaterial = exports.WebCryptoEncryptionMaterial = exports.NodeDecryptionMaterial = exports.NodeEncryptionMaterial = exports.supportsKeyObject = void 0; const encrypted_data_key_1 = __nccwpck_require__(30466); const signature_key_1 = __nccwpck_require__(80872); const immutable_class_1 = __nccwpck_require__(32746); const keyring_trace_1 = __nccwpck_require__(24530); const node_algorithms_1 = __nccwpck_require__(79966); const web_crypto_algorithms_1 = __nccwpck_require__(28311); const needs_1 = __nccwpck_require__(91846); exports.supportsKeyObject = (function () { try { const { KeyObject, createSecretKey } = __nccwpck_require__(6113); // eslint-disable-line @typescript-eslint/no-var-requires if (!KeyObject || !createSecretKey) return false; return { KeyObject, createSecretKey }; } catch (ex) { return false; } })(); /* * This public interface to the CryptographicMaterial object is provided for * developers of CMMs and keyrings only. If you are a user of the AWS Encryption * SDK and you are not developing your own CMMs and/or keyrings, you do not * need to use it and you should not do so. * * The CryptographicMaterial's purpose is to bind together all the required elements for * encrypting or decrypting a payload. * The functional data key (unencrypted or CryptoKey) is the most sensitive data and needs to * be protected. The longer this data persists in memory the * greater the opportunity to be invalidated. Because * a Caching CMM exists it is important to ensure that the * unencrypted data key and its meta data can not be manipulated, * and that the unencrypted data key can be zeroed when * it is no longer needed. */ const timingSafeEqual = (function () { try { /* It is possible for `require` to return an empty object, or an object * that does not implement `timingSafeEqual`. * in this case I need a fallback */ const { timingSafeEqual: nodeTimingSafeEqual } = __nccwpck_require__(6113); // eslint-disable-line @typescript-eslint/no-var-requires return nodeTimingSafeEqual || portableTimingSafeEqual; } catch (e) { return portableTimingSafeEqual; } /* https://codahale.com/a-lesson-in-timing-attacks/ */ function portableTimingSafeEqual(a, b) { /* It is *possible* that a runtime could optimize this constant time function. * Adding `eval` could prevent the optimization, but this is no guarantee. * The eval below is commented out * because if a browser is using a Content Security Policy with `'unsafe-eval'` * it would fail on this eval. * The value in attempting to ensure that this function is not optimized * is not worth the cost of making customers allow `'unsafe-eval'`. * If you want to copy this function for your own use, * please review the timing-attack link above. * Side channel attacks are pernicious and subtle. */ // eval('') // eslint-disable-line no-eval /* Check for early return (Postcondition) UNTESTED: Size is well-know information * and does not leak information about contents. */ if (a.byteLength !== b.byteLength) return false; let diff = 0; for (let i = 0; i < b.length; i++) { diff |= a[i] ^ b[i]; } return diff === 0; } })(); class NodeEncryptionMaterial { suite; setUnencryptedDataKey; getUnencryptedDataKey; zeroUnencryptedDataKey; hasUnencryptedDataKey; keyringTrace = []; encryptedDataKeys; addEncryptedDataKey; setSignatureKey; signatureKey; encryptionContext; constructor(suite, encryptionContext) { /* Precondition: NodeEncryptionMaterial suite must be NodeAlgorithmSuite. */ (0, needs_1.needs)(suite instanceof node_algorithms_1.NodeAlgorithmSuite, 'Suite must be a NodeAlgorithmSuite'); this.suite = suite; /* Precondition: NodeEncryptionMaterial encryptionContext must be an object, even if it is empty. */ (0, needs_1.needs)(encryptionContext && typeof encryptionContext === 'object', 'Encryption context must be set'); this.encryptionContext = Object.freeze({ ...encryptionContext }); // EncryptionMaterial have generated a data key on setUnencryptedDataKey const setFlags = keyring_trace_1.KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY; decorateCryptographicMaterial(this, setFlags); decorateEncryptionMaterial(this); Object.setPrototypeOf(this, NodeEncryptionMaterial.prototype); Object.freeze(this); } hasValidKey() { return this.hasUnencryptedDataKey; } } exports.NodeEncryptionMaterial = NodeEncryptionMaterial; (0, immutable_class_1.frozenClass)(NodeEncryptionMaterial); class NodeDecryptionMaterial { suite; setUnencryptedDataKey; getUnencryptedDataKey; zeroUnencryptedDataKey; hasUnencryptedDataKey; keyringTrace = []; setVerificationKey; verificationKey; encryptionContext; constructor(suite, encryptionContext) { /* Precondition: NodeDecryptionMaterial suite must be NodeAlgorithmSuite. */ (0, needs_1.needs)(suite instanceof node_algorithms_1.NodeAlgorithmSuite, 'Suite must be a NodeAlgorithmSuite'); this.suite = suite; /* Precondition: NodeDecryptionMaterial encryptionContext must be an object, even if it is empty. */ (0, needs_1.needs)(encryptionContext && typeof encryptionContext === 'object', 'Encryption context must be set'); this.encryptionContext = Object.freeze({ ...encryptionContext }); // DecryptionMaterial have decrypted a data key on setUnencryptedDataKey const setFlags = keyring_trace_1.KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY; decorateCryptographicMaterial(this, setFlags); decorateDecryptionMaterial(this); Object.setPrototypeOf(this, NodeDecryptionMaterial.prototype); Object.freeze(this); } hasValidKey() { return this.hasUnencryptedDataKey; } } exports.NodeDecryptionMaterial = NodeDecryptionMaterial; (0, immutable_class_1.frozenClass)(NodeDecryptionMaterial); class WebCryptoEncryptionMaterial { suite; setUnencryptedDataKey; getUnencryptedDataKey; zeroUnencryptedDataKey; hasUnencryptedDataKey; keyringTrace = []; encryptedDataKeys; addEncryptedDataKey; setSignatureKey; signatureKey; setCryptoKey; getCryptoKey; hasCryptoKey; validUsages; encryptionContext; constructor(suite, encryptionContext) { /* Precondition: WebCryptoEncryptionMaterial suite must be WebCryptoAlgorithmSuite. */ (0, needs_1.needs)(suite instanceof web_crypto_algorithms_1.WebCryptoAlgorithmSuite, 'Suite must be a WebCryptoAlgorithmSuite'); this.suite = suite; this.validUsages = Object.freeze([ 'deriveKey', 'encrypt', ]); /* Precondition: WebCryptoEncryptionMaterial encryptionContext must be an object, even if it is empty. */ (0, needs_1.needs)(encryptionContext && typeof encryptionContext === 'object', 'Encryption context must be set'); this.encryptionContext = Object.freeze({ ...encryptionContext }); // EncryptionMaterial have generated a data key on setUnencryptedDataKey const setFlag = keyring_trace_1.KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY; decorateCryptographicMaterial(this, setFlag); decorateEncryptionMaterial(this); decorateWebCryptoMaterial(this, setFlag); Object.setPrototypeOf(this, WebCryptoEncryptionMaterial.prototype); Object.freeze(this); } hasValidKey() { return this.hasUnencryptedDataKey && this.hasCryptoKey; } } exports.WebCryptoEncryptionMaterial = WebCryptoEncryptionMaterial; (0, immutable_class_1.frozenClass)(WebCryptoEncryptionMaterial); class WebCryptoDecryptionMaterial { suite; setUnencryptedDataKey; getUnencryptedDataKey; zeroUnencryptedDataKey; hasUnencryptedDataKey; keyringTrace = []; setVerificationKey; verificationKey; setCryptoKey; getCryptoKey; hasCryptoKey; validUsages; encryptionContext; constructor(suite, encryptionContext) { /* Precondition: WebCryptoDecryptionMaterial suite must be WebCryptoAlgorithmSuite. */ (0, needs_1.needs)(suite instanceof web_crypto_algorithms_1.WebCryptoAlgorithmSuite, 'Suite must be a WebCryptoAlgorithmSuite'); this.suite = suite; this.validUsages = Object.freeze([ 'deriveKey', 'decrypt', ]); /* Precondition: WebCryptoDecryptionMaterial encryptionContext must be an object, even if it is empty. */ (0, needs_1.needs)(encryptionContext && typeof encryptionContext === 'object', 'Encryption context must be set'); this.encryptionContext = Object.freeze({ ...encryptionContext }); // DecryptionMaterial have decrypted a data key on setUnencryptedDataKey const setFlag = keyring_trace_1.KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY; decorateCryptographicMaterial(this, setFlag); decorateDecryptionMaterial(this); decorateWebCryptoMaterial(this, setFlag); Object.setPrototypeOf(this, WebCryptoDecryptionMaterial.prototype); Object.freeze(this); } hasValidKey() { return this.hasCryptoKey; } } exports.WebCryptoDecryptionMaterial = WebCryptoDecryptionMaterial; (0, immutable_class_1.frozenClass)(WebCryptoDecryptionMaterial); function isEncryptionMaterial(obj) { return (obj instanceof WebCryptoEncryptionMaterial || obj instanceof NodeEncryptionMaterial); } exports.isEncryptionMaterial = isEncryptionMaterial; function isDecryptionMaterial(obj) { return (obj instanceof WebCryptoDecryptionMaterial || obj instanceof NodeDecryptionMaterial); } exports.isDecryptionMaterial = isDecryptionMaterial; function decorateCryptographicMaterial(material, setFlag) { /* Precondition: setFlag must be in the set of KeyringTraceFlag.SET_FLAGS. */ (0, needs_1.needs)(setFlag & keyring_trace_1.KeyringTraceFlag.SET_FLAGS, 'Invalid setFlag'); /* When a KeyringTraceFlag is passed to setUnencryptedDataKey, * it must be valid for the type of material. * It is invalid to claim that EncryptionMaterial were decrypted. */ const deniedSetFlags = (keyring_trace_1.KeyringTraceFlag.SET_FLAGS ^ setFlag) | (setFlag === keyring_trace_1.KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY ? keyring_trace_1.KeyringTraceFlag.DECRYPT_FLAGS : setFlag === keyring_trace_1.KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY ? keyring_trace_1.KeyringTraceFlag.ENCRYPT_FLAGS : 0); let unencryptedDataKeyZeroed = false; let unencryptedDataKey; // This copy of the unencryptedDataKey is stored to insure that the // unencrypted data key is *never* modified. Since the // unencryptedDataKey is returned by reference, any change // to it would be propagated to any cached versions. let udkForVerification; const setUnencryptedDataKey = (dataKey, trace) => { /* Avoid making unnecessary copies of the dataKey. */ const tempUdk = dataKey instanceof Uint8Array ? dataKey : unwrapDataKey(dataKey); /* All security conditions are tested here and failures will throw. */ verifyUnencryptedDataKeyForSet(tempUdk, trace); unencryptedDataKey = wrapWithKeyObjectIfSupported(dataKey); udkForVerification = new Uint8Array(tempUdk); material.keyringTrace.push(trace); return material; }; const getUnencryptedDataKey = () => { /* Precondition: unencryptedDataKey must be set before we can return it. */ (0, needs_1.needs)(unencryptedDataKey, 'unencryptedDataKey has not been set'); /* Precondition: unencryptedDataKey must not be Zeroed out. * Returning a null key would be incredibly bad. */ (0, needs_1.needs)(!unencryptedDataKeyZeroed, 'unencryptedDataKey has been zeroed.'); /* Precondition: The unencryptedDataKey must not have been modified. * If the unencryptedDataKey is a KeyObject, * then the security around modification is handled in C. * Do not duplicate the secret just to check... */ (0, needs_1.needs)(!(unencryptedDataKey instanceof Uint8Array) || timingSafeEqual(udkForVerification, unwrapDataKey(unencryptedDataKey)), 'unencryptedDataKey has been corrupted.'); return unencryptedDataKey; }; Object.defineProperty(material, 'hasUnencryptedDataKey', { // Check that we have both not zeroed AND that we have not set get: () => !!unencryptedDataKey && !unencryptedDataKeyZeroed, enumerable: true, }); const zeroUnencryptedDataKey = () => { /* These checks are separated on purpose. It should be impossible to have only one unset. * *But* if it was the case, I *must* make sure I zero out the set one, and not leave it up to GC. * If I only checked on say unencryptedDataKey, and udkForVerification was somehow set, * doing the simplest thing would be to set both to new Uint8Array. * Leaving udkForVerification to be garbage collected. * This level of insanity is due to the fact that we are dealing with the unencrypted data key. */ let unsetCount = 0; /* Precondition: If the unencryptedDataKey has not been set, it should not be settable later. */ if (!unencryptedDataKey) { unencryptedDataKey = new Uint8Array(); unsetCount += 1; } /* Precondition: If the udkForVerification has not been set, it should not be settable later. */ if (!udkForVerification) { udkForVerification = new Uint8Array(); unsetCount += 1; } /* The KeyObject manages its own ref counter. * Once there are no more users, it will clean the memory. */ if (!(unencryptedDataKey instanceof Uint8Array)) { unencryptedDataKey = new Uint8Array(); } unencryptedDataKey.fill(0); udkForVerification.fill(0); unencryptedDataKeyZeroed = true; /* Postcondition UNTESTED: Both unencryptedDataKey and udkForVerification must be either set or unset. * If it is ever the case that only one was unset, then something is wrong in a profound way. * It is not clear how this could ever happen, unless someone is manipulating the OS... */ (0, needs_1.needs)(unsetCount === 0 || unsetCount === 2, 'Either unencryptedDataKey or udkForVerification was not set.'); return material; }; (0, immutable_class_1.readOnlyProperty)(material, 'setUnencryptedDataKey', setUnencryptedDataKey); (0, immutable_class_1.readOnlyProperty)(material, 'getUnencryptedDataKey', getUnencryptedDataKey); (0, immutable_class_1.readOnlyProperty)(material, 'zeroUnencryptedDataKey', zeroUnencryptedDataKey); return material; function verifyUnencryptedDataKeyForSet(dataKey, trace) { /* Precondition: unencryptedDataKey must not be set. Modifying the unencryptedDataKey is denied */ (0, needs_1.needs)(!unencryptedDataKey, 'unencryptedDataKey has already been set'); /* Precondition: dataKey must be Binary Data */ (0, needs_1.needs)(dataKey instanceof Uint8Array, 'dataKey must be a Uint8Array'); /* Precondition: dataKey should have an ArrayBuffer that *only* stores the key. * This is a simple check to make sure that the key is not stored on * a large potentially shared ArrayBuffer. * If this was the case, it may be possible to find or manipulate. */ (0, needs_1.needs)(dataKey.byteOffset === 0, 'Unencrypted Master Key must be an isolated buffer.'); /* Precondition: The data key length must agree with algorithm specification. * If this is not the case, it either means ciphertext was tampered * with or the keyring implementation is not setting the length properly. */ (0, needs_1.needs)(dataKey.byteLength === material.suite.keyLengthBytes, 'Key length does not agree with the algorithm specification.'); /* Precondition: Trace must be set, and the flag must indicate that the data key was generated. */ (0, needs_1.needs)(trace && trace.keyName && trace.keyNamespace, 'Malformed KeyringTrace'); /* Precondition: On set the required KeyringTraceFlag must be set. */ (0, needs_1.needs)(trace.flags & setFlag, 'Required KeyringTraceFlag not set'); /* Precondition: Only valid flags are allowed. * An unencrypted data key can not be both generated and decrypted. */ (0, needs_1.needs)(!(trace.flags & deniedSetFlags), 'Invalid KeyringTraceFlags set.'); } } exports.decorateCryptographicMaterial = decorateCryptographicMaterial; function decorateEncryptionMaterial(material) { const deniedEncryptFlags = keyring_trace_1.KeyringTraceFlag.SET_FLAGS | keyring_trace_1.KeyringTraceFlag.DECRYPT_FLAGS; const encryptedDataKeys = []; let signatureKey; const addEncryptedDataKey = (edk, flags) => { /* Precondition: If a data key has not already been generated, there must be no EDKs. * Pushing EDKs on the list before the data key has been generated may cause the list of * EDKs to be inconsistent. (i.e., they would decrypt to different data keys.) */ (0, needs_1.needs)(material.hasUnencryptedDataKey, 'Unencrypted data key not set.'); /* Precondition: Edk must be EncryptedDataKey * Putting things onto the list that are not EncryptedDataKey * may cause the list of EDKs to be inconsistent. (i.e. they may not serialize, or be mutable) */ (0, needs_1.needs)(edk instanceof encrypted_data_key_1.EncryptedDataKey, 'Unsupported instance of encryptedDataKey'); /* Precondition: flags must indicate that the key was encrypted. */ (0, needs_1.needs)(flags & keyring_trace_1.KeyringTraceFlag.WRAPPING_KEY_ENCRYPTED_DATA_KEY, 'Encrypted data key flag must be set.'); /* Precondition: flags must not include a setFlag or a decrypt flag. * The setFlag is reserved for setting the unencrypted data key * and must only occur once in the set of KeyringTrace flags. * The two setFlags in use are: * KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY * KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY * * KeyringTraceFlag.WRAPPING_KEY_VERIFIED_ENC_CTX is reserved for the decrypt path */ (0, needs_1.needs)(!(flags & deniedEncryptFlags), 'Invalid flag for EncryptedDataKey.'); material.keyringTrace.push({ keyName: edk.providerInfo, keyNamespace: edk.providerId, flags, }); encryptedDataKeys.push(edk); return material; }; (0, immutable_class_1.readOnlyProperty)(material, 'addEncryptedDataKey', addEncryptedDataKey); Object.defineProperty(material, 'encryptedDataKeys', { // I only want EDKs added through addEncryptedDataKey // so I return a new array get: () => [...encryptedDataKeys], enumerable: true, }); const setSignatureKey = (key) => { /* Precondition: The SignatureKey stored must agree with the algorithm specification. * If this is not the case it means the MaterialManager or Keyring is not setting * the SignatureKey correctly */ (0, needs_1.needs)(material.suite.signatureCurve, 'Algorithm specification does not support signatures.'); /* Precondition: signatureKey must not be set. Modifying the signatureKey is denied. */ (0, needs_1.needs)(!signatureKey, 'Signature key has already been set.'); /* Precondition: key must be a SignatureKey. */ (0, needs_1.needs)(key instanceof signature_key_1.SignatureKey, 'Unsupported instance of key'); signatureKey = key; return material; }; (0, immutable_class_1.readOnlyProperty)(material, 'setSignatureKey', setSignatureKey); Object.defineProperty(material, 'signatureKey', { get: () => { /* Precondition: The SignatureKey requested must agree with the algorithm specification. * If this is not the case it means the MaterialManager or Keyring is not setting * the SignatureKey correctly */ (0, needs_1.needs)(!!material.suite.signatureCurve === !!signatureKey, 'Algorithm specification not satisfied.'); return signatureKey; }, enumerable: true, }); return material; } exports.decorateEncryptionMaterial = decorateEncryptionMaterial; function decorateDecryptionMaterial(material) { // Verification Key let verificationKey; const setVerificationKey = (key) => { /* Precondition: The VerificationKey stored must agree with the algorithm specification. * If this is not the case it means the MaterialManager or Keyring is not setting * the VerificationKey correctly */ (0, needs_1.needs)(material.suite.signatureCurve, 'Algorithm specification does not support signatures.'); /* Precondition: verificationKey must not be set. Modifying the verificationKey is denied. */ (0, needs_1.needs)(!verificationKey, 'Verification key has already been set.'); /* Precondition: key must be a VerificationKey. */ (0, needs_1.needs)(key instanceof signature_key_1.VerificationKey, 'Unsupported instance of key'); verificationKey = key; return material; }; (0, immutable_class_1.readOnlyProperty)(material, 'setVerificationKey', setVerificationKey); Object.defineProperty(material, 'verificationKey', { get: () => { /* Precondition: The VerificationKey requested must agree with the algorithm specification. * If this is not the case it means the MaterialManager or Keyring is not setting * the VerificationKey correctly */ (0, needs_1.needs)(!!material.suite.signatureCurve === !!verificationKey, 'Algorithm specification not satisfied.'); return verificationKey; }, enumerable: true, }); return material; } exports.decorateDecryptionMaterial = decorateDecryptionMaterial; function decorateWebCryptoMaterial(material, setFlags) { let cryptoKey; const setCryptoKey = (dataKey, trace) => { /* Precondition: cryptoKey must not be set. Modifying the cryptoKey is denied */ (0, needs_1.needs)(!cryptoKey, 'cryptoKey is already set.'); /* Precondition: dataKey must be a supported type. */ (0, needs_1.needs)(isCryptoKey(dataKey) || isMixedBackendCryptoKey(dataKey), 'Unsupported dataKey type.'); /* Precondition: The CryptoKey must match the algorithm suite specification. */ (0, needs_1.needs)(isValidCryptoKey(dataKey, material), 'CryptoKey settings not acceptable.'); /* If the material does not have an unencrypted data key, * then we are setting the crypto key here and need a keyring trace . */ if (!material.hasUnencryptedDataKey) { /* Precondition: If the CryptoKey is the only version, the trace information must be set here. */ (0, needs_1.needs)(trace && trace.keyName && trace.keyNamespace, 'Malformed KeyringTrace'); /* Precondition: On setting the CryptoKey the required KeyringTraceFlag must be set. */ (0, needs_1.needs)(trace.flags & setFlags, 'Required KeyringTraceFlag not set'); /* If I a setting a cryptoKey without an unencrypted data key, * an unencrypted data should never be set. * The expectation is if you are setting the cryptoKey *first* then * the unencrypted data key has already been "handled". * This ensures that a cryptoKey and an unencrypted data key always match. */ material.zeroUnencryptedDataKey(); material.keyringTrace.push(trace); } if (isCryptoKey(dataKey)) { cryptoKey = dataKey; } else { const { zeroByteCryptoKey, nonZeroByteCryptoKey } = dataKey; cryptoKey = Object.freeze({ zeroByteCryptoKey, nonZeroByteCryptoKey }); } return material; }; (0, immutable_class_1.readOnlyProperty)(material, 'setCryptoKey', setCryptoKey); const getCryptoKey = () => { /* Precondition: The cryptoKey must be set before we can return it. */ (0, needs_1.needs)(cryptoKey, 'Crypto key is not set.'); // In the case of MixedBackendCryptoKey the object // has already been frozen above so it is safe to return return cryptoKey; }; (0, immutable_class_1.readOnlyProperty)(material, 'getCryptoKey', getCryptoKey); Object.defineProperty(material, 'hasCryptoKey', { get: () => !!cryptoKey, enumerable: true, }); return material; } exports.decorateWebCryptoMaterial = decorateWebCryptoMaterial; function isCryptoKey(dataKey) { return (dataKey && 'algorithm' in dataKey && 'type' in dataKey && 'usages' in dataKey && 'extractable' in dataKey); } exports.isCryptoKey = isCryptoKey; function isValidCryptoKey(dataKey, material) { if (!isCryptoKey(dataKey)) { const { zeroByteCryptoKey, nonZeroByteCryptoKey } = dataKey; return (isValidCryptoKey(zeroByteCryptoKey, material) && isValidCryptoKey(nonZeroByteCryptoKey, material)); } const { suite, validUsages } = material; const { encryption, keyLength, kdf } = suite; /* See: * https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey * https://developer.mozilla.org/en-US/docs/Web/API/AesKeyGenParams */ const { type, algorithm, usages, extractable } = dataKey; // @ts-ignore length is an optional value... const { name, length } = algorithm; /* MSRCrypto, for legacy reasons, * normalizes the algorithm name * to lower case. * https://github.com/microsoft/MSR-JavaScript-Crypto/issues/1 * For now, I'm going to upper case the name. */ // Only symmetric algorithms return (type === 'secret' && // Must match the suite ((kdf && name.toUpperCase() === kdf) || (name.toUpperCase() === encryption && length === keyLength)) && /* Only valid usage are: encrypt|decrypt|deriveKey * The complexity between deriveKey and suite.kdf should be handled in the Material class. */ usages.some((u) => validUsages.includes(u)) && // Since CryptoKey can not be zeroized, not extractable is the next best thing !extractable); } exports.isValidCryptoKey = isValidCryptoKey; function isMixedBackendCryptoKey(dataKey) { const { zeroByteCryptoKey, nonZeroByteCryptoKey } = dataKey; return isCryptoKey(zeroByteCryptoKey) && isCryptoKey(nonZeroByteCryptoKey); } function keyUsageForMaterial(material) { const { suite } = material; if (suite.kdf) return 'deriveKey'; return subtleFunctionForMaterial(material); } exports.keyUsageForMaterial = keyUsageForMaterial; function subtleFunctionForMaterial(material) { if (material instanceof WebCryptoEncryptionMaterial) return 'encrypt'; if (material instanceof WebCryptoDecryptionMaterial) return 'decrypt'; throw new Error('Unsupported material'); } exports.subtleFunctionForMaterial = subtleFunctionForMaterial; function unwrapDataKey(dataKey) { if (dataKey instanceof Uint8Array) return dataKey; if (exports.supportsKeyObject && dataKey instanceof exports.supportsKeyObject.KeyObject) return dataKey.export(); throw new Error('Unsupported dataKey type'); } exports.unwrapDataKey = unwrapDataKey; function wrapWithKeyObjectIfSupported(dataKey) { if (exports.supportsKeyObject) { if (dataKey instanceof Uint8Array) { const ko = exports.supportsKeyObject.createSecretKey(dataKey); /* Postcondition: Zero the secret. It is now inside the KeyObject. */ dataKey.fill(0); return ko; } if (dataKey instanceof exports.supportsKeyObject.KeyObject) return dataKey; } else if (dataKey instanceof Uint8Array) { return dataKey; } throw new Error('Unsupported dataKey type'); } exports.wrapWithKeyObjectIfSupported = wrapWithKeyObjectIfSupported; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY3J5cHRvZ3JhcGhpY19tYXRlcmlhbC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9jcnlwdG9ncmFwaGljX21hdGVyaWFsLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7QUFXdEMsNkRBQXVEO0FBQ3ZELG1EQUErRDtBQUMvRCx1REFBaUU7QUFDakUsbURBQWdFO0FBQ2hFLHVEQUFzRDtBQUN0RCxtRUFBaUU7QUFDakUsbUNBQStCO0FBZWxCLFFBQUEsaUJBQWlCLEdBQUcsQ0FBQztJQUNoQyxJQUFJO1FBQ0YsTUFBTSxFQUFFLFNBQVMsRUFBRSxlQUFlLEVBQUUsR0FBRyxPQUFPLENBQUMsUUFBUSxDQUFrQixDQUFBLENBQUMseURBQXlEO1FBQ25JLElBQUksQ0FBQyxTQUFTLElBQUksQ0FBQyxlQUFlO1lBQUUsT0FBTyxLQUFLLENBQUE7UUFFaEQsT0FBTyxFQUFFLFNBQVMsRUFBRSxlQUFlLEVBQUUsQ0FBQTtLQUN0QztJQUFDLE9BQU8sRUFBRSxFQUFFO1FBQ1gsT0FBTyxLQUFLLENBQUE7S0FDYjtBQUNILENBQUMsQ0FBQyxFQUFFLENBQUE7QUFFSjs7Ozs7Ozs7Ozs7Ozs7O0dBZUc7QUFFSCxNQUFNLG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UQsU0FBZ0IsNEJBQTRCLENBQzFDLE9BQXNDO0lBRXRDLElBQUkseUJBQWlCLEVBQUU7UUFDckIsSUFBSSxPQUFPLFlBQVksVUFBVSxFQUFFO1lBQ2pDLE1BQU0sRUFBRSxHQUFHLHlCQUFpQixDQUFDLGVBQWUsQ0FBQyxPQUFPLENBQUMsQ0FBQTtZQUNyRCxzRUFBc0U7WUFDdEUsT0FBTyxDQUFDLElBQUksQ0FBQyxDQUFDLENBQUMsQ0FBQTtZQUNmLE9BQU8sRUFBRSxDQUFBO1NBQ1Y7UUFDRCxJQUFJLE9BQU8sWUFBWSx5QkFBaUIsQ0FBQyxTQUFTO1lBQUUsT0FBTyxPQUFPLENBQUE7S0FDbkU7U0FBTSxJQUFJLE9BQU8sWUFBWSxVQUFVLEVBQUU7UUFDeEMsT0FBTyxPQUFPLENBQUE7S0FDZjtJQUNELE1BQU0sSUFBSSxLQUFLLENBQUMsMEJBQTBCLENBQUMsQ0FBQTtBQUM3QyxDQUFDO0FBZkQsb0VBZUMifQ== /***/ }), /***/ 26601: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.decodeNamedCurves = void 0; const bn_js_1 = __importDefault(__nccwpck_require__(6641)); const needs_1 = __nccwpck_require__(91846); const prime256v1 = eccDecodeCompressedPoint(new bn_js_1.default('FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF', 16), new bn_js_1.default('FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC', 16), new bn_js_1.default('5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B', 16) // new BN('FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551', 16) ); const secp384r1 = eccDecodeCompressedPoint(new bn_js_1.default('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF', 16), new bn_js_1.default('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC', 16), new bn_js_1.default('B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF', 16) // new BN('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973', 16) ); exports.decodeNamedCurves = Object.freeze({ // NodeJS/OpenSSL names prime256v1, secp384r1, // WebCrypto/Browser names 'P-256': prime256v1, 'P-384': secp384r1, }); /* * 1. This only works for prime curves * 2. This will not handle the point at infinity */ function eccDecodeCompressedPoint(p, a, b /*, order: BN */) { const zero = new bn_js_1.default(0); const one = new bn_js_1.default(1); const two = new bn_js_1.default(2); const three = new bn_js_1.default(3); const four = new bn_js_1.default(4); // # Only works for p % 4 == 3 at this time. // # This is the case for all currently supported algorithms. // # This will need to be expanded if curves which do not match this are added. // # Python-ecdsa has these algorithms implemented. Copy or reference? // # https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm // # Handbook of Applied Cryptography, algorithms 3.34 - 3.39 (0, needs_1.needs)(p.mod(four).eq(three), 'Curve not supported at this time'); const montP = bn_js_1.default.mont(p); const redPow = p.add(one).div(four); const yOrderMap = { 2: zero, 3: one, }; const compressedLength = 1 + p.bitLength() / 8; return function decode(compressedPoint) { /* Precondition: compressedPoint must be the correct length. */ (0, needs_1.needs)(compressedPoint.byteLength === compressedLength, 'Compressed point length is not correct.'); const xBuff = compressedPoint.slice(1); const keyLength = xBuff.byteLength; const x = new bn_js_1.default([...xBuff]); const yOrder = yOrderMap[compressedPoint[0]]; const x3 = x.pow(three).mod(p); const ax = a.mul(x).mod(p); const alpha = x3.add(ax).add(b).mod(p); const beta = alpha.toRed(montP).redPow(redPow).fromRed(); if (beta.mod(two).eq(yOrder)) { const y = beta; return returnBuffer(x, y, keyLength); } else { const y = p.sub(beta); return returnBuffer(x, y, keyLength); } }; } function returnBuffer(x, y, keyLength) { return new Uint8Array([ 4, ...x.toArray('be', keyLength), ...y.toArray('be', keyLength), ]); } //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZWNjX2RlY29kZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9lY2NfZGVjb2RlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7Ozs7QUFFdEMsa0RBQXNCO0FBRXRCLG1DQUErQjtBQUUvQixNQUFNLFVBQVUsR0FBRyx3QkFBd0IsQ0FDekMsSUFBSSxlQUFFLENBQ0osa0VBQWtFLEVBQ2xFLEVBQUUsQ0FDSCxFQUNELElBQUksZUFBRSxDQUNKLGtFQUFrRSxFQUNsRSxFQUFFLENBQ0gsRUFDRCxJQUFJLGVBQUUsQ0FBQyxrRUFBa0UsRUFBRSxFQUFFLENBQUM7QUFDOUUsaUZBQWlGO0NBQ2xGLENBQUE7QUFDRCxNQUFNLFNBQVMsR0FBRyx3QkFBd0IsQ0FDeEMsSUFBSSxlQUFFLENBQ0osa0dBQWtHLEVBQ2xHLEVBQUUsQ0FDSCxFQUNELElBQUksZUFBRSxDQUNKLGtHQUFrRyxFQUNsRyxFQUFFLENBQ0gsRUFDRCxJQUFJLGVBQUUsQ0FDSixrR0FBa0csRUFDbEcsRUFBRSxDQUNIO0FBQ0QsaUhBQWlIO0NBQ2xILENBQUE7QUFPWSxRQUFBLGlCQUFpQixHQUFnQyxNQUFNLEN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UMsS0FBSyxDQUFDLENBQUMsTUFBTSxDQUFDLE1BQU0sQ0FBQyxDQUFDLE9BQU8sRUFBRSxDQUFBO1FBQ3hELElBQUksSUFBSSxDQUFDLEdBQUcsQ0FBQyxHQUFHLENBQUMsQ0FBQyxFQUFFLENBQUMsTUFBTSxDQUFDLEVBQUU7WUFDNUIsTUFBTSxDQUFDLEdBQUcsSUFBSSxDQUFBO1lBQ2QsT0FBTyxZQUFZLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxTQUFTLENBQUMsQ0FBQTtTQUNyQzthQUFNO1lBQ0wsTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFDLEdBQUcsQ0FBQyxJQUFJLENBQUMsQ0FBQTtZQUNyQixPQUFPLFlBQVksQ0FBQyxDQUFDLEVBQUUsQ0FBQyxFQUFFLFNBQVMsQ0FBQyxDQUFBO1NBQ3JDO0lBQ0gsQ0FBQyxDQUFBO0FBQ0gsQ0FBQztBQUVELFNBQVMsWUFBWSxDQUFDLENBQUssRUFBRSxDQUFLLEVBQUUsU0FBaUI7SUFDbkQsT0FBTyxJQUFJLFVBQVUsQ0FBQztRQUNwQixDQUFDO1FBQ0QsR0FBRyxDQUFDLENBQUMsT0FBTyxDQUFDLElBQUksRUFBRSxTQUFTLENBQUM7UUFDN0IsR0FBRyxDQUFDLENBQUMsT0FBTyxDQUFDLElBQUksRUFBRSxTQUFTLENBQUM7S0FDOUIsQ0FBQyxDQUFBO0FBQ0osQ0FBQyJ9 /***/ }), /***/ 97659: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.encodeNamedCurves = void 0; const bn_js_1 = __importDefault(__nccwpck_require__(6641)); const needs_1 = __nccwpck_require__(91846); const prime256v1 = eccEncodeCompressedPoint(32); const secp384r1 = eccEncodeCompressedPoint(48); exports.encodeNamedCurves = Object.freeze({ // NodeJS/OpenSSL names prime256v1, secp384r1, // WebCrypto/Browser names 'P-256': prime256v1, 'P-384': secp384r1, }); /* * 1. This only works for prime curves * 2. This will not handle the point at infinity */ function eccEncodeCompressedPoint(keyLength) { return function encode(publicKey) { /* Precondition: publicKey must be the right length. * The format for the public key is [type, ...keyLength, ...keyLength] */ (0, needs_1.needs)(publicKey.byteLength === 1 + keyLength * 2, 'Malformed public key.'); // const type = publicKey[0] const x = publicKey.slice(1, keyLength + 1); const y = publicKey.slice(keyLength + 1, keyLength * 2 + 1); const yOrder = new bn_js_1.default([...y]).mod(new bn_js_1.default(2)).toNumber() + 2; const compressPoint = new Uint8Array(1 + x.length); compressPoint.set([yOrder], 0); compressPoint.set(x, 1); return compressPoint; }; } //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZWNjX2VuY29kZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9lY2NfZW5jb2RlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7Ozs7QUFFdEMsa0RBQXNCO0FBRXRCLG1DQUErQjtBQUUvQixNQUFNLFVBQVUsR0FBRyx3QkFBd0IsQ0FBQyxFQUFFLENBQUMsQ0FBQTtBQUMvQyxNQUFNLFNBQVMsR0FBRyx3QkFBd0IsQ0FBQyxFQUFFLENBQUMsQ0FBQTtBQVFqQyxRQUFBLGlCQUFpQixHQUFnQyxNQUFNLENBQUMsTUFBTSxDQUFDO0lBQzFFLHVCQUF1QjtJQUN2QixVQUFVO0lBQ1YsU0FBUztJQUNULDBCQUEwQjtJQUMxQixPQUFPLEVBQUUsVUFBVTtJQUNuQixPQUFPLEVBQUUsU0FBUztDQUNuQixDQUFDLENBQUE7QUFFRjs7O0d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rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.EncryptedDataKey = void 0; const immutable_class_1 = __nccwpck_require__(32746); const needs_1 = __nccwpck_require__(91846); class EncryptedDataKey { constructor(edkInput) { const { providerInfo, providerId, encryptedDataKey, rawInfo } = edkInput; (0, needs_1.needs)(typeof providerInfo === 'string' && providerInfo && typeof providerId === 'string' && providerId && encryptedDataKey instanceof Uint8Array && encryptedDataKey.byteLength, 'Malformed encrypted data key'); (0, immutable_class_1.readOnlyProperty)(this, 'providerInfo', providerInfo); (0, immutable_class_1.readOnlyProperty)(this, 'providerId', providerId); (0, immutable_class_1.readOnlyBinaryProperty)(this, 'encryptedDataKey', encryptedDataKey); if (rawInfo instanceof Uint8Array) { (0, immutable_class_1.readOnlyBinaryProperty)(this, 'rawInfo', rawInfo); } else { (0, immutable_class_1.readOnlyProperty)(this, 'rawInfo', undefined); } Object.setPrototypeOf(this, EncryptedDataKey.prototype); Object.freeze(this); } } exports.EncryptedDataKey = EncryptedDataKey; (0, immutable_class_1.frozenClass)(EncryptedDataKey); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW5jcnlwdGVkX2RhdGFfa2V5LmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL2VuY3J5cHRlZF9kYXRhX2tleS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUEsb0VBQW9FO0FBQ3BFLHNDQUFzQzs7O0FBRXRDLHVEQUkwQjtBQUMxQixtQ0FBK0I7QUFnQy9CLE1BQWEsZ0JBQWdCO0lBTTNCLFlBQVksUUFBMkI7UUFDckMsTUFBTSxFQUFFLFlBQVksRUFBRSxVQUFVLEVBQUUsZ0JBQWdCLEVBQUUsT0FBTyxFQUFFLEdBQUcsUUFBUSxDQUFBO1FBQ3hFLElBQUEsYUFBSyxFQUNILE9BQU8sWUFBWSxLQUFLLFFBQVE7WUFDOUIsWUFBWTtZQUNaLE9BQU8sVUFBVSxLQUFLLFFBQVE7WUFDOUIsVUFBVTtZQUNWLGdCQUFnQixZQUFZLFVBQVU7WUFDdEMsZ0JBQWdCLENBQUMsVUFBVSxFQUM3Qiw4QkFBOEIsQ0FDL0IsQ0FBQTtRQUVELElBQUEsa0NBQWdCLEVBQUMsSUFBSSxFQUFFLGNBQWMsRUFBRSxZQUFZLENBQUMsQ0FBQTtRQUNwRCxJQUFBLGtDQUFnQixFQUFDLElBQUksRUFBRSxZQUFZLEVBQUUsVUFBVSxDQUFDLENBQUE7UUFDaEQsSUFBQSx3Q0FBc0IsRUFBQyxJQUFJLEVBQUUsa0JBQWtCLEVBQUUsZ0JBQWdCLENBQUMsQ0FBQTtRQUNsRSxJQUFJLE9BQU8sWUFBWSxVQUFVLEVBQUU7WUFDakMsSUFBQSx3Q0FBc0IsRUFBQyxJQUFJLEVBQUUsU0FBUyxFQUFFLE9BQU8sQ0FBQyxDQUFBO1NBQ2pEO2FBQU07WUFDTCxJQUFBLGtDQUFnQixFQUFDLElBQUksRUFBRSxTQUFTLEVBQUUsU0FBUyxDQUFDLENBQUE7U0FDN0M7UUFFRCxNQUFNLENBQUMsY0FBYyxDQUFDLElBQUksRUFBRSxnQkFBZ0IsQ0FBQyxTQUFTLENBQUMsQ0FBQTtRQUN2RCxNQUFNLENBQUMsTUFBTSxDQUFDLElBQUksQ0FBQyxDQUFBO0lBQ3JCLENBQUM7Q0FDRjtBQTlCRCw0Q0E4QkM7QUFFRCxJQUFBLDZCQUFXLEVBQUMsZ0JBQWdCLENBQUMsQ0FBQSJ9 /***/ }), /***/ 84104: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NotSupported = void 0; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 class NotSupported extends Error { code; constructor(message) { super(message); Object.setPrototypeOf(this, NotSupported.prototype); this.code = 'NOT_SUPPORTED'; } } exports.NotSupported = NotSupported; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXJyb3IuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvZXJyb3IudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7O0FBQUEsb0VBQW9FO0FBQ3BFLHNDQUFzQztBQUN0QyxNQUFhLFlBQWEsU0FBUSxLQUFLO0lBQ3JDLElBQUksQ0FBUTtJQUVaLFlBQVksT0FBZ0I7UUFDMUIsS0FBSyxDQUFDLE9BQU8sQ0FBQyxDQUFBO1FBQ2QsTUFBTSxDQUFDLGNBQWMsQ0FBQyxJQUFJLEVBQUUsWUFBWSxDQUFDLFNBQVMsQ0FBQyxDQUFBO1FBQ25ELElBQUksQ0FBQyxJQUFJLEdBQUcsZUFBZSxDQUFBO0lBQzdCLENBQUM7Q0FDRjtBQVJELG9DQVFDIn0= /***/ }), /***/ 32746: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.readOnlyProperty = exports.readOnlyBinaryProperty = exports.frozenClass = exports.immutableBaseClass = exports.immutableClass = void 0; function immutableClass(ObjectClass) { Object.freeze(ObjectClass); const propertyNames = Object.getOwnPropertyNames(ObjectClass.prototype); propertyNames .filter((name) => name !== 'constructor') .forEach((name) => Object.defineProperty(ObjectClass.prototype, name, { writable: false })); Object.seal(ObjectClass.prototype); return ObjectClass; } exports.immutableClass = immutableClass; function immutableBaseClass(ObjectClass) { Object.setPrototypeOf(ObjectClass.prototype, null); immutableClass(ObjectClass); return ObjectClass; } exports.immutableBaseClass = immutableBaseClass; function frozenClass(ObjectClass) { Object.setPrototypeOf(ObjectClass.prototype, null); Object.freeze(ObjectClass.prototype); Object.freeze(ObjectClass); return ObjectClass; } exports.frozenClass = frozenClass; function readOnlyBinaryProperty(obj, name, value) { // should this also add a zero property? // and should it create a local value? maybe not. const safeValue = new Uint8Array(value); Object.defineProperty(obj, name, { get: () => new Uint8Array(safeValue), enumerable: true, }); } exports.readOnlyBinaryProperty = readOnlyBinaryProperty; function readOnlyProperty(obj, name, value) { Object.defineProperty(obj, name, { value, enumerable: true, writable: false }); } exports.readOnlyProperty = readOnlyProperty; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW1tdXRhYmxlX2NsYXNzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL2ltbXV0YWJsZV9jbGFzcy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUEsb0VBQW9FO0FBQ3BFLHNDQUFzQzs7O0FBRXRDLFNBQWdCLGNBQWMsQ0FBQyxXQUFnQjtJQUM3QyxNQUFNLENBQUMsTUFBTSxDQUFDLFdBQVcsQ0FBQyxDQUFBO0lBQzFCLE1BQU0sYUFBYSxHQUFHLE1BQU0sQ0FBQyxtQkFBbUIsQ0FBQyxXQUFXLENBQUMsU0FBUyxDQUFDLENBQUE7SUFDdkUsYUFBYTtTQUNWLE1BQU0sQ0FBQyxDQUFDLElBQUksRUFBRSxFQUFFLENBQUMsSUFBSSxLQUFLLGFBQWEsQ0FBQztTQUN4QyxPQUFPLENBQUMsQ0FBQyxJQUFJLEVBQUUsRUFBRSxDQUNoQixNQUFNLENBQUMsY0FBYyxDQUFDLFdBQVcsQ0FBQyxTQUFTLEVBQUUsSUFBSSxFQUFFLEVBQUUsUUFBUSxFQUFFLEtBQUssRUFBRSxDQUFDLENBQ3hFLENBQUE7SUFDSCxNQUFNLENBQUMsSUFBSSxDQUFDLFdBQVcsQ0FBQyxTQUFTLENBQUMsQ0FBQTtJQUNsQyxPQUFPLFdBQVcsQ0FBQTtBQUNwQixDQUFDO0FBVkQsd0NBVUM7QUFFRCxTQUFnQixrQ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ElBQUksRUFBRSxRQUFRLEVBQUUsS0FBSyxFQUFFLENBQUMsQ0FBQTtBQUNoRixDQUFDO0FBTkQsNENBTUMifQ== /***/ }), /***/ 77519: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 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.NotSupported = exports.cloneMaterial = exports.needs = exports.readOnlyProperty = exports.frozenClass = exports.immutableClass = exports.immutableBaseClass = exports.EncryptedDataKey = exports.VerificationKey = exports.SignatureKey = exports.decorateWebCryptoMaterial = exports.decorateCryptographicMaterial = exports.wrapWithKeyObjectIfSupported = exports.unwrapDataKey = exports.isDecryptionMaterial = exports.isEncryptionMaterial = exports.WebCryptoDecryptionMaterial = exports.WebCryptoEncryptionMaterial = exports.subtleFunctionForMaterial = exports.keyUsageForMaterial = exports.isCryptoKey = exports.isValidCryptoKey = exports.NodeDecryptionMaterial = exports.NodeEncryptionMaterial = exports.MultiKeyringWebCrypto = exports.MultiKeyringNode = exports.KeyringTraceFlag = exports.NodeAlgorithmSuite = exports.WebCryptoAlgorithmSuite = exports.CommittingAlgorithmSuiteIdentifier = exports.NonCommittingAlgorithmSuiteIdentifier = exports.MessageFormat = exports.SignaturePolicySuites = exports.SignaturePolicy = exports.CommitmentPolicySuites = exports.CommitmentPolicy = exports.AlgorithmSuite = exports.AlgorithmSuiteIdentifier = void 0; var algorithm_suites_1 = __nccwpck_require__(79993); Object.defineProperty(exports, "AlgorithmSuiteIdentifier", ({ enumerable: true, get: function () { return algorithm_suites_1.AlgorithmSuiteIdentifier; } })); Object.defineProperty(exports, "AlgorithmSuite", ({ enumerable: true, get: function () { return algorithm_suites_1.AlgorithmSuite; } })); Object.defineProperty(exports, "CommitmentPolicy", ({ enumerable: true, get: function () { return algorithm_suites_1.CommitmentPolicy; } })); Object.defineProperty(exports, "CommitmentPolicySuites", ({ enumerable: true, get: function () { return algorithm_suites_1.CommitmentPolicySuites; } })); Object.defineProperty(exports, "SignaturePolicy", ({ enumerable: true, get: function () { return algorithm_suites_1.SignaturePolicy; } })); Object.defineProperty(exports, "SignaturePolicySuites", ({ enumerable: true, get: function () { return algorithm_suites_1.SignaturePolicySuites; } })); Object.defineProperty(exports, "MessageFormat", ({ enumerable: true, get: function () { return algorithm_suites_1.MessageFormat; } })); Object.defineProperty(exports, "NonCommittingAlgorithmSuiteIdentifier", ({ enumerable: true, get: function () { return algorithm_suites_1.NonCommittingAlgorithmSuiteIdentifier; } })); Object.defineProperty(exports, "CommittingAlgorithmSuiteIdentifier", ({ enumerable: true, get: function () { return algorithm_suites_1.CommittingAlgorithmSuiteIdentifier; } })); var web_crypto_algorithms_1 = __nccwpck_require__(28311); Object.defineProperty(exports, "WebCryptoAlgorithmSuite", ({ enumerable: true, get: function () { return web_crypto_algorithms_1.WebCryptoAlgorithmSuite; } })); var node_algorithms_1 = __nccwpck_require__(79966); Object.defineProperty(exports, "NodeAlgorithmSuite", ({ enumerable: true, get: function () { return node_algorithms_1.NodeAlgorithmSuite; } })); __exportStar(__nccwpck_require__(78033), exports); var keyring_trace_1 = __nccwpck_require__(24530); Object.defineProperty(exports, "KeyringTraceFlag", ({ enumerable: true, get: function () { return keyring_trace_1.KeyringTraceFlag; } })); var multi_keyring_1 = __nccwpck_require__(68417); Object.defineProperty(exports, "MultiKeyringNode", ({ enumerable: true, get: function () { return multi_keyring_1.MultiKeyringNode; } })); Object.defineProperty(exports, "MultiKeyringWebCrypto", ({ enumerable: true, get: function () { return multi_keyring_1.MultiKeyringWebCrypto; } })); __exportStar(__nccwpck_require__(82617), exports); var cryptographic_material_1 = __nccwpck_require__(91301); Object.defineProperty(exports, "NodeEncryptionMaterial", ({ enumerable: true, get: function () { return cryptographic_material_1.NodeEncryptionMaterial; } })); Object.defineProperty(exports, "NodeDecryptionMaterial", ({ enumerable: true, get: function () { return cryptographic_material_1.NodeDecryptionMaterial; } })); var cryptographic_material_2 = __nccwpck_require__(91301); Object.defineProperty(exports, "isValidCryptoKey", ({ enumerable: true, get: function () { return cryptographic_material_2.isValidCryptoKey; } })); Object.defineProperty(exports, "isCryptoKey", ({ enumerable: true, get: function () { return cryptographic_material_2.isCryptoKey; } })); Object.defineProperty(exports, "keyUsageForMaterial", ({ enumerable: true, get: function () { return cryptographic_material_2.keyUsageForMaterial; } })); Object.defineProperty(exports, "subtleFunctionForMaterial", ({ enumerable: true, get: function () { return cryptographic_material_2.subtleFunctionForMaterial; } })); var cryptographic_material_3 = __nccwpck_require__(91301); Object.defineProperty(exports, "WebCryptoEncryptionMaterial", ({ enumerable: true, get: function () { return cryptographic_material_3.WebCryptoEncryptionMaterial; } })); Object.defineProperty(exports, "WebCryptoDecryptionMaterial", ({ enumerable: true, get: function () { return cryptographic_material_3.WebCryptoDecryptionMaterial; } })); var cryptographic_material_4 = __nccwpck_require__(91301); Object.defineProperty(exports, "isEncryptionMaterial", ({ enumerable: true, get: function () { return cryptographic_material_4.isEncryptionMaterial; } })); Object.defineProperty(exports, "isDecryptionMaterial", ({ enumerable: true, get: function () { return cryptographic_material_4.isDecryptionMaterial; } })); var cryptographic_material_5 = __nccwpck_require__(91301); Object.defineProperty(exports, "unwrapDataKey", ({ enumerable: true, get: function () { return cryptographic_material_5.unwrapDataKey; } })); Object.defineProperty(exports, "wrapWithKeyObjectIfSupported", ({ enumerable: true, get: function () { return cryptographic_material_5.wrapWithKeyObjectIfSupported; } })); var cryptographic_material_6 = __nccwpck_require__(91301); Object.defineProperty(exports, "decorateCryptographicMaterial", ({ enumerable: true, get: function () { return cryptographic_material_6.decorateCryptographicMaterial; } })); Object.defineProperty(exports, "decorateWebCryptoMaterial", ({ enumerable: true, get: function () { return cryptographic_material_6.decorateWebCryptoMaterial; } })); var signature_key_1 = __nccwpck_require__(80872); Object.defineProperty(exports, "SignatureKey", ({ enumerable: true, get: function () { return signature_key_1.SignatureKey; } })); Object.defineProperty(exports, "VerificationKey", ({ enumerable: true, get: function () { return signature_key_1.VerificationKey; } })); var encrypted_data_key_1 = __nccwpck_require__(30466); Object.defineProperty(exports, "EncryptedDataKey", ({ enumerable: true, get: function () { return encrypted_data_key_1.EncryptedDataKey; } })); var immutable_class_1 = __nccwpck_require__(32746); Object.defineProperty(exports, "immutableBaseClass", ({ enumerable: true, get: function () { return immutable_class_1.immutableBaseClass; } })); Object.defineProperty(exports, "immutableClass", ({ enumerable: true, get: function () { return immutable_class_1.immutableClass; } })); Object.defineProperty(exports, "frozenClass", ({ enumerable: true, get: function () { return immutable_class_1.frozenClass; } })); Object.defineProperty(exports, "readOnlyProperty", ({ enumerable: true, get: function () { return immutable_class_1.readOnlyProperty; } })); var needs_1 = __nccwpck_require__(91846); Object.defineProperty(exports, "needs", ({ enumerable: true, get: function () { return needs_1.needs; } })); var clone_cryptographic_material_1 = __nccwpck_require__(3821); Object.defineProperty(exports, "cloneMaterial", ({ enumerable: true, get: function () { return clone_cryptographic_material_1.cloneMaterial; } })); __exportStar(__nccwpck_require__(50479), exports); var error_1 = __nccwpck_require__(84104); Object.defineProperty(exports, "NotSupported", ({ enumerable: true, get: function () { return error_1.NotSupported; } })); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwa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QUFGL0IsdUhBQUEsYUFBYSxPQUFBO0FBQ2Isc0lBQUEsNEJBQTRCLE9BQUE7QUFFOUIsbUVBS2lDO0FBSC9CLHVJQUFBLDZCQUE2QixPQUFBO0FBQzdCLG1JQUFBLHlCQUF5QixPQUFBO0FBRzNCLGlEQUErRDtBQUF0RCw2R0FBQSxZQUFZLE9BQUE7QUFBRSxnSEFBQSxlQUFlLE9BQUE7QUFDdEMsMkRBQTBFO0FBQWpFLHNIQUFBLGdCQUFnQixPQUFBO0FBRXpCLHFEQUswQjtBQUp4QixxSEFBQSxrQkFBa0IsT0FBQTtBQUNsQixpSEFBQSxjQUFjLE9BQUE7QUFDZCw4R0FBQSxXQUFXLE9BQUE7QUFDWCxtSEFBQSxnQkFBZ0IsT0FBQTtBQUdsQixpQ0FBK0I7QUFBdEIsOEZBQUEsS0FBSyxPQUFBO0FBQ2QsK0VBQThEO0FBQXJELDZIQUFBLGFBQWEsT0FBQTtBQUV0QiwwQ0FBdUI7QUFDdkIsaUNBQXNDO0FBQTdCLHFHQUFBLFlBQVksT0FBQSJ9 /***/ }), /***/ 78033: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.KeyringWebCrypto = exports.KeyringNode = exports.Keyring = void 0; const encrypted_data_key_1 = __nccwpck_require__(30466); const immutable_class_1 = __nccwpck_require__(32746); const cryptographic_material_1 = __nccwpck_require__(91301); const needs_1 = __nccwpck_require__(91846); /* * This public interface to the Keyring object is provided for * developers of CMMs and keyrings only. If you are a user of the AWS Encryption * SDK and you are not developing your own CMMs and/or keyrings, you do not * need to use it and you should not do so. */ class Keyring { async onEncrypt(material) { /* Precondition: material must be a type of isEncryptionMaterial. * There are several security properties that NodeEncryptionMaterial and WebCryptoEncryptionMaterial * posses. * The unencryptedDataKey can only be written once. * If a data key has not already been generated, there must be no EDKs. * See cryptographic_materials.ts */ (0, needs_1.needs)((0, cryptographic_material_1.isEncryptionMaterial)(material), 'Unsupported type of material.'); const _material = await this._onEncrypt(material); /* Postcondition: The EncryptionMaterial objects must be the same. * See cryptographic_materials.ts. The CryptographicMaterial objects * provide several security properties, including immutability of * the unencrypted data key and the ability to zero the data key. * This is insured by returning the same material. */ (0, needs_1.needs)(material === _material, 'New EncryptionMaterial instances can not be created.'); /* Postcondition UNTESTED: If this keyring generated data key, it must be the right length. * See cryptographic_materials.ts This is handled in setUnencryptedDataKey * this condition is listed here to keep help keep track of important conditions */ return material; } /* NOTE: The order of EDK's passed to the onDecrypt function is a clear * intent on the part of the person who did the encryption. * The EDK's should always correspond to the order serialized. * It is the Keyrings responsibility to maintain this order. * The most clear example is from KMS. KMS is a regional service. * This means that a call to decrypt an EDK must go to the * region that "owns" this EDK. If the decryption is done * in a different region. To control this behavior the person * who called encrypt can control the order of EDK and in the * configuration of the KMS Keyring. */ async onDecrypt(material, encryptedDataKeys) { /* Precondition: material must be DecryptionMaterial. */ (0, needs_1.needs)((0, cryptographic_material_1.isDecryptionMaterial)(material), 'Unsupported material type.'); /* Precondition: Attempt to decrypt iif material does not have an unencrypted data key. */ if (material.hasValidKey()) return material; /* Precondition: encryptedDataKeys must all be EncryptedDataKey. */ (0, needs_1.needs)(encryptedDataKeys.every((edk) => edk instanceof encrypted_data_key_1.EncryptedDataKey), 'Unsupported EncryptedDataKey type'); const _material = await this._onDecrypt(material, encryptedDataKeys); /* Postcondition: The DecryptionMaterial objects must be the same. * See cryptographic_materials.ts. The CryptographicMaterial objects * provide several security properties, including immutability of * the unencrypted data key and the ability to zero the data key. * This is insured by returning the same material. */ (0, needs_1.needs)(material === _material, 'New DecryptionMaterial instances can not be created.'); /* See cryptographic_materials.ts The length condition is handled there. * But the condition is important and so repeated here. * The postcondition is "If an EDK was decrypted, its length must agree with algorithm specification." * If this is not the case, it either means ciphertext was tampered * with or the keyring implementation is not setting the length properly. */ return material; } } exports.Keyring = Keyring; (0, immutable_class_1.immutableBaseClass)(Keyring); class KeyringNode extends Keyring { } exports.KeyringNode = KeyringNode; (0, immutable_class_1.immutableClass)(KeyringNode); class KeyringWebCrypto extends Keyring { } exports.KeyringWebCrypto = KeyringWebCrypto; (0, immutable_class_1.immutableClass)(KeyringWebCrypto); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoia2V5cmluZy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9rZXlyaW5nLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7QUFFdEMsNkRBQXVEO0FBQ3ZELHVEQUFzRTtBQUV0RSxxRUFHaUM7QUFNakMsbUNBQStCO0FBSS9COzs7OztHQUtHO0FBRUgsTUFBc0IsT0FBTztJQUMzQixLQUFLLENBQUMsU0FBUyxDQUNiLFFBQStCO1FBRS9COzs7Ozs7V0FNRztRQUNILElBQUEsYUFBSyxFQUFDLElBQUEsNkNBQW9CLEVBQUMsUUFBUSxDQUFDLEVBQUUsK0JBQStCLENBQUMsQ0FBQTtRQUV0RSxNQUFNLFNBQVMsR0FBRyxNQUFNLElBQUksQ0FBQyxVQUFVLENBQUMsUUFBUSxDQUFDLENBQUE7UUFFakQ7Ozs7O1dBS0c7UUFDSCxJQUFBLGFBQUssRUFDSCxRQUFRLEtBQUssU0FBUyxFQUN0QixzREFBc0QsQ0FDdkQsQ0FBQTtRQUVEOzs7V0FHRztRQUVILE9BQU8sUUFBUSxDQUFBO0lBQ2pCLENBQUM7SUFNRDs7Ozs7Ozs7OztPQVVHO0lBQ0gsS0FBSyxDQUFDLFNBQVMsQ0FDYixRQUErQixFQUMvQixpQkFBcUM7UUFFckMsd0RBQXdEO1FBQ3hELElBQUEsYUFBSyxFQUFDLElBQUEsNkNBQW9CLEVBQUMsUUFBUSxDQUFDLEVBQUUsNEJBQTRCLENBQUMsQ0FBQTtRQUVuRSwwRkFBMEY7UUFDMUYsSUFBSSxRQUFRLENBQUMsV0FBVyxFQUFFO1lBQUUsT0FBTyxRQUFRLENBQUE7UUFFM0MsbUVBQW1FO1FBQ25FLElBQUEsYUFBSyxFQUNILGlCQUFpQixDQUFDLEtBQUssQ0FBQyxDQUFDLEdBQUcsRUFBRSxFQUFFLENBQUMsR0FBRyxZQUFZLHFDQUFnQixDQUFDLEVBQ2pFLG1DQUFtQyxDQUNwQyxDQUFBO1FBRUQsTUFBTSxTQUFTLEdBQUcsTUFBTSxJQUFJLENBQUMsVUFBVSxDQUFDLFFBQVEsRUFBRSxpQkFBaUIsQ0FBQyxDQUFBO1FBRXBFOzs7OztXQUtHO1FBQ0gsSUFBQSxhQUFLLEVBQ0gsUUFBUSxLQUFLLFNBQVMsRUFDdEIsc0RBQXNELENBQ3ZELENBQUE7UUFFRDs7Ozs7V0FLRztRQUVILE9BQU8sUUFBUSxDQUFBO0lBQ2pCLENBQUM7Q0FNRjtBQTVGRCwwQkE0RkM7QUFFRCxJQUFBLG9DQUFrQixFQUFDLE9BQU8sQ0FBQyxDQUFBO0FBRTNCLE1BQXNCLFdBQVksU0FBUSxPQUEyQjtDQUFHO0FBQXhFLGtDQUF3RTtBQUN4RSxJQUFBLGdDQUFjLEVBQUMsV0FBVyxDQUFDLENBQUE7QUFDM0IsTUFBc0IsZ0JBQWlCLFNBQVEsT0FBZ0M7Q0FBRztBQUFsRiw0Q0FBa0Y7QUFDbEYsSUFBQSxnQ0FBYyxFQUFDLGdCQUFnQixDQUFDLENBQUEifQ== /***/ }), /***/ 24530: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.KeyringTraceFlag = void 0; var KeyringTraceFlag; (function (KeyringTraceFlag) { /** * Bit flag indicating this wrapping key generated the data key. */ KeyringTraceFlag[KeyringTraceFlag["WRAPPING_KEY_GENERATED_DATA_KEY"] = 1] = "WRAPPING_KEY_GENERATED_DATA_KEY"; /** * Bit flag indicating this wrapping key encrypted the data key. */ KeyringTraceFlag[KeyringTraceFlag["WRAPPING_KEY_ENCRYPTED_DATA_KEY"] = 2] = "WRAPPING_KEY_ENCRYPTED_DATA_KEY"; /** * Bit flag indicating this wrapping key decrypted the data key. */ KeyringTraceFlag[KeyringTraceFlag["WRAPPING_KEY_DECRYPTED_DATA_KEY"] = 4] = "WRAPPING_KEY_DECRYPTED_DATA_KEY"; /** * Bit flag indicating this wrapping key signed the encryption context. */ KeyringTraceFlag[KeyringTraceFlag["WRAPPING_KEY_SIGNED_ENC_CTX"] = 8] = "WRAPPING_KEY_SIGNED_ENC_CTX"; /** * Bit flag indicating this wrapping key verified the signature of the encryption context. */ KeyringTraceFlag[KeyringTraceFlag["WRAPPING_KEY_VERIFIED_ENC_CTX"] = 16] = "WRAPPING_KEY_VERIFIED_ENC_CTX"; /* KeyringTraceFlags are organized here. * The three groupings are set, encrypt, and decrypt. * An unencrypted data key is set and is required to have a SET_FLAG. * For the encrypt path, the unencrypted data key must be generated. * For the decrypt path, the unencrypted data key must be decrypted. * * A encrypted data key must be encrypted * and the encryption context may be signed. * * When an encrypted data key is decrypted, * the encryption context may be verified. * * This organization is to keep a KeyringTrace for an encrypted data key * for listing the WRAPPING_KEY_VERIFIED_ENC_CTX flag. */ KeyringTraceFlag[KeyringTraceFlag["ENCRYPT_FLAGS"] = 10] = "ENCRYPT_FLAGS"; KeyringTraceFlag[KeyringTraceFlag["SET_FLAGS"] = 5] = "SET_FLAGS"; KeyringTraceFlag[KeyringTraceFlag["DECRYPT_FLAGS"] = 20] = "DECRYPT_FLAGS"; })(KeyringTraceFlag = exports.KeyringTraceFlag || (exports.KeyringTraceFlag = {})); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoia2V5cmluZ190cmFjZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9rZXlyaW5nX3RyYWNlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7QUFvQ3RDLElBQVksZ0JBZ0RYO0FBaERELFdBQVksZ0JBQWdCO0lBQzFCOztPQUVHO0lBQ0gsNkdBQW1DLENBQUE7SUFFbkM7O09BRUc7SUFDSCw2R0FBd0MsQ0FBQTtJQUV4Qzs7T0FFRztJQUNILDZHQUF3QyxDQUFBO0lBRXhDOztPQUVHO0lBQ0gscUdBQW9DLENBQUE7SUFFcEM7O09BRUc7SUFDSCwwR0FBc0MsQ0FBQTtJQUV0Qzs7Ozs7Ozs7Ozs7Ozs7T0FjRztJQUVILDBFQUE2RSxDQUFBO0lBRTdFLGlFQUE2RSxDQUFBO0lBRTdFLDBFQUMrQixDQUFBO0FBQ2pDLENBQUMsRUFoRFcsZ0JBQWdCLEdBQWhCLHdCQUFnQixLQUFoQix3QkFBZ0IsUUFnRDNCIn0= /***/ }), /***/ 82617: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWF0ZXJpYWxzX21hbmFnZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvbWF0ZXJpYWxzX21hbmFnZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0MifQ== /***/ }), /***/ 68417: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MultiKeyringWebCrypto = exports.MultiKeyringNode = void 0; const immutable_class_1 = __nccwpck_require__(32746); const keyring_1 = __nccwpck_require__(78033); const needs_1 = __nccwpck_require__(91846); class MultiKeyringNode extends keyring_1.KeyringNode { generator; children; constructor(input) { super(); decorateProperties(this, keyring_1.KeyringNode, input); } _onEncrypt = buildPrivateOnEncrypt(); _onDecrypt = buildPrivateOnDecrypt(); } exports.MultiKeyringNode = MultiKeyringNode; (0, immutable_class_1.immutableClass)(MultiKeyringNode); class MultiKeyringWebCrypto extends keyring_1.KeyringWebCrypto { constructor(input) { super(); decorateProperties(this, keyring_1.KeyringWebCrypto, input); } _onEncrypt = buildPrivateOnEncrypt(); _onDecrypt = buildPrivateOnDecrypt(); } exports.MultiKeyringWebCrypto = MultiKeyringWebCrypto; (0, immutable_class_1.immutableClass)(MultiKeyringWebCrypto); function decorateProperties(obj, BaseKeyring, { generator, children = [] }) { /* Precondition: MultiKeyring must have keyrings. */ (0, needs_1.needs)(generator || children.length, 'Noop MultiKeyring is not supported.'); /* Precondition: generator must be a Keyring. */ (0, needs_1.needs)(!!generator === generator instanceof BaseKeyring, 'Generator must be a Keyring'); /* Precondition: All children must be Keyrings. */ (0, needs_1.needs)(children.every((kr) => kr instanceof BaseKeyring), 'Child must be a Keyring'); (0, immutable_class_1.readOnlyProperty)(obj, 'children', Object.freeze(children.slice())); (0, immutable_class_1.readOnlyProperty)(obj, 'generator', generator); } function buildPrivateOnEncrypt() { return async function _onEncrypt(material) { /* Precondition: Only Keyrings explicitly designated as generators can generate material. * Technically, the precondition below will handle this. * Since if I do not have an unencrypted data key, * and I do not have a generator, * then generated.hasUnencryptedDataKey === false will throw. * But this is a much more meaningful error. */ (0, needs_1.needs)(!material.hasUnencryptedDataKey ? this.generator : true, 'Only Keyrings explicitly designated as generators can generate material.'); const generated = this.generator ? await this.generator.onEncrypt(material) : material; /* Precondition: A Generator Keyring *must* ensure generated material. */ (0, needs_1.needs)(generated.hasUnencryptedDataKey, 'Generator Keyring has not generated material.'); /* By default this is a serial operation. A keyring _may_ perform an expensive operation * or create resource constraints such that encrypting with multiple keyrings could * fail in unexpected ways. * Additionally, "downstream" keyrings may make choices about the EncryptedDataKeys they * append based on already appended EDK's. */ for (const keyring of this.children) { await keyring.onEncrypt(generated); } // Keyrings are required to not create new EncryptionMaterial instances, but // only append EncryptedDataKey. Therefore the generated material has all // the data I want. return generated; }; } function buildPrivateOnDecrypt() { return async function _onDecrypt(material, encryptedDataKeys) { const children = this.children.slice(); if (this.generator) children.unshift(this.generator); const childKeyringErrors = []; for (const keyring of children) { /* Check for early return (Postcondition): Do not attempt to decrypt once I have a valid key. */ if (material.hasValidKey()) return material; try { await keyring.onDecrypt(material, encryptedDataKeys); } catch (e) { /* Failures onDecrypt should not short-circuit the process * If the caller does not have access they may have access * through another Keyring. */ childKeyringErrors.push({ errPlus: e }); } } /* Postcondition: A child keyring must provide a valid data key or no child keyring must have raised an error. * If I have a data key, * decrypt errors can be ignored. * However, if I was unable to decrypt a data key AND I have errors, * these errors should bubble up. * Otherwise, the only error customers will see is that * the material does not have an unencrypted data key. * So I return a concatenated Error message */ (0, needs_1.needs)(material.hasValidKey() || (!material.hasValidKey() && !childKeyringErrors.length), childKeyringErrors.reduce((m, e, i) => `${m} Error #${i + 1} \n ${e.errPlus.stack} \n`, 'Unable to decrypt data key and one or more child keyrings had an error. \n ')); return material; }; } //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibXVsdGlfa2V5cmluZy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9tdWx0aV9rZXlyaW5nLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7QUFFdEMsdURBQW9FO0FBQ3BFLHVDQUFrRTtBQU9sRSxtQ0FBK0I7QUFLL0IsTUFBYSxnQkFDWCxTQUFRLHFCQUFXO0lBR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VBQUUsRUFBRSxDQUFDLEdBQUcsQ0FBQyxXQUFXLENBQUMsR0FBRyxDQUFDLE9BQU8sQ0FBQyxDQUFDLE9BQU8sQ0FBQyxLQUFLLEtBQUssRUFDNUQsNkVBQTZFLENBQzlFLENBQ0YsQ0FBQTtRQUVELE9BQU8sUUFBUSxDQUFBO0lBQ2pCLENBQUMsQ0FBQTtBQUNILENBQUMifQ== /***/ }), /***/ 91846: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.needs = void 0; /* Preconditions, postconditions, and loop invariants are very * useful for safe programing. They also document the specifications. * This function is to help simplify the semantic burden of parsing * these constructions. * * Instead of constructions like * if (!goodCondition) throw new Error('condition not true') * * needs(goodCondition, 'condition not true') */ function needs(condition, errorMessage, Err = Error) { if (!condition) { throw new Err(errorMessage); } } exports.needs = needs; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibmVlZHMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvbmVlZHMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7OztBQUV0Qzs7Ozs7Ozs7O0dBU0c7QUFFSCxTQUFnQixLQUFLLENBQ25CLFNBQWMsRUFDZCxZQUFvQixFQUNwQixNQUF3QixLQUFLO0lBRTdCLElBQUksQ0FBQyxTQUFTLEVBQUU7UUFDZCxNQUFNLElBQUksR0FBRyxDQUFDLFlBQVksQ0FBQyxDQUFBO0tBQzVCO0FBQ0gsQ0FBQztBQVJELHNCQVFDIn0= /***/ }), /***/ 79966: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NodeAlgorithmSuite = void 0; /* * This file contains information about particular algorithm suites used * within the encryption SDK. In most cases, end-users don't need to * manipulate this structure, but it can occasionally be needed for more * advanced use cases, such as writing keyrings. * * These are the Node.js specific values the AWS Encryption SDK for JavaScript * Algorithm Suites. */ const algorithm_suites_1 = __nccwpck_require__(79993); /* References to https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/algorithms-reference.html * These are the composed parameters for each algorithm suite specification for * for the WebCrypto environment. */ const nodeAlgAes128GcmIv12Tag16 = { id: algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16, messageFormat: algorithm_suites_1.MessageFormat.V1, encryption: 'aes-128-gcm', keyLength: 128, ivLength: 12, tagLength: 128, cacheSafe: false, commitment: 'NONE', }; const nodeAlgAes192GcmIv12Tag16 = { id: algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES192_GCM_IV12_TAG16, messageFormat: algorithm_suites_1.MessageFormat.V1, encryption: 'aes-192-gcm', keyLength: 192, ivLength: 12, tagLength: 128, cacheSafe: false, commitment: 'NONE', }; const nodeAlgAes256GcmIv12Tag16 = { id: algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16, messageFormat: algorithm_suites_1.MessageFormat.V1, encryption: 'aes-256-gcm', keyLength: 256, ivLength: 12, tagLength: 128, cacheSafe: false, commitment: 'NONE', }; const nodeAlgAes128GcmIv12Tag16HkdfSha256 = { id: algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256, messageFormat: algorithm_suites_1.MessageFormat.V1, encryption: 'aes-128-gcm', keyLength: 128, ivLength: 12, tagLength: 128, kdf: 'HKDF', kdfHash: 'sha256', cacheSafe: true, commitment: 'NONE', }; const nodeAlgAes192GcmIv12Tag16HkdfSha256 = { id: algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES192_GCM_IV12_TAG16_HKDF_SHA256, messageFormat: algorithm_suites_1.MessageFormat.V1, encryption: 'aes-192-gcm', keyLength: 192, ivLength: 12, tagLength: 128, kdf: 'HKDF', kdfHash: 'sha256', cacheSafe: true, commitment: 'NONE', }; const nodeAlgAes256GcmIv12Tag16HkdfSha256 = { id: algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA256, messageFormat: algorithm_suites_1.MessageFormat.V1, encryption: 'aes-256-gcm', keyLength: 256, ivLength: 12, tagLength: 128, kdf: 'HKDF', kdfHash: 'sha256', cacheSafe: true, commitment: 'NONE', }; const nodeAlgAes128GcmIv12Tag16HkdfSha256EcdsaP256 = { id: algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256, messageFormat: algorithm_suites_1.MessageFormat.V1, encryption: 'aes-128-gcm', keyLength: 128, ivLength: 12, tagLength: 128, kdf: 'HKDF', kdfHash: 'sha256', cacheSafe: true, signatureCurve: 'prime256v1', signatureHash: 'sha256', commitment: 'NONE', }; const nodeAlgAes192GcmIv12Tag16HkdfSha384EcdsaP384 = { id: algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, messageFormat: algorithm_suites_1.MessageFormat.V1, encryption: 'aes-192-gcm', keyLength: 192, ivLength: 12, tagLength: 128, kdf: 'HKDF', kdfHash: 'sha384', cacheSafe: true, signatureCurve: 'secp384r1', signatureHash: 'sha384', commitment: 'NONE', }; const nodeAlgAes256GcmIv12Tag16HkdfSha384EcdsaP384 = { id: algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, messageFormat: algorithm_suites_1.MessageFormat.V1, encryption: 'aes-256-gcm', keyLength: 256, ivLength: 12, tagLength: 128, kdf: 'HKDF', kdfHash: 'sha384', cacheSafe: true, signatureCurve: 'secp384r1', signatureHash: 'sha384', commitment: 'NONE', }; const nodeAlgAes256GcmHkdfSha512Committing = { id: algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY, messageFormat: algorithm_suites_1.MessageFormat.V2, encryption: 'aes-256-gcm', keyLength: 256, ivLength: 12, tagLength: 128, kdf: 'HKDF', kdfHash: 'sha512', cacheSafe: true, commitment: 'KEY', commitmentHash: 'sha512', suiteDataLength: 32, commitmentLength: 256, saltLengthBytes: 32, }; const nodeAlgAes256GcmHkdfSha512CommittingEcdsaP384 = { id: algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY_ECDSA_P384, messageFormat: algorithm_suites_1.MessageFormat.V2, encryption: 'aes-256-gcm', keyLength: 256, ivLength: 12, tagLength: 128, kdf: 'HKDF', kdfHash: 'sha512', cacheSafe: true, signatureCurve: 'secp384r1', signatureHash: 'sha384', commitment: 'KEY', commitmentHash: 'sha512', suiteDataLength: 32, commitmentLength: 256, saltLengthBytes: 32, }; const nodeAlgorithms = Object.freeze({ [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16]: Object.freeze(nodeAlgAes128GcmIv12Tag16), [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES192_GCM_IV12_TAG16]: Object.freeze(nodeAlgAes192GcmIv12Tag16), [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16]: Object.freeze(nodeAlgAes256GcmIv12Tag16), [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256]: Object.freeze(nodeAlgAes128GcmIv12Tag16HkdfSha256), [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES192_GCM_IV12_TAG16_HKDF_SHA256]: Object.freeze(nodeAlgAes192GcmIv12Tag16HkdfSha256), [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA256]: Object.freeze(nodeAlgAes256GcmIv12Tag16HkdfSha256), [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256]: Object.freeze(nodeAlgAes128GcmIv12Tag16HkdfSha256EcdsaP256), [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384]: Object.freeze(nodeAlgAes192GcmIv12Tag16HkdfSha384EcdsaP384), [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384]: Object.freeze(nodeAlgAes256GcmIv12Tag16HkdfSha384EcdsaP384), [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY]: Object.freeze(nodeAlgAes256GcmHkdfSha512Committing), [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY_ECDSA_P384]: Object.freeze(nodeAlgAes256GcmHkdfSha512CommittingEcdsaP384), }); class NodeAlgorithmSuite extends algorithm_suites_1.AlgorithmSuite { type = 'node'; constructor(id) { super(nodeAlgorithms[id]); Object.setPrototypeOf(this, NodeAlgorithmSuite.prototype); Object.freeze(this); } } exports.NodeAlgorithmSuite = NodeAlgorithmSuite; Object.freeze(NodeAlgorithmSuite.prototype); Object.freeze(NodeAlgorithmSuite); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibm9kZV9hbGdvcml0aG1zLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL25vZGVfYWxnb3JpdGhtcy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUEsb0VBQW9FO0FBQ3BFLHNDQUFzQzs7O0FBRXRDOzs7Ozs7OztHQVFHO0FBRUgseURBZTJC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yxnREFBZ0QsQ0FBQyxFQUN6RSxNQUFNLENBQUMsTUFBTSxDQUFDLG9DQUFvQyxDQUFDO0lBQ3JELENBQUMsMkNBQXdCLENBQUMsMkRBQTJELENBQUMsRUFDcEYsTUFBTSxDQUFDLE1BQU0sQ0FBQyw2Q0FBNkMsQ0FBQztDQUMvRCxDQUFDLENBQUE7QUFFRixNQUFhLGtCQUNYLFNBQVEsaUNBQWM7SUFTdEIsSUFBSSxHQUEyQixNQUFNLENBQUE7SUFFckMsWUFBWSxFQUE0QjtRQUN0QyxLQUFLLENBQUMsY0FBYyxDQUFDLEVBQUUsQ0FBQyxDQUFDLENBQUE7UUFDekIsTUFBTSxDQUFDLGNBQWMsQ0FBQyxJQUFJLEVBQUUsa0JBQWtCLENBQUMsU0FBUyxDQUFDLENBQUE7UUFDekQsTUFBTSxDQUFDLE1BQU0sQ0FBQyxJQUFJLENBQUMsQ0FBQTtJQUNyQixDQUFDO0NBQ0Y7QUFqQkQsZ0RBaUJDO0FBRUQsTUFBTSxDQUFDLE1BQU0sQ0FBQyxrQkFBa0IsQ0FBQyxTQUFTLENBQUMsQ0FBQTtBQUMzQyxNQUFNLENBQUMsTUFBTSxDQUFDLGtCQUFrQixDQUFDLENBQUEifQ== /***/ }), /***/ 13770: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.chunk64 = exports.privateKeyPem = exports.publicKeyPem = void 0; /* Before Node.js v11 the crypto module did not support * a method to PEM format a ECDH key. It has always supported * producing such keys: `crypto.createECDH`. But formatting * these keys as a PEM for use in `crypto.Sign` and * `crypto.Verify` has not been possible in native `crypto`. * As Node.js v6, v8, and v10 reach end of life, this code * can be deleted. */ // @ts-ignore const asn1_js_1 = __importDefault(__nccwpck_require__(14293)); const Rfc5915Key = asn1_js_1.default.define('Rfc5915Key', function () { this.seq().obj(this.key('version').int(), this.key('privateKey').octstr(), this.key('parameters').optional().explicit(0).objid({ '1 2 840 10045 3 1 7': 'prime256v1', '1 3 132 0 34': 'secp384r1', }), this.key('publicKey').optional().explicit(1).bitstr()); }); const SpkiKey = asn1_js_1.default.define('SpkiKey', function () { this.seq().obj(this.key('algorithmIdentifier') .seq() .obj(this.key('publicKeyType').objid({ '1 2 840 10045 2 1': 'EC', }), this.key('parameters').objid({ '1 2 840 10045 3 1 7': 'prime256v1', '1 3 132 0 34': 'secp384r1', })), this.key('publicKey').bitstr()); }); function publicKeyPem(curve, publicKey) { const buff = SpkiKey.encode({ algorithmIdentifier: { publicKeyType: 'EC', parameters: curve, }, publicKey: { data: publicKey }, }, 'der'); return [ '-----BEGIN PUBLIC KEY-----', ...chunk64(buff), '-----END PUBLIC KEY-----', '', ].join('\n'); } exports.publicKeyPem = publicKeyPem; function privateKeyPem(curve, privateKey, publicKey) { const buff = Rfc5915Key.encode({ version: 1, privateKey: privateKey, parameters: curve, publicKey: { data: publicKey }, }, 'der'); return [ '-----BEGIN EC PRIVATE KEY-----', ...chunk64(buff), '-----END EC PRIVATE KEY-----', '', ].join('\n'); } exports.privateKeyPem = privateKeyPem; function chunk64(buff) { const chunkSize = 64; const str = buff.toString('base64'); const numChunks = Math.ceil(str.length / chunkSize); const chunks = new Array(numChunks); for (let i = 0, o = 0; i < numChunks; ++i, o += chunkSize) { chunks[i] = str.slice(o, o + chunkSize); } return chunks; } exports.chunk64 = chunk64; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicGVtX2hlbHBlcnMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvcGVtX2hlbHBlcnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7Ozs7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M5QixFQUFFO0tBQ0gsQ0FBQyxJQUFJLENBQUMsSUFBSSxDQUFDLENBQUE7QUFDZCxDQUFDO0FBckJELHNDQXFCQztBQUVELFNBQWdCLE9BQU8sQ0FBQyxJQUFZO0lBQ2xDLE1BQU0sU0FBUyxHQUFHLEVBQUUsQ0FBQTtJQUNwQixNQUFNLEdBQUcsR0FBRyxJQUFJLENBQUMsUUFBUSxDQUFDLFFBQVEsQ0FBQyxDQUFBO0lBQ25DLE1BQU0sU0FBUyxHQUFHLElBQUksQ0FBQyxJQUFJLENBQUMsR0FBRyxDQUFDLE1BQU0sR0FBRyxTQUFTLENBQUMsQ0FBQTtJQUNuRCxNQUFNLE1BQU0sR0FBYSxJQUFJLEtBQUssQ0FBQyxTQUFTLENBQUMsQ0FBQTtJQUU3QyxLQUFLLElBQUksQ0FBQyxHQUFHLENBQUMsRUFBRSxDQUFDLEdBQUcsQ0FBQyxFQUFFLENBQUMsR0FBRyxTQUFTLEVBQUUsRUFBRSxDQUFDLEVBQUUsQ0FBQyxJQUFJLFNBQVMsRUFBRTtRQUN6RCxNQUFNLENBQUMsQ0FBQyxDQUFDLEdBQUcsR0FBRyxDQUFDLEtBQUssQ0FBQyxDQUFDLEVBQUUsQ0FBQyxHQUFHLFNBQVMsQ0FBQyxDQUFBO0tBQ3hDO0lBRUQsT0FBTyxNQUFNLENBQUE7QUFDZixDQUFDO0FBWEQsMEJBV0MifQ== /***/ }), /***/ 80872: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.VerificationKey = exports.SignatureKey = void 0; const ecc_encode_1 = __nccwpck_require__(97659); const ecc_decode_1 = __nccwpck_require__(26601); const immutable_class_1 = __nccwpck_require__(32746); const pem_helpers_1 = __nccwpck_require__(13770); /* * This public interface to the SignatureKey object is provided for * developers of CMMs and keyrings only. If you are a user of the AWS Encryption * SDK and you are not developing your own CMMs and/or keyrings, you do not * need to use it and you should not do so. */ class SignatureKey { constructor(privateKey, compressPoint, suite) { const { signatureCurve: namedCurve } = suite; /* Precondition: Do not create a SignatureKey for an algorithm suite that does not have an EC named curve. */ if (!namedCurve) throw new Error('Unsupported Algorithm'); /* This is unfortunately complicated. Node v11 crypto will accept * a PEM formated Buffer to sign. But the ECDH class will still * return Buffers that are not PEM formated, but _only_ the points * on the curve. This means I have to make a choice about * formating. I chose to assume that t Buffer/Uin8Array is * _only_ the raw points. */ if (privateKey instanceof Uint8Array) { const pem = (0, pem_helpers_1.privateKeyPem)(namedCurve, fromBuffer(privateKey), fromBuffer(compressPoint)); (0, immutable_class_1.readOnlyProperty)(this, 'privateKey', pem); } else { (0, immutable_class_1.readOnlyProperty)(this, 'privateKey', privateKey); } (0, immutable_class_1.readOnlyBinaryProperty)(this, 'compressPoint', compressPoint); (0, immutable_class_1.readOnlyProperty)(this, 'signatureCurve', namedCurve); Object.setPrototypeOf(this, SignatureKey.prototype); Object.freeze(this); } static encodeCompressPoint(publicKeyBytes, suite) { const { signatureCurve: namedCurve } = suite; /* Precondition: Do not return a compress point for an algorithm suite that does not have an EC named curve. */ if (!namedCurve) throw new Error('Unsupported Algorithm'); return ecc_encode_1.encodeNamedCurves[namedCurve](publicKeyBytes); } } exports.SignatureKey = SignatureKey; (0, immutable_class_1.frozenClass)(SignatureKey); class VerificationKey { publicKey; signatureCurve; constructor(publicKey, suite) { const { signatureCurve: namedCurve } = suite; /* Precondition: Do not create a VerificationKey for an algorithm suite that does not have an EC named curve. */ if (!namedCurve) throw new Error('Unsupported Algorithm'); /* This is unfortunately complicated. Node v11 crypto will accept * a PEM formated Buffer to verify. But the ECDH class will still * return Buffers that are not PEM formated, but _only_ the points * on the curve. This means I have to make a choice about * formating. I chose to assume that the Buffer/Uin8Array is * _only_ the raw points. */ if (publicKey instanceof Uint8Array) { const pem = (0, pem_helpers_1.publicKeyPem)(namedCurve, fromBuffer(publicKey)); (0, immutable_class_1.readOnlyProperty)(this, 'publicKey', pem); } else { (0, immutable_class_1.readOnlyProperty)(this, 'publicKey', publicKey); } (0, immutable_class_1.readOnlyProperty)(this, 'signatureCurve', namedCurve); Object.setPrototypeOf(this, VerificationKey.prototype); Object.freeze(this); } static decodeCompressPoint(compressPoint, suite) { const { signatureCurve: namedCurve } = suite; /* Precondition: Do not decode a public key for an algorithm suite that does not have an EC named curve. */ if (!namedCurve) throw new Error('Unsupported Algorithm'); return ecc_decode_1.decodeNamedCurves[namedCurve](compressPoint); } } exports.VerificationKey = VerificationKey; (0, immutable_class_1.frozenClass)(VerificationKey); function fromBuffer(uint) { const { buffer, byteOffset, byteLength } = uint; return Buffer.from(buffer, byteOffset, byteLength); } //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2lnbmF0dXJlX2tleS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9zaWduYXR1cmVfa2V5LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7QUFPdEMsNkNBQWdEO0FBQ2hELDZDQUFnRDtBQUNoRCx1REFJMEI7QUFDMUIsK0NBQTJEO0FBRzNEOzs7OztHQUtHO0FBRUgsTUFBYSxZQUFZO0lBSXZCLFlBQ0UsVUFBMkMsRUFDM0MsYUFBeUIsRUFDekIsS0FBcUI7UUFFckIsTUFBTSxFQUFFLGNBQWMsRUFBRSxVQUFVLEVBQUUsR0FBRyxLQUFLLENBQUE7UUFDNUMsNkdBQTZHO1FBQzdHLElBQUksQ0FBQyxVQUFVO1lBQUUsTUFBTSxJQUFJLEtBQUssQ0FBQyx1QkFBdUIsQ0FBQyxDQUFBO1FBQ3pEOzs7Ozs7V0FNRztRQUNILElBQUksVUFBVSxZQUFZLFVBQVUsRUFBRTtZQUNwQyxNQUFNLEdBQUcsR0FBRyxJQUFBL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UFpQixDQUFDLFVBQVUsQ0FBQyxDQUFDLGFBQWEsQ0FBQyxDQUFBO0lBQ3JELENBQUM7Q0FDRjtBQXZDRCwwQ0F1Q0M7QUFDRCxJQUFBLDZCQUFXLEVBQUMsZUFBZSxDQUFDLENBQUE7QUFFNUIsU0FBUyxVQUFVLENBQUMsSUFBZ0I7SUFDbEMsTUFBTSxFQUFFLE1BQU0sRUFBRSxVQUFVLEVBQUUsVUFBVSxFQUFFLEdBQUcsSUFBSSxDQUFBO0lBQy9DLE9BQU8sTUFBTSxDQUFDLElBQUksQ0FBQyxNQUFNLEVBQUUsVUFBVSxFQUFFLFVBQVUsQ0FBQyxDQUFBO0FBQ3BELENBQUMifQ== /***/ }), /***/ 50479: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidHlwZXMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvdHlwZXMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0MifQ== /***/ }), /***/ 28311: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WebCryptoAlgorithmSuite = void 0; /* * This file contains information about particular algorithm suites used * within the encryption SDK. In most cases, end-users don't need to * manipulate this structure, but it can occasionally be needed for more * advanced use cases, such as writing keyrings. * * These are the WebCrypto specific values the AWS Encryption SDK for JavaScript * Algorithm Suites. */ const algorithm_suites_1 = __nccwpck_require__(79993); const needs_1 = __nccwpck_require__(91846); /* References to https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/algorithms-reference.html * These are the composed parameters for each algorithm suite specification for * for the WebCrypto environment. */ const webCryptoAlgAes128GcmIv12Tag16 = { id: algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16, messageFormat: algorithm_suites_1.MessageFormat.V1, encryption: 'AES-GCM', keyLength: 128, ivLength: 12, tagLength: 128, cacheSafe: false, commitment: 'NONE', }; /* Web browsers do not support 192 bit key lengths at this time. */ const webCryptoAlgAes192GcmIv12Tag16 = { id: algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES192_GCM_IV12_TAG16, messageFormat: algorithm_suites_1.MessageFormat.V1, encryption: 'AES-GCM', keyLength: 192, ivLength: 12, tagLength: 128, cacheSafe: false, commitment: 'NONE', }; const webCryptoAlgAes256GcmIv12Tag16 = { id: algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16, messageFormat: algorithm_suites_1.MessageFormat.V1, encryption: 'AES-GCM', keyLength: 256, ivLength: 12, tagLength: 128, cacheSafe: false, commitment: 'NONE', }; const webCryptoAlgAes128GcmIv12Tag16HkdfSha256 = { id: algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256, messageFormat: algorithm_suites_1.MessageFormat.V1, encryption: 'AES-GCM', keyLength: 128, ivLength: 12, tagLength: 128, kdf: 'HKDF', kdfHash: 'SHA-256', cacheSafe: true, commitment: 'NONE', }; /* Web browsers do not support 192 bit key lengths at this time. */ const webCryptoAlgAes192GcmIv12Tag16HkdfSha256 = { id: algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES192_GCM_IV12_TAG16_HKDF_SHA256, messageFormat: algorithm_suites_1.MessageFormat.V1, encryption: 'AES-GCM', keyLength: 192, ivLength: 12, tagLength: 128, kdf: 'HKDF', kdfHash: 'SHA-256', cacheSafe: true, commitment: 'NONE', }; const webCryptoAlgAes256GcmIv12Tag16HkdfSha256 = { id: algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA256, messageFormat: algorithm_suites_1.MessageFormat.V1, encryption: 'AES-GCM', keyLength: 256, ivLength: 12, tagLength: 128, kdf: 'HKDF', kdfHash: 'SHA-256', cacheSafe: true, commitment: 'NONE', }; const webCryptoAlgAes128GcmIv12Tag16HkdfSha256EcdsaP256 = { id: algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256, messageFormat: algorithm_suites_1.MessageFormat.V1, encryption: 'AES-GCM', keyLength: 128, ivLength: 12, tagLength: 128, kdf: 'HKDF', kdfHash: 'SHA-256', cacheSafe: true, signatureCurve: 'P-256', signatureHash: 'SHA-256', commitment: 'NONE', }; /* Web browsers do not support 192 bit key lengths at this time. */ const webCryptoAlgAes192GcmIv12Tag16HkdfSha384EcdsaP384 = { id: algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, messageFormat: algorithm_suites_1.MessageFormat.V1, encryption: 'AES-GCM', keyLength: 192, ivLength: 12, tagLength: 128, kdf: 'HKDF', kdfHash: 'SHA-384', cacheSafe: true, signatureCurve: 'P-384', signatureHash: 'SHA-384', commitment: 'NONE', }; const webCryptoAlgAes256GcmIv12Tag16HkdfSha384EcdsaP384 = { id: algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, messageFormat: algorithm_suites_1.MessageFormat.V1, encryption: 'AES-GCM', keyLength: 256, ivLength: 12, tagLength: 128, kdf: 'HKDF', kdfHash: 'SHA-384', cacheSafe: true, signatureCurve: 'P-384', signatureHash: 'SHA-384', commitment: 'NONE', }; const webCryptoAlgAes256GcmHkdfSha512Committing = { id: algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY, messageFormat: algorithm_suites_1.MessageFormat.V2, encryption: 'AES-GCM', keyLength: 256, ivLength: 12, tagLength: 128, kdf: 'HKDF', kdfHash: 'SHA-512', cacheSafe: true, commitment: 'KEY', commitmentHash: 'SHA-512', suiteDataLength: 32, commitmentLength: 256, saltLengthBytes: 32, }; const webCryptoAlgAes256GcmHkdfSha512CommittingEcdsaP384 = { id: algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY_ECDSA_P384, messageFormat: algorithm_suites_1.MessageFormat.V2, encryption: 'AES-GCM', keyLength: 256, ivLength: 12, tagLength: 128, kdf: 'HKDF', kdfHash: 'SHA-512', cacheSafe: true, signatureCurve: 'P-384', signatureHash: 'SHA-384', commitment: 'KEY', commitmentHash: 'SHA-512', suiteDataLength: 32, commitmentLength: 256, saltLengthBytes: 32, }; const webCryptoAlgorithms = Object.freeze({ [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16]: Object.freeze(webCryptoAlgAes128GcmIv12Tag16), [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES192_GCM_IV12_TAG16]: Object.freeze(webCryptoAlgAes192GcmIv12Tag16), [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16]: Object.freeze(webCryptoAlgAes256GcmIv12Tag16), [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256]: Object.freeze(webCryptoAlgAes128GcmIv12Tag16HkdfSha256), [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES192_GCM_IV12_TAG16_HKDF_SHA256]: Object.freeze(webCryptoAlgAes192GcmIv12Tag16HkdfSha256), [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA256]: Object.freeze(webCryptoAlgAes256GcmIv12Tag16HkdfSha256), [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256]: Object.freeze(webCryptoAlgAes128GcmIv12Tag16HkdfSha256EcdsaP256), [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384]: Object.freeze(webCryptoAlgAes192GcmIv12Tag16HkdfSha384EcdsaP384), [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384]: Object.freeze(webCryptoAlgAes256GcmIv12Tag16HkdfSha384EcdsaP384), [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY]: Object.freeze(webCryptoAlgAes256GcmHkdfSha512Committing), [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY_ECDSA_P384]: Object.freeze(webCryptoAlgAes256GcmHkdfSha512CommittingEcdsaP384), }); const supportedWebCryptoAlgorithms = Object.freeze({ [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16]: Object.freeze(webCryptoAlgAes128GcmIv12Tag16), // [AlgorithmSuiteIdentifier.ALG_AES192_GCM_IV12_TAG16]: Object.freeze(webCryptoAlgAes192GcmIv12Tag16), [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16]: Object.freeze(webCryptoAlgAes256GcmIv12Tag16), [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256]: Object.freeze(webCryptoAlgAes128GcmIv12Tag16HkdfSha256), // [AlgorithmSuiteIdentifier.ALG_AES192_GCM_IV12_TAG16_HKDF_SHA256]: Object.freeze(webCryptoAlgAes192GcmIv12Tag16HkdfSha256), [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA256]: Object.freeze(webCryptoAlgAes256GcmIv12Tag16HkdfSha256), [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256]: Object.freeze(webCryptoAlgAes128GcmIv12Tag16HkdfSha256EcdsaP256), // [AlgorithmSuiteIdentifier.ALG_AES192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384]: Object.freeze(webCryptoAlgAes192GcmIv12Tag16HkdfSha384EcdsaP384), [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384]: Object.freeze(webCryptoAlgAes256GcmIv12Tag16HkdfSha384EcdsaP384), [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY]: Object.freeze(webCryptoAlgAes256GcmHkdfSha512Committing), [algorithm_suites_1.AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA512_COMMIT_KEY_ECDSA_P384]: Object.freeze(webCryptoAlgAes256GcmHkdfSha512CommittingEcdsaP384), }); class WebCryptoAlgorithmSuite extends algorithm_suites_1.AlgorithmSuite { type = 'webCrypto'; constructor(id) { super(webCryptoAlgorithms[id]); /* Precondition: Browsers do not support 192 bit keys so the AlgorithmSuiteIdentifier is removed. * This is primarily an error in decrypt but this make it clear. * The error can manifest deep in the decrypt loop making it hard to debug. */ (0, needs_1.needs)(Object.prototype.hasOwnProperty.call(supportedWebCryptoAlgorithms, id), '192-bit AES keys are not supported'); Object.setPrototypeOf(this, WebCryptoAlgorithmSuite.prototype); Object.freeze(this); } } exports.WebCryptoAlgorithmSuite = WebCryptoAlgorithmSuite; Object.freeze(WebCryptoAlgorithmSuite.prototype); Object.freeze(WebCryptoAlgorithmSuite); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoid2ViX2NyeXB0b19hbGdvcml0aG1zLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4v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BQ3pFLE1BQU0sQ0FBQyxNQUFNLENBQUMsaURBQWlELENBQUM7SUFDbEUsQ0FBQywyQ0FBd0IsQ0FBQyxnREFBZ0QsQ0FBQyxFQUN6RSxNQUFNLENBQUMsTUFBTSxDQUFDLHlDQUF5QyxDQUFDO0lBQzFELENBQUMsMkNBQXdCLENBQUMsMkRBQTJELENBQUMsRUFDcEYsTUFBTSxDQUFDLE1BQU0sQ0FBQyxrREFBa0QsQ0FBQztDQUNwRSxDQUFDLENBQUE7QUFFSixNQUFhLHVCQUNYLFNBQVEsaUNBQWM7SUFTdEIsSUFBSSxHQUFnQyxXQUFXLENBQUE7SUFFL0MsWUFBWSxFQUE0QjtRQUN0QyxLQUFLLENBQUMsbUJBQW1CLENBQUMsRUFBRSxDQUFDLENBQUMsQ0FBQTtRQUM5Qjs7O1dBR0c7UUFDSCxJQUFBLGFBQUssRUFDSCxNQUFNLENBQUMsU0FBUyxDQUFDLGNBQWMsQ0FBQyxJQUFJLENBQUMsNEJBQTRCLEVBQUUsRUFBRSxDQUFDLEVBQ3RFLG9DQUFvQyxDQUNyQyxDQUFBO1FBQ0QsTUFBTSxDQUFDLGNBQWMsQ0FBQyxJQUFJLEVBQUUsdUJBQXVCLENBQUMsU0FBUyxDQUFDLENBQUE7UUFDOUQsTUFBTSxDQUFDLE1BQU0sQ0FBQyxJQUFJLENBQUMsQ0FBQTtJQUNyQixDQUFDO0NBQ0Y7QUF6QkQsMERBeUJDO0FBRUQsTUFBTSxDQUFDLE1BQU0sQ0FBQyx1QkFBdUIsQ0FBQyxTQUFTLENBQUMsQ0FBQTtBQUNoRCxNQUFNLENBQUMsTUFBTSxDQUFDLHVCQUF1QixDQUFDLENBQUEifQ== /***/ }), /***/ 86979: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 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.RawAesWrappingSuiteIdentifier = void 0; var raw_keyring_1 = __nccwpck_require__(2218); Object.defineProperty(exports, "RawAesWrappingSuiteIdentifier", ({ enumerable: true, get: function () { return raw_keyring_1.RawAesWrappingSuiteIdentifier; } })); __exportStar(__nccwpck_require__(92507), exports); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7Ozs7Ozs7Ozs7Ozs7Ozs7O0FBRXRDLHVEQUdnQztBQUY5Qiw0SEFBQSw2QkFBNkIsT0FBQTtBQUcvQix5REFBc0MifQ== /***/ }), /***/ 92507: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.RawAesKeyringNode = void 0; const material_management_node_1 = __nccwpck_require__(12563); const crypto_1 = __nccwpck_require__(6113); const serialize_1 = __nccwpck_require__(26683); const raw_keyring_1 = __nccwpck_require__(2218); const fromUtf8 = (input) => Buffer.from(input, 'utf8'); const toUtf8 = (input) => Buffer.from(input.buffer, input.byteOffset, input.byteLength).toString('utf8'); const { serializeEncryptionContext } = (0, serialize_1.serializeFactory)(fromUtf8); const { rawAesEncryptedDataKey } = (0, raw_keyring_1.rawAesEncryptedDataKeyFactory)(toUtf8, fromUtf8); const { rawAesEncryptedParts } = (0, raw_keyring_1.rawAesEncryptedPartsFactory)(fromUtf8); class RawAesKeyringNode extends material_management_node_1.KeyringNode { constructor(input) { super(); const { keyName, keyNamespace, unencryptedMasterKey, wrappingSuite } = input; /* Precondition: AesKeyringNode needs identifying information for encrypt and decrypt. */ (0, material_management_node_1.needs)(keyName && keyNamespace, 'Identifying information must be defined.'); /* Precondition: RawAesKeyringNode requires wrappingSuite to be a valid RawAesWrappingSuite. */ const wrappingMaterial = new raw_keyring_1.NodeRawAesMaterial(wrappingSuite) /* Precondition: unencryptedMasterKey must correspond to the NodeAlgorithmSuite specification. * Note: the KeyringTrace and flag are _only_ set because I am reusing an existing implementation. * See: raw_aes_material.ts in @aws-crypto/raw-keyring for details */ .setUnencryptedDataKey(unencryptedMasterKey, { keyNamespace, keyName, flags: material_management_node_1.KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, }); const _wrapKey = async (material) => { /* The AAD section is uInt16BE(length) + AAD * see: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/message-format.html#header-aad * However, the RAW Keyring wants _only_ the ADD. * So, I just slice off the length. */ const { buffer, byteOffset, byteLength } = serializeEncryptionContext(material.encryptionContext).slice(2); const aad = Buffer.from(buffer, byteOffset, byteLength); const { keyNamespace, keyName } = this; return aesGcmWrapKey(keyNamespace, keyName, material, aad, wrappingMaterial); }; const _unwrapKey = async (material, edk) => { const { keyNamespace, keyName } = this; /* The AAD section is uInt16BE(length) + AAD * see: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/message-format.html#header-aad * However, the RAW Keyring wants _only_ the ADD. * So, I just slice off the length. */ const { buffer, byteOffset, byteLength } = serializeEncryptionContext(material.encryptionContext).slice(2); const aad = Buffer.from(buffer, byteOffset, byteLength); // const aad = Buffer.concat(encodeEncryptionContext(context || {})) return aesGcmUnwrapKey(keyNamespace, keyName, material, wrappingMaterial, edk, aad); }; (0, material_management_node_1.readOnlyProperty)(this, 'keyName', keyName); (0, material_management_node_1.readOnlyProperty)(this, 'keyNamespace', keyNamespace); (0, material_management_node_1.readOnlyProperty)(this, '_wrapKey', _wrapKey); (0, material_management_node_1.readOnlyProperty)(this, '_unwrapKey', _unwrapKey); } _filter({ providerId, providerInfo }) { const { keyNamespace, keyName } = this; return providerId === keyNamespace && providerInfo.startsWith(keyName); } _onEncrypt = (0, raw_keyring_1._onEncrypt)(randomBytesAsync); _onDecrypt = (0, raw_keyring_1._onDecrypt)(); } exports.RawAesKeyringNode = RawAesKeyringNode; (0, material_management_node_1.immutableClass)(RawAesKeyringNode); const encryptFlags = material_management_node_1.KeyringTraceFlag.WRAPPING_KEY_ENCRYPTED_DATA_KEY | material_management_node_1.KeyringTraceFlag.WRAPPING_KEY_SIGNED_ENC_CTX; const decryptFlags = material_management_node_1.KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY | material_management_node_1.KeyringTraceFlag.WRAPPING_KEY_VERIFIED_ENC_CTX; /** * Uses aes-gcm to encrypt the data key and return the passed NodeEncryptionMaterial with * an EncryptedDataKey added. * @param keyNamespace [String] The keyring namespace (for KeyringTrace) * @param keyName [String] The keyring name (for KeyringTrace and to extract the extra info stored in providerInfo) * @param material [NodeEncryptionMaterial] The target material to which the EncryptedDataKey will be added * @param aad [Buffer] The serialized aad (EncryptionContext) * @param wrappingMaterial [NodeRawAesMaterial] The material used to decrypt the EncryptedDataKey * @returns [NodeEncryptionMaterial] Mutates and returns the same NodeEncryptionMaterial that was passed but with an EncryptedDataKey added */ function aesGcmWrapKey(keyNamespace, keyName, material, aad, wrappingMaterial) { const { encryption, ivLength } = wrappingMaterial.suite; const iv = (0, crypto_1.randomBytes)(ivLength); const wrappingDataKey = wrappingMaterial.getUnencryptedDataKey(); const dataKey = (0, material_management_node_1.unwrapDataKey)(material.getUnencryptedDataKey()); const cipher = (0, crypto_1.createCipheriv)(encryption, wrappingDataKey, iv).setAAD(aad); // Buffer.concat will use the shared buffer space, and the resultant buffer will have a byteOffset... const ciphertext = (0, serialize_1.concatBuffers)(cipher.update(dataKey), cipher.final()); const authTag = cipher.getAuthTag(); const edk = rawAesEncryptedDataKey(keyNamespace, keyName, iv, ciphertext, authTag); return material.addEncryptedDataKey(edk, encryptFlags); } /** * Uses aes-gcm to decrypt the encrypted data key and return the passed NodeDecryptionMaterial with * the unencrypted data key set. * @param keyNamespace [String] The keyring namespace (for KeyringTrace) * @param keyName [String] The keyring name (for KeyringTrace and to extract the extra info stored in providerInfo) * @param material [NodeDecryptionMaterial] The target material to which the decrypted data key will be added * @param wrappingMaterial [NodeRawAesMaterial] The material used to decrypt the EncryptedDataKey * @param edk [EncryptedDataKey] The EncryptedDataKey on which to operate * @param aad [Buffer] The serialized aad (EncryptionContext) * @returns [NodeDecryptionMaterial] Mutates and returns the same NodeDecryptionMaterial that was passed but with the unencrypted data key set */ function aesGcmUnwrapKey(keyNamespace, keyName, material, wrappingMaterial, edk, aad) { const { authTag, ciphertext, iv } = rawAesEncryptedParts(material.suite, keyName, edk); const { encryption } = wrappingMaterial.suite; // createDecipheriv is incorrectly typed in @types/node. It should take key: CipherKey, not key: BinaryLike const decipher = (0, crypto_1.createDecipheriv)(encryption, wrappingMaterial.getUnencryptedDataKey(), iv) .setAAD(aad) .setAuthTag(authTag); // Buffer.concat will use the shared buffer space, and the resultant buffer will have a byteOffset... const unencryptedDataKey = (0, serialize_1.concatBuffers)(decipher.update(ciphertext), decipher.final()); const trace = { keyNamespace, keyName, flags: decryptFlags }; return material.setUnencryptedDataKey(unencryptedDataKey, trace); } async function randomBytesAsync(size) { return new Promise((resolve, reject) => { (0, crypto_1.randomBytes)(size, (err, buffer) => { if (err) return reject(err); resolve(buffer); }); }); } //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicmF3X2Flc19rZXlyaW5nX25vZ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SxZQUFZLEVBQUUsQ0FBQTtJQUM1RCxPQUFPLFFBQVEsQ0FBQyxxQkFBcUIsQ0FBQyxrQkFBa0IsRUFBRSxLQUFLLENBQUMsQ0FBQTtBQUNsRSxDQUFDO0FBRUQsS0FBSyxVQUFVLGdCQUFnQixDQUFDLElBQVk7SUFDMUMsT0FBTyxJQUFJLE9BQU8sQ0FBQyxDQUFDLE9BQU8sRUFBRSxNQUFNLEVBQUUsRUFBRTtRQUNyQyxJQUFBLG9CQUFXLEVBQUMsSUFBSSxFQUFFLENBQUMsR0FBaUIsRUFBRSxNQUFjLEVBQUUsRUFBRTtZQUN0RCxJQUFJLEdBQUc7Z0JBQUUsT0FBTyxNQUFNLENBQUMsR0FBRyxDQUFDLENBQUE7WUFDM0IsT0FBTyxDQUFDLE1BQU0sQ0FBQyxDQUFBO1FBQ2pCLENBQUMsQ0FBQyxDQUFBO0lBQ0osQ0FBQyxDQUFDLENBQUE7QUFDSixDQUFDIn0= /***/ }), /***/ 2218: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 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__(57925), exports); __exportStar(__nccwpck_require__(82121), exports); __exportStar(__nccwpck_require__(71606), exports); __exportStar(__nccwpck_require__(94868), exports); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7Ozs7Ozs7Ozs7Ozs7Ozs7QUFFdEMsNERBQXlDO0FBQ3pDLHFEQUFrQztBQUNsQyxnRUFBNkM7QUFDN0MsMkRBQXdDIn0= /***/ }), /***/ 57925: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.RawAesWrappingSuiteIdentifier = void 0; const material_management_1 = __nccwpck_require__(77519); const AES128_GCM_IV12_TAG16_NO_PADDING = material_management_1.AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16; const AES192_GCM_IV12_TAG16_NO_PADDING = material_management_1.AlgorithmSuiteIdentifier.ALG_AES192_GCM_IV12_TAG16; const AES256_GCM_IV12_TAG16_NO_PADDING = material_management_1.AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16; exports.RawAesWrappingSuiteIdentifier = Object.freeze({ AES128_GCM_IV12_TAG16_NO_PADDING, AES192_GCM_IV12_TAG16_NO_PADDING, AES256_GCM_IV12_TAG16_NO_PADDING, // Adding reverse lookup to support checking supported suites [AES128_GCM_IV12_TAG16_NO_PADDING]: AES128_GCM_IV12_TAG16_NO_PADDING, [AES192_GCM_IV12_TAG16_NO_PADDING]: AES192_GCM_IV12_TAG16_NO_PADDING, [AES256_GCM_IV12_TAG16_NO_PADDING]: AES256_GCM_IV12_TAG16_NO_PADDING, }); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicmF3X2Flc19hbGdvcml0aG1fc3VpdGUuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvcmF3X2Flc19hbGdvcml0aG1fc3VpdGUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7OztBQUV0Qyx5RUFBMEU7QUFZMUUsTUFBTSxnQ0FBZ0MsR0FDcEMsOENBQXdCLENBQUMseUJBQXlCLENBQUE7QUFDcEQsTUFBTSxnQ0FBZ0MsR0FDcEMsOENBQXdCLENBQUMseUJBQXlCLENBQUE7QUFDcEQsTUFBTSxnQ0FBZ0MsR0FDcEMsOENBQXdCLENBQUMseUJBQXlCLENBQUE7QUFDdkMsUUFBQSw2QkFBNkIsR0FFdEMsTUFBTSxDQUFDLE1BQU0sQ0FBQztJQUNoQixnQ0FBZ0M7SUFDaEMsZ0NBQWdDO0lBQ2hDLGdDQUFnQztJQUNoQyw2REFBNkQ7SUFDN0QsQ0FBQyxnQ0FBZ0MsQ0FBQyxFQUFFLGdDQUFnQztJQUNwRSxDQUFDLGdDQUFnQyxDQUFDLEVBQUUsZ0NBQWdDO0lBQ3BFLENBQUMsZ0NBQWdDLENBQUMsRUFBRSxnQ0FBZ0M7Q0FDckUsQ0FBQyxDQUFBIn0= /***/ }), /***/ 71606: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.rawAesEncryptedPartsFactory = exports.rawAesEncryptedDataKeyFactory = void 0; /* For raw AES keyrings the required wrapping information is stored in an EncryptedDataKey. * KeyNamespace (identifies the keyring "class"), * KeyName (identifies this specific keyring, like a KMS CMK ARN) * * { * providerId: KeyNamespace * providerInfo: utf8Encode(KeyName + TagLengthBits uInt32BE + IVLength uInt32BE + iv) * encryptedDataKey: wrapped key + authTag * } * * The AAD (encryption context) is the same as the message. */ const serialize_1 = __nccwpck_require__(26683); const material_management_1 = __nccwpck_require__(77519); function rawAesEncryptedDataKeyFactory(toUtf8, fromUtf8) { return { rawAesEncryptedDataKey }; function rawAesEncryptedDataKey(keyNamespace, keyName, iv, ciphertext, authTag) { const ivLength = iv.byteLength; const authTagBitLength = authTag.byteLength * 8; const encryptedDataKey = (0, serialize_1.concatBuffers)(ciphertext, authTag); const providerId = keyNamespace; const rawInfo = (0, serialize_1.concatBuffers)(fromUtf8(keyName), (0, serialize_1.uInt32BE)(authTagBitLength), (0, serialize_1.uInt32BE)(ivLength), iv); const providerInfo = toUtf8(rawInfo); return new material_management_1.EncryptedDataKey({ encryptedDataKey, providerId, providerInfo, rawInfo, }); } } exports.rawAesEncryptedDataKeyFactory = rawAesEncryptedDataKeyFactory; function rawAesEncryptedPartsFactory(fromUtf8) { return { rawAesEncryptedParts }; function rawAesEncryptedParts(suite, keyName, { encryptedDataKey, rawInfo }) { /* Precondition: rawInfo must be a Uint8Array. */ if (!(rawInfo instanceof Uint8Array)) throw new Error('Malformed Encrypted Data Key.'); // see above for format, slice off the "string part" rawInfo = rawInfo.slice(fromUtf8(keyName).byteLength); /* Uint8Array is a view on top of the underlying ArrayBuffer. * This means that raw underlying memory stored in the ArrayBuffer * may be larger than the Uint8Array. This is especially true of * the Node.js Buffer object. The offset and length *must* be * passed to the DataView otherwise I will get unexpected results. */ const dataView = new DataView(rawInfo.buffer, rawInfo.byteOffset, rawInfo.byteLength); /* See above: * uInt32BE(authTagBitLength),uInt32BE(ivLength), iv */ const tagLengthBits = dataView.getUint32(0, false); // big endian const ivLength = dataView.getUint32(4, false); // big endian /* Precondition: The ivLength must match the algorith suite specification. */ (0, material_management_1.needs)(ivLength === suite.ivLength, 'Malformed providerInfo'); /* Precondition: The tagLength must match the algorith suite specification. */ (0, material_management_1.needs)(tagLengthBits === suite.tagLength, 'Malformed providerInfo'); /* Precondition: The byteLength of rawInfo should match the encoded length. */ (0, material_management_1.needs)(rawInfo.byteLength === 4 + 4 + ivLength, 'Malformed providerInfo'); const tagLength = tagLengthBits / 8; /* Precondition: The encryptedDataKey byteLength must match the algorith suite specification and encoded length. */ (0, material_management_1.needs)(encryptedDataKey.byteLength === tagLength + suite.keyLengthBytes, 'Malformed providerInfo'); const iv = rawInfo.slice(-ivLength); const authTag = encryptedDataKey.slice(-tagLength); const ciphertext = encryptedDataKey.slice(0, -tagLength); return { authTag, ciphertext, iv }; } } exports.rawAesEncryptedPartsFactory = rawAesEncryptedPartsFactory; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicmF3X2Flc19lbmNyeXB0ZWRfZGF0YV9rZXlzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL3Jhd19hZXNfZW5jcnlwdGVkX2RhdGFfa2V5cy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUEsb0VBQW9FO0FBQ3BFLHNDQUFzQzs7O0FBRXRDOzs7Ozs7Ozs7OztHQVdHO0FBRUgscURBQStEO0FBQy9ELHlFQUl3QztBQUV4QyxTQUFnQiw2QkFBNkIsQ0FDM0MsTUFBcUMsRUFDckMsUUFBdUM7SUFFdkMsT0FBTyxFQUFFLHNCQUFzQixFQUFFLENBQUE7SUFFakMsU0FBUyxzQkFBc0IsQ0FDN0IsWUFBb0IsRUFDcEIsT0FBZSxFQUNmLEVBQWMsRUFDZCxVQUFzQixFQUN0QixPQUFtQjtRQUVuQixNQUFNLFFBQVEsR0FBRyxFQUFFLENBQUMsVUFBVSxDQUFBO1FBQzlCLE1BQU0sZ0JBQWdCLEdBQUcsT0FBTyxDQUFDLFVBQVUsR0FBRyxDQUFDLENBQUE7UUFDL0MsTUFBTSxnQkFBZ0IsR0FBRyxJQUFBLHlCQUFhLEVBQUMsVUFBVSxFQUFFLE9BQU8sQ0FBQyxDQUFBO1FBQzNELE1BQU0sVUFBVSxHQUFHLFlBQVksQ0FBQTtRQUMvQixNQUFNLE9BQU8sR0FBRyxJQU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BQztBQUNILENBQUM7QUFqREQsa0VBaURDIn0= /***/ }), /***/ 82121: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WebCryptoRawAesMaterial = exports.NodeRawAesMaterial = void 0; /* Here I am reusing the Material implementation and interface from material-management. * This is because there are many security guarantees that this implementations offer * that map to the current implementation of raw AES keyrings. * The KeyringTrace is an unfortunate case because there is no mapping. * However the trade off seems worth it and the convolutions to make it work seem minimal. */ const material_management_1 = __nccwpck_require__(77519); const raw_aes_algorithm_suite_1 = __nccwpck_require__(57925); class NodeRawAesMaterial { suite; setUnencryptedDataKey; getUnencryptedDataKey; zeroUnencryptedDataKey; hasUnencryptedDataKey; keyringTrace = []; encryptionContext = Object.freeze({}); constructor(suiteId) { /* Precondition: NodeRawAesMaterial suiteId must be RawAesWrappingSuiteIdentifier. */ (0, material_management_1.needs)(raw_aes_algorithm_suite_1.RawAesWrappingSuiteIdentifier[suiteId], 'suiteId not supported.'); this.suite = new material_management_1.NodeAlgorithmSuite(suiteId); /* NodeRawAesMaterial need to set a flag, this is an abuse of TraceFlags * because the material is not generated. * but CryptographicMaterial force a flag to be set. */ const setFlags = material_management_1.KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY; (0, material_management_1.decorateCryptographicMaterial)(this, setFlags); Object.setPrototypeOf(this, NodeRawAesMaterial.prototype); Object.freeze(this); } hasValidKey() { return this.hasUnencryptedDataKey; } } exports.NodeRawAesMaterial = NodeRawAesMaterial; (0, material_management_1.frozenClass)(NodeRawAesMaterial); class WebCryptoRawAesMaterial { suite; setUnencryptedDataKey; getUnencryptedDataKey; zeroUnencryptedDataKey; hasUnencryptedDataKey; keyringTrace = []; setCryptoKey; getCryptoKey; hasCryptoKey; validUsages; encryptionContext = Object.freeze({}); constructor(suiteId) { /* Precondition: WebCryptoAlgorithmSuite suiteId must be RawAesWrappingSuiteIdentifier. */ (0, material_management_1.needs)(raw_aes_algorithm_suite_1.RawAesWrappingSuiteIdentifier[suiteId], 'suiteId not supported.'); this.suite = new material_management_1.WebCryptoAlgorithmSuite(suiteId); this.validUsages = Object.freeze([ 'decrypt', 'encrypt', ]); /* WebCryptoRawAesMaterial need to set a flag, this is an abuse of TraceFlags * because the material is not generated. * but CryptographicMaterial force a flag to be set. */ const setFlag = material_management_1.KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY; (0, material_management_1.decorateCryptographicMaterial)(this, setFlag); (0, material_management_1.decorateWebCryptoMaterial)(this, setFlag); Object.setPrototypeOf(this, WebCryptoRawAesMaterial.prototype); Object.freeze(this); } hasValidKey() { return this.hasUnencryptedDataKey && this.hasCryptoKey; } } exports.WebCryptoRawAesMaterial = WebCryptoRawAesMaterial; (0, material_management_1.frozenClass)(WebCryptoRawAesMaterial); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicmF3X2Flc19tYXRlcmlhbC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9yYXdfYWVzX21hdGVyaWFsLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7QUFFdEM7Ozs7O0dBS0c7QUFFSCx5RUFnQndDO0FBRXhDLHVFQUdrQztBQUVsQyxNQUFhLGtCQUFrQjtJQUc3QixLQUFLLENBQW9CO0lBQ3pCLHFCQUFxQixDQUdFO0lBQ3ZCLHFCQUFxQixDQUFzQztJQUMzRCxzQkFBc0IsQ0FBMkI7SUFDakQscUJBQXFCLENBQVU7SUFDL0IsWUFBWSxHQUFtQixFQUFFLENBQUE7SUFDakMsaUJBQWlCLEdBQXNCLE1BQU0sQ0FBQyxNQUFNLENBQUMsRUFBRSxDQUFDLENBQUE7SUFDeEQsWUFBWSxPQUFnQztRQUMx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FBQyxFQUFFLHdCQUF3QixDQUFDLENBQUE7UUFDdkUsSUFBSSxDQUFDLEtBQUssR0FBRyxJQUFJLDZDQUF1QixDQUFDLE9BQU8sQ0FBQyxDQUFBO1FBQ2pELElBQUksQ0FBQyxXQUFXLEdBQUcsTUFBTSxDQUFDLE1BQU0sQ0FBQztZQUMvQixTQUFTO1lBQ1QsU0FBUztTQUNhLENBQUMsQ0FBQTtRQUN6Qjs7O1dBR0c7UUFDSCxNQUFNLE9BQU8sR0FBRyxzQ0FBZ0IsQ0FBQywrQkFBK0IsQ0FBQTtRQUNoRSxJQUFBLG1EQUE2QixFQUEwQixJQUFJLEVBQUUsT0FBTyxDQUFDLENBQUE7UUFDckUsSUFBQSwrQ0FBeUIsRUFBMEIsSUFBSSxFQUFFLE9BQU8sQ0FBQyxDQUFBO1FBQ2pFLE1BQU0sQ0FBQyxjQUFjLENBQUMsSUFBSSxFQUFFLHVCQUF1QixDQUFDLFNBQVMsQ0FBQyxDQUFBO1FBQzlELE1BQU0sQ0FBQyxNQUFNLENBQUMsSUFBSSxDQUFDLENBQUE7SUFDckIsQ0FBQztJQUNELFdBQVc7UUFDVCxPQUFPLElBQUksQ0FBQyxxQkFBcUIsSUFBSSxJQUFJLENBQUMsWUFBWSxDQUFBO0lBQ3hELENBQUM7Q0FDRjtBQTNDRCwwREEyQ0M7QUFDRCxJQUFBLGlDQUFXLEVBQUMsdUJBQXVCLENBQUMsQ0FBQSJ9 /***/ }), /***/ 94868: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports._onDecrypt = exports._onEncrypt = void 0; const material_management_1 = __nccwpck_require__(77519); function _onEncrypt(randomBytes) { return async function _onEncrypt(material) { if (!material.hasUnencryptedDataKey) { const trace = { keyName: this.keyName, keyNamespace: this.keyNamespace, flags: material_management_1.KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, }; const udk = await randomBytes(material.suite.keyLengthBytes); material.setUnencryptedDataKey(udk, trace); } return this._wrapKey(material); }; } exports._onEncrypt = _onEncrypt; function _onDecrypt() { return async function _onDecrypt(material, encryptedDataKeys) { /* Check for early return (Postcondition): If the material is already valid, attempting to decrypt is a bad idea. */ if (material.hasValidKey()) return material; const edks = encryptedDataKeys.filter(this._filter, this); /* Check for early return (Postcondition): If there are not EncryptedDataKeys for this keyring, do nothing. */ if (!edks.length) return material; for (const edk of edks) { try { return await this._unwrapKey(material, edk); } catch (e) { // there should be some debug here? or wrap? // Failures decrypt should not short-circuit the process // If the caller does not have access they may have access // through another Keyring. } } return material; }; } exports._onDecrypt = _onDecrypt; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicmF3X2tleXJpbmdfZGVjb3JhdG9ycy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9yYXdfa2V5cmluZ19kZWNvcmF0b3JzLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7QUFFdEMseUVBT3dDO0FBVXhDLFNBQWdCLFVBQVUsQ0FHeEIsV0FBbUQ7SUFDbkQsT0FBTyxLQUFLLFVBQVUsVUFBVSxDQUU5QixRQUErQjtRQUUvQixJQUFJLENBQUMsUUFBUSxDQUFDLHFCQUFxQixFQUFFO1lBQ25DLE1BQU0sS0FBSyxHQUFpQjtnQkFDMUIsT0FBTyxFQUFFLElBQUksQ0FBQyxPQUFPO2dCQUNyQixZQUFZLEVBQUUsSUFBSSxDQUFDLFlBQVk7Z0JBQy9CLEtBQUssRUFBRSxzQ0FBZ0IsQ0FBQywrQkFBK0I7YUFDeEQsQ0FBQTtZQUNELE1BQU0sR0FBRyxHQUFHLE1BQU0sV0FBVyxDQUFDLFFBQVEsQ0FBQyxLQUFLLENBQUMsY0FBYyxDQUFDLENBQUE7WUFDNUQsUUFBUSxDQUFDLHFCQUFxQixDQUFDLEdBQUcsRUFBRSxLQUFLLENBQUMsQ0FBQTtTQUMzQztRQUNELE9BQU8sSUFBSSxDQUFDLFFBQVEsQ0FBQyxRQUFRLENBQUMsQ0FBQTtJQUNoQyxDQUFDLENBQUE7QUFDSCxDQUFDO0FBbkJELGdDQW1CQztBQUVELFNBQWdCLFVBQVU7SUFJeEIsT0FBTyxLQUFLLFVBQVUsVUFBVSxDQUU5QixRQUErQixFQUMvQixpQkFBcUM7UUFFckMsb0hBQW9IO1FBQ3BILElBQUksUUFBUSxDQUFDLFdBQVcsRUFBRTtZQUFFLE9BQU8sUUFBUSxDQUFBO1FBQzNDLE1BQU0sSUFBSSxHQUFHLGlCQUFpQixDQUFDLE1BQU0sQ0FBQyxJQUFJLENBQUMsT0FBTyxFQUFFLElBQUksQ0FBQyxDQUFBO1FBQ3pELDhHQUE4RztRQUM5RyxJQUFJLENBQUMsSUFBSSxDQUFDLE1BQU07WUFBRSxPQUFPLFFBQVEsQ0FBQTtRQUVqQyxLQUFLLE1BQU0sR0FBRyxJQUFJLElBQUksRUFBRTtZQUN0QixJQUFJO2dCQUNGLE9BQU8sTUFBTSxJQUFJLENBQUMsVUFBVSxDQUFDLFFBQVEsRUFBRSxHQUFHLENBQUMsQ0FBQTthQUM1QztZQUFDLE9BQU8sQ0FBQyxFQUFFO2dCQUNWLDZDQUE2QztnQkFDN0Msd0RBQXdEO2dCQUN4RCwwREFBMEQ7Z0JBQzFELDJCQUEyQjthQUM1QjtTQUNGO1FBRUQsT0FBTyxRQUFRLENBQUE7SUFDakIsQ0FBQyxDQUFBO0FBQ0gsQ0FBQztBQTVCRCxnQ0E0QkMifQ== /***/ }), /***/ 55276: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 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__(6214), exports); __exportStar(__nccwpck_require__(3187), exports); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7Ozs7Ozs7Ozs7Ozs7Ozs7QUFFdEMseURBQXNDO0FBQ3RDLHdEQUFxQyJ9 /***/ }), /***/ 3187: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.oaepHashSupported = void 0; /* oaepHash support was added in Node.js v12.9.1 (https://github.com/nodejs/node/pull/28335) * However, the integration tests need to be able to verify functionality on other versions. * There are no constants to sniff, * and looking at the version would not catch back-ports. * So I simply try the function. * However there is a rub as the test might seem backwards. * Sending an invalid hash to the version that supports oaepHash will throw an error. * But sending an invalid hash to a version that does not support oaepHash will be ignored. */ const material_management_node_1 = __nccwpck_require__(12563); const crypto_1 = __nccwpck_require__(6113); exports.oaepHashSupported = (function () { const key = '-----BEGIN PUBLIC KEY-----\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAs7RoNYEPAIws89VV+kra\nrVv/4wbdmUAaAKWgWuxZi5na9GJSmnhCkqyLRm7wPbQY4LCoa5/IMUxkHLsYDPdu\nudY0Qm0GcoxOlvJKHYo4RjF7HyiS34D6dvyO4Gd3aq0mZHoxSGCxW/7hf03wEMzc\niVJXWHXhaI0lD6nrzIEgLrE4L+3V2LeAQjvZsTKd+bYMqeZOL2syiVVIAU8POwAG\nGVBroJoveFm/SUp6lCiN0M2kTeyQA2ax3QTtZSAa8nwrI7U52XOzVmdMicJsy2Pg\nuW98te3MuODdK24yNkHIkYameP/Umf/SJshUJQd5a/TUp3XE+HhOWAumx22tIDlC\nvZS11cuk2fp0WeHUnXaC19N5qWKfvHEKSugzty/z3lGP7ItFhrF2X1qJHeAAsL11\nkjo6Lc48KsE1vKvbnW4VLyB3wdNiVvmUNO29tPXwaR0Q5Gbr3jk3nUzdkEHouHWQ\n41lubOHCCBN3V13mh/MgtNhESHjfmmOnh54ErD9saA1d7CjTf8g2wqmjEqvGSW6N\nq7zhcWR2tp1olflS7oHzul4/I3hnkfL6Kb2xAWWaQKvg3mtsY2OPlzFEP0tR5UcH\nPfp5CeS1Xzg7hN6vRICW6m4l3u2HJFld2akDMm1vnSz8RCbPW7jp7YBxUkWJmypM\ntG7Yv2aGZXGbUtM8o1cZarECAwEAAQ==\n-----END PUBLIC KEY-----'; const oaepHash = 'i_am_not_valid'; try { // @ts-ignore (0, crypto_1.publicEncrypt)({ key, padding: crypto_1.constants.RSA_PKCS1_OAEP_PADDING, oaepHash }, Buffer.from([1, 2, 3, 4])); /* See note above, * only versions that support oaepHash will respond. * So the only way I can get here is if the option was ignored. */ return false; } catch (ex) { if (ex instanceof material_management_node_1.NotSupported) { (0, material_management_node_1.needs)(ex.code === 'ERR_OSSL_EVP_INVALID_DIGEST', 'Unexpected error testing oaepHash.'); return true; } return Error('Unexpected error testing oaepHash.'); } })(); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxl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Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.RawRsaKeyringNode = void 0; const material_management_node_1 = __nccwpck_require__(12563); const crypto_1 = __nccwpck_require__(6113); const raw_keyring_1 = __nccwpck_require__(2218); const oaep_hash_supported_1 = __nccwpck_require__(3187); const supportedOaepHash = [ 'sha1', 'sha256', 'sha384', 'sha512', undefined, ]; class RawRsaKeyringNode extends material_management_node_1.KeyringNode { constructor(input) { super(); const { rsaKey, keyName, keyNamespace, padding = crypto_1.constants.RSA_PKCS1_OAEP_PADDING, oaepHash, } = input; const { publicKey, privateKey } = rsaKey; /* Precondition: RsaKeyringNode needs either a public or a private key to operate. */ (0, material_management_node_1.needs)(publicKey || privateKey, 'No Key provided.'); /* Precondition: RsaKeyringNode needs identifying information for encrypt and decrypt. */ (0, material_management_node_1.needs)(keyName && keyNamespace, 'Identifying information must be defined.'); /* Precondition: The AWS ESDK only supports specific hash values for OAEP padding. */ (0, material_management_node_1.needs)(padding === crypto_1.constants.RSA_PKCS1_OAEP_PADDING ? oaep_hash_supported_1.oaepHashSupported ? supportedOaepHash.includes(oaepHash) : !oaepHash || oaepHash === 'sha1' : !oaepHash, 'Unsupported oaepHash'); const _wrapKey = async (material) => { /* Precondition: Public key must be defined to support encrypt. */ if (!publicKey) throw new Error('No public key defined in constructor. Encrypt disabled.'); const { buffer, byteOffset, byteLength } = (0, material_management_node_1.unwrapDataKey)(material.getUnencryptedDataKey()); const encryptedDataKey = (0, crypto_1.publicEncrypt)({ key: publicKey, padding, oaepHash }, Buffer.from(buffer, byteOffset, byteLength)); const providerInfo = this.keyName; const providerId = this.keyNamespace; const flag = material_management_node_1.KeyringTraceFlag.WRAPPING_KEY_ENCRYPTED_DATA_KEY; const edk = new material_management_node_1.EncryptedDataKey({ encryptedDataKey, providerInfo, providerId, }); return material.addEncryptedDataKey(edk, flag); }; const _unwrapKey = async (material, edk) => { /* Precondition: Private key must be defined to support decrypt. */ if (!privateKey) throw new Error('No private key defined in constructor. Decrypt disabled.'); const trace = { keyName: this.keyName, keyNamespace: this.keyNamespace, flags: material_management_node_1.KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY, }; const { buffer, byteOffset, byteLength } = edk.encryptedDataKey; const encryptedDataKey = Buffer.from(buffer, byteOffset, byteLength); const unencryptedDataKey = (0, crypto_1.privateDecrypt)({ key: privateKey, padding, oaepHash }, encryptedDataKey); return material.setUnencryptedDataKey(unencryptedDataKey, trace); }; (0, material_management_node_1.readOnlyProperty)(this, 'keyName', keyName); (0, material_management_node_1.readOnlyProperty)(this, 'keyNamespace', keyNamespace); (0, material_management_node_1.readOnlyProperty)(this, '_wrapKey', _wrapKey); (0, material_management_node_1.readOnlyProperty)(this, '_unwrapKey', _unwrapKey); } _filter({ providerId, providerInfo }) { const { keyNamespace, keyName } = this; return providerId === keyNamespace && providerInfo === keyName; } _onEncrypt = (0, raw_keyring_1._onEncrypt)(randomBytesAsync); _onDecrypt = (0, raw_keyring_1._onDecrypt)(); } exports.RawRsaKeyringNode = RawRsaKeyringNode; (0, material_management_node_1.immutableClass)(RawRsaKeyringNode); async function randomBytesAsync(size) { return new Promise((resolve, reject) => { (0, crypto_1.randomBytes)(size, (err, buffer) => { if (err) return reject(err); resolve(buffer); }); }); } //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicmF3X3JzYV9rZXlyaW5nX25vZGUuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvcmF3X3JzYV9rZXlyaW5nX25vZGUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7OztBQUV0QyxtRkFhNkM7QUFFN0MsbUNBT2U7QUFFZix5REFLZ0M7QUFFaEMsK0RBQXlEO0FBa0J6RCxNQUFNLGlCQUFpQixHQUFlO0lBQ3BDLE1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Sx3QkFBVSxFQUNyQixnQkFBZ0IsQ0FDakIsQ0FBQTtJQUNELFVBQVUsR0FBRyxJQUFBLHdCQUFVLEdBQXlDLENBQUE7Q0FDakU7QUEvRkQsOENBK0ZDO0FBQ0QsSUFBQSx5Q0FBYyxFQUFDLGlCQUFpQixDQUFDLENBQUE7QUFFakMsS0FBSyxVQUFVLGdCQUFnQixDQUFDLElBQVk7SUFDMUMsT0FBTyxJQUFJLE9BQU8sQ0FBQyxDQUFDLE9BQU8sRUFBRSxNQUFNLEVBQUUsRUFBRTtRQUNyQyxJQUFBLG9CQUFXLEVBQUMsSUFBSSxFQUFFLENBQUMsR0FBaUIsRUFBRSxNQUFjLEVBQUUsRUFBRTtZQUN0RCxJQUFJLEdBQUc7Z0JBQUUsT0FBTyxNQUFNLENBQUMsR0FBRyxDQUFDLENBQUE7WUFDM0IsT0FBTyxDQUFDLE1BQU0sQ0FBQyxDQUFBO1FBQ2pCLENBQUMsQ0FBQyxDQUFBO0lBQ0osQ0FBQyxDQUFDLENBQUE7QUFDSixDQUFDIn0= /***/ }), /***/ 38822: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.aadFactory = void 0; /* * This public interface for constructing the additional authenticated data (AAD) * is provided for the use of the Encryption SDK for JavaScript only. It can be used * as a reference but is not intended to be use by any packages other than the * Encryption SDK for JavaScript. * * This AAD is used for the Body section * See: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/body-aad-reference.html */ const bn_js_1 = __importDefault(__nccwpck_require__(6641)); const identifiers_1 = __nccwpck_require__(79044); const concat_buffers_1 = __nccwpck_require__(29097); const uint_util_1 = __nccwpck_require__(57715); function aadFactory(fromUtf8) { return { messageAADContentString, messageAAD, }; function messageAADContentString({ contentType, isFinalFrame, }) { switch (contentType) { case identifiers_1.ContentType.NO_FRAMING: return identifiers_1.ContentAADString.NON_FRAMED_STRING_ID; case identifiers_1.ContentType.FRAMED_DATA: return isFinalFrame ? identifiers_1.ContentAADString.FINAL_FRAME_STRING_ID : identifiers_1.ContentAADString.FRAME_STRING_ID; default: throw new Error('Unrecognized content type'); } } function messageAAD(messageId, aadContentString, seqNum, contentLength) { return (0, concat_buffers_1.concatBuffers)(messageId, fromUtf8(aadContentString), (0, uint_util_1.uInt32BE)(seqNum), new Uint8Array(new bn_js_1.default(contentLength).toArray('be', 8))); } } exports.aadFactory = aadFactory; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYWFkX2ZhY3RvcnkuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvYWFkX2ZhY3RvcnkudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7Ozs7OztBQUV0Qzs7Ozs7Ozs7R0FRRztBQUVILGtEQUFzQjtBQUN0QiwrQ0FBNkQ7QUFFN0QscURBQWdEO0FBQ2hELDJDQUFzQztBQUV0QyxTQUFnQixVQUFVLENBQUMsUUFBdUM7SUFDaEUsT0FBTztRQUNMLHVCQUF1QjtRQUN2QixVQUFVO0tBQ1gsQ0FBQTtJQUVELFNBQVMsdUJBQXVCLENBQUMsRUFDL0IsV0FBVyxFQUNYLFlBQVksR0FJYjtRQUNDLFFBQVEsV0FBVyxFQUFFO1lBQ25CLEtBQUsseUJBQVcsQ0FBQyxVQUFVO2dCQUN6QixPQUFPLDhCQUFnQixDQUFDLG9CQUFvQixDQUFBO1lBQzlDLEtBQUsseUJBQVcsQ0FBQyxXQUFXO2dCQUMxQixPQUFPLFlBQVk7b0JBQ2pCLENBQUMsQ0FBQyw4QkFBZ0IsQ0FBQyxxQkFBcUI7b0JBQ3hDLENBQUMsQ0FBQyw4QkFBZ0IsQ0FBQyxlQUFlLENBQUE7WUFDdEM7Z0JBQ0UsTUFBTSxJQUFJLEtBQUssQ0FBQywyQkFBMkIsQ0FBQyxDQUFBO1NBQy9DO0lBQ0gsQ0FBQztJQUVELFNBQVMsVUFBVSxDQUNqQixTQUFxQixFQUNyQixnQkFBa0MsRUFDbEMsTUFBYyxFQUNkLGFBQXFCO1FBRXJCLE9BQU8sSUFBQSw4QkFBYSxFQUNsQixTQUFTLEVBQ1QsUUFBUSxDQUFDLGdCQUFnQixDQUFDLEVBQzFCLElBQUEsb0JBQVEsRUFBQyxNQUFNLENBQUMsRUFDaEIsSUFBSSxVQUFVLENBQUMsSUFBSSxlQUFFLENBQUMsYUFBYSxDQUFDLENBQUMsT0FBTyxDQUFDLElBQUksRUFBRSxDQUFDLENBQUMsQ0FBQyxDQUN2RCxDQUFBO0lBQ0gsQ0FBQztBQUNILENBQUM7QUF0Q0QsZ0NBc0NDIn0= /***/ }), /***/ 29097: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.concatBuffers = void 0; function concatBuffers(...inputBuffers) { const neededLength = inputBuffers.reduce((sum, buff) => sum + buff.byteLength, 0); const outputBuffer = new Uint8Array(neededLength); let offset = 0; inputBuffers.forEach((buff) => { if (ArrayBuffer.isView(buff)) { const { buffer, byteOffset, byteLength } = buff; outputBuffer.set(new Uint8Array(buffer, byteOffset, byteLength), offset); } else { outputBuffer.set(new Uint8Array(buff), offset); } offset += buff.byteLength; }); return outputBuffer; } exports.concatBuffers = concatBuffers; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uY2F0X2J1ZmZlcnMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvY29uY2F0X2J1ZmZlcnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7OztBQUl0QyxTQUFnQixhQUFhLENBQzNCLEdBQUcsWUFBOEM7SUFFakQsTUFBTSxZQUFZLEdBQUcsWUFBWSxDQUFDLE1BQU0sQ0FDdEMsQ0FBQyxHQUFHLEVBQUUsSUFBSSxFQUFFLEVBQUUsQ0FBQyxHQUFHLEdBQUcsSUFBSSxDQUFDLFVBQVUsRUFDcEMsQ0FBQyxDQUNGLENBQUE7SUFDRCxNQUFNLFlBQVksR0FBRyxJQUFJLFVBQVUsQ0FBQyxZQUFZLENBQUMsQ0FBQTtJQUNqRCxJQUFJLE1BQU0sR0FBRyxDQUFDLENBQUE7SUFFZCxZQUFZLENBQUMsT0FBTyxDQUFDLENBQUMsSUFBSSxFQUFFLEVBQUU7UUFDNUIsSUFBSSxXQUFXLENBQUMsTUFBTSxDQUFDLElBQUksQ0FBQyxFQUFFO1lBQzVCLE1BQU0sRUFBRSxNQUFNLEVBQUUsVUFBVSxFQUFFLFVBQVUsRUFBRSxHQUFHLElBQUksQ0FBQTtZQUMvQyxZQUFZLENBQUMsR0FBRyxDQUFDLElBQUksVUFBVSxDQUFDLE1BQU0sRUFBRSxVQUFVLEVBQUUsVUFBVSxDQUFDLEVBQUUsTUFBTSxDQUFDLENBQUE7U0FDekU7YUFBTTtZQUNMLFlBQVksQ0FBQyxHQUFHLENBQUMsSUFBSSxVQUFVLENBQUMsSUFBSSxDQUFDLEVBQUUsTUFBTSxDQUFDLENBQUE7U0FDL0M7UUFDRCxNQUFNLElBQUksSUFBSSxDQUFDLFVBQVUsQ0FBQTtJQUMzQixDQUFDLENBQUMsQ0FBQTtJQUVGLE9BQU8sWUFBWSxDQUFBO0FBQ3JCLENBQUM7QUFyQkQsc0NBcUJDIn0= /***/ }), /***/ 93696: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.decodeNonFrameBodyHeader = exports.decodeFinalFrameBodyHeader = exports.decodeFrameBodyHeader = exports.decodeBodyHeader = void 0; const bn_js_1 = __importDefault(__nccwpck_require__(6641)); const identifiers_1 = __nccwpck_require__(79044); const material_management_1 = __nccwpck_require__(77519); /* * This public interface for reading the BodyHeader format is provided for * the use of the Encryption SDK for JavaScript only. It can be used * as a reference but is not intended to be use by any packages other * than the Encryption SDK for JavaScript. * * See: * https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/message-format.html#body-framing * https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/message-format.html#body-no-framing */ /** * decodeBodyHeader * * I need to be able to parse the BodyHeader, but since the data may be streamed * I may not have all the data yet. The caller is expected to maintain and append * to the buffer and call this function with the same readPos until the function * returns a BodyHeader. * * @param buffer Uint8Array * @param headerInfo HeaderInfo * @param readPos number * @returns BodyHeader|false */ function decodeBodyHeader(buffer, headerInfo, readPos) { /* Precondition: The contentType must be a supported format. */ (0, material_management_1.needs)(identifiers_1.ContentType[headerInfo.messageHeader.contentType], 'Unknown contentType'); switch (headerInfo.messageHeader.contentType) { case identifiers_1.ContentType.FRAMED_DATA: return decodeFrameBodyHeader(buffer, headerInfo, readPos); case identifiers_1.ContentType.NO_FRAMING: return decodeNonFrameBodyHeader(buffer, headerInfo, readPos); } return false; } exports.decodeBodyHeader = decodeBodyHeader; /** * Exported for testing. Used by decodeBodyHeader to compose a complete solution. * @param buffer Uint8Array * @param headerInfo HeaderInfo * @param readPos number */ function decodeFrameBodyHeader(buffer, headerInfo, readPos) { /* Precondition: The contentType must be FRAMED_DATA. */ (0, material_management_1.needs)(identifiers_1.ContentType.FRAMED_DATA === headerInfo.messageHeader.contentType, 'Unknown contentType'); const { frameLength } = headerInfo.messageHeader; const { ivLength, tagLength } = headerInfo.algorithmSuite; /* Uint8Array is a view on top of the underlying ArrayBuffer. * This means that raw underlying memory stored in the ArrayBuffer * may be larger than the Uint8Array. This is especially true of * the Node.js Buffer object. The offset and length *must* be * passed to the DataView otherwise I will get unexpected results. */ const dataView = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength); /* Precondition: decodeFrameBodyHeader readPos must be within the byte length of the buffer given. */ (0, material_management_1.needs)(dataView.byteLength >= readPos && readPos >= 0, 'readPos out of bounds.'); /* Check for early return (Postcondition): There must be enough data to decodeFrameBodyHeader. * The format expressed here is * SequenceIdentifier: Uint32 * IVLength: Uint8 * There is a special case where the SequenceIdentifier is the Final Frame. */ if (4 + ivLength + readPos > dataView.byteLength) return false; const sequenceNumber = dataView.getUint32(readPos); /* Postcondition: decodeFrameBodyHeader sequenceNumber must be greater than 0. */ (0, material_management_1.needs)(sequenceNumber > 0, 'Malformed sequenceNumber.'); if (sequenceNumber === identifiers_1.SequenceIdentifier.SEQUENCE_NUMBER_END) { return decodeFinalFrameBodyHeader(buffer, headerInfo, readPos); } const iv = buffer.slice((readPos += 4), (readPos += ivLength)); return { sequenceNumber, iv, contentLength: frameLength, readPos, tagLength, isFinalFrame: false, contentType: identifiers_1.ContentType.FRAMED_DATA, }; } exports.decodeFrameBodyHeader = decodeFrameBodyHeader; /** * Exported for testing. Used by decodeBodyHeader to compose a complete solution. * @param buffer Uint8Array * @param headerInfo HeaderInfo * @param readPos number */ function decodeFinalFrameBodyHeader(buffer, headerInfo, readPos) { /* Precondition: The contentType must be FRAMED_DATA to be a Final Frame. */ (0, material_management_1.needs)(identifiers_1.ContentType.FRAMED_DATA === headerInfo.messageHeader.contentType, 'Unknown contentType'); const { ivLength, tagLength } = headerInfo.algorithmSuite; /* Uint8Array is a view on top of the underlying ArrayBuffer. * This means that raw underlying memory stored in the ArrayBuffer * may be larger than the Uint8Array. This is especially true of * the Node.js Buffer object. The offset and length *must* be * passed to the DataView otherwise I will get unexpected results. */ const dataView = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength); /* Precondition: decodeFinalFrameBodyHeader readPos must be within the byte length of the buffer given. */ (0, material_management_1.needs)(dataView.byteLength >= readPos && readPos >= 0, 'readPos out of bounds.'); /* Check for early return (Postcondition): There must be enough data to decodeFinalFrameBodyHeader. * The format expressed here is * SEQUENCE_NUMBER_END: Uint32(FFFF) * SequenceIdentifier: Uint32 * IVLength: Uint8 * Reserved: Uint32 * ContentLength: Uint32 */ if (4 + 4 + ivLength + 4 + readPos > dataView.byteLength) return false; /* The precondition SEQUENCE_NUMBER_END: Uint32(FFFF) is handled above. */ const sequenceEnd = dataView.getUint32(readPos, false); // big endian /* Postcondition: sequenceEnd must be SEQUENCE_NUMBER_END. */ (0, material_management_1.needs)(sequenceEnd === identifiers_1.SequenceIdentifier.SEQUENCE_NUMBER_END, 'Malformed final frame: Invalid sequence number end value'); const sequenceNumber = dataView.getUint32((readPos += 4), false); // big endian /* Postcondition: decodeFinalFrameBodyHeader sequenceNumber must be greater than 0. */ (0, material_management_1.needs)(sequenceNumber > 0, 'Malformed sequenceNumber.'); const iv = buffer.slice((readPos += 4), (readPos += ivLength)); const contentLength = dataView.getUint32(readPos); /* Postcondition: The final frame MUST NOT exceed the frameLength. */ (0, material_management_1.needs)(headerInfo.messageHeader.frameLength >= contentLength, 'Final frame length exceeds frame length.'); return { sequenceNumber, iv, contentLength, readPos: readPos + 4, tagLength, isFinalFrame: true, contentType: identifiers_1.ContentType.FRAMED_DATA, }; } exports.decodeFinalFrameBodyHeader = decodeFinalFrameBodyHeader; /** * Exported for testing. Used by decodeBodyHeader to compose a complete solution. * @param buffer Uint8Array * @param headerInfo HeaderInfo * @param readPos number */ function decodeNonFrameBodyHeader(buffer, headerInfo, readPos) { /* Precondition: The contentType must be NO_FRAMING. */ (0, material_management_1.needs)(identifiers_1.ContentType.NO_FRAMING === headerInfo.messageHeader.contentType, 'Unknown contentType'); const { ivLength, tagLength } = headerInfo.algorithmSuite; /* Uint8Array is a view on top of the underlying ArrayBuffer. * This means that raw underlying memory stored in the ArrayBuffer * may be larger than the Uint8Array. This is especially true of * the Node.js Buffer object. The offset and length *must* be * passed to the DataView otherwise I will get unexpected results. */ const dataView = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength); /* Precondition: decodeNonFrameBodyHeader readPos must be within the byte length of the buffer given. */ (0, material_management_1.needs)(dataView.byteLength >= readPos && readPos >= 0, 'readPos out of bounds.'); /* Check for early return (Postcondition): There must be enough data to decodeNonFrameBodyHeader. * The format expressed here is * IVLength: Uint8 * ContentLength: Uint64 */ if (ivLength + 8 + readPos > dataView.byteLength) return false; const iv = buffer.slice(readPos, (readPos += ivLength)); const contentLengthBuff = buffer.slice(readPos, (readPos += 8)); const contentLengthBN = new bn_js_1.default([...contentLengthBuff], 16, 'be'); // This will throw if the number is larger than Number.MAX_SAFE_INTEGER. // i.e. a 53 bit number const contentLength = contentLengthBN.toNumber(); /* Postcondition: Non-framed content length MUST NOT exceed AES-GCM safe limits. * https://github.com/awslabs/aws-encryption-sdk-specification/blob/master/data-format/message-body.md#encrypted-content-length */ (0, material_management_1.needs)(identifiers_1.Maximum.BYTES_PER_AES_GCM_NONCE > contentLength, 'Content length out of bounds.'); return { sequenceNumber: 1, iv, contentLength, readPos, tagLength, isFinalFrame: true, contentType: identifiers_1.ContentType.NO_FRAMING, }; } exports.decodeNonFrameBodyHeader = decodeNonFrameBodyHeader; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVjb2RlX2JvZHlfaGVhZGVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL2RlY29kZV9ib2R5X2hlYWRlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUEsb0VBQW9FO0FBQ3BFLHNDQUFzQzs7Ozs7O0FBRXRDLGtEQUFzQjtBQUN0QiwrQ0FBd0U7QUFPeEUseUVBQXVEO0FBRXZEOzs7Ozs7Ozs7R0F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FQUFFLElBQUk7UUFDbEIsV0FBVyxFQUFFLHlCQUFXLENBQUMsVUFBVTtLQUNwQyxDQUFBO0FBQ0gsQ0FBQztBQTVERCw0REE0REMifQ== /***/ }), /***/ 84745: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.decodeEncryptionContextFactory = void 0; /* * This public interface for parsing the AWS Encryption SDK Message Header Format * is provided for the use of the Encryption SDK for JavaScript only. It can be used * as a reference but is not intended to be use by any packages other than the * Encryption SDK for JavaScript. * * See: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/message-format.html#header-structure */ const material_management_1 = __nccwpck_require__(77519); const read_element_1 = __nccwpck_require__(8385); // To deal with Browser and Node.js I inject a function to handle utf8 encoding. function decodeEncryptionContextFactory(toUtf8) { return decodeEncryptionContext; /** * Exported for testing. Used by deserializeMessageHeader to compose a complete solution. * @param encodedEncryptionContext Uint8Array */ function decodeEncryptionContext(encodedEncryptionContext) { const encryptionContext = Object.create(null); /* Check for early return (Postcondition): The case of 0 length is defined as an empty object. */ if (!encodedEncryptionContext.byteLength) { return Object.freeze(encryptionContext); } /* Uint8Array is a view on top of the underlying ArrayBuffer. * This means that raw underlying memory stored in the ArrayBuffer * may be larger than the Uint8Array. This is especially true of * the Node.js Buffer object. The offset and length *must* be * passed to the DataView otherwise I will get unexpected results. */ const dataView = new DataView(encodedEncryptionContext.buffer, encodedEncryptionContext.byteOffset, encodedEncryptionContext.byteLength); const pairsCount = dataView.getUint16(0, false); // big endian const elementInfo = (0, read_element_1.readElements)(pairsCount, 2, encodedEncryptionContext, 2); /* Postcondition: Since the encryption context has a length, it must have pairs. * Unlike the encrypted data key section, the encryption context has a length * element. This means I should always pass the entire section. */ if (!elementInfo) throw new Error('context parse error'); const { elements, readPos } = elementInfo; /* Postcondition: The byte length of the encodedEncryptionContext must match the readPos. */ (0, material_management_1.needs)(encodedEncryptionContext.byteLength === readPos, 'Overflow, too much data.'); for (let count = 0; count < pairsCount; count++) { const [key, value] = elements[count].map(toUtf8); /* Postcondition: The number of keys in the encryptionContext must match the pairsCount. * If the same Key value is serialized... */ (0, material_management_1.needs)(encryptionContext[key] === undefined, 'Duplicate encryption context key value.'); encryptionContext[key] = value; } Object.freeze(encryptionContext); return encryptionContext; } } exports.decodeEncryptionContextFactory = decodeEncryptionContextFactory; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVjb2RlX2VuY3J5cHRpb25fY29udGV4dC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9kZWNvZGVfZW5jcnlwdGlvbl9jb250ZXh0LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7QUFFdEM7Ozs7Ozs7R0FPRztBQUVILHlFQUEwRTtBQUMxRSxpREFBNkM7QUFFN0MsZ0ZBQWdGO0FBQ2hGLFNBQWdCLDhCQUE4QixDQUM1QyxNQUFxQztJQUVyQyxPQUFPLHVCQUF1QixDQUFBO0lBRTlCOzs7T0FHRztJQUNILFNBQVMsdUJBQXVCLENBQzlCLHdCQUFvQztRQUVwQyxNQUFNLGlCQUFpQixHQUFzQixNQUFNLENBQUMsTUFBTSxDQUFDLElBQUksQ0FBQyxDQUFBO1FBQ2hFLGlHQUFpRztRQUNqRyxJQUFJLENBQUMsd0JBQXdCLENBQUMsVUFBVSxFQUFFO1lBQ3hDLE9BQU8sTUFBTSxDQUFDLE1BQU0sQ0FBQyxpQkFBaUIsQ0FBQyxDQUFBO1NBQ3hDO1FBQ0Q7Ozs7O1dBS0c7UUFDSCxNQUFNLFFBQVEsR0FBRyxJQUFJLFFBQVEsQ0FDM0Isd0JBQXdCLENBQUMsTUFBTSxFQUMvQix3QkFBd0IsQ0FBQyxV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FCLENBQUM7QUFDSCxDQUFDO0FBekRELHdFQXlEQyJ9 /***/ }), /***/ 18210: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.deserializeEncryptedDataKeysFactory = void 0; /* * This public interface for parsing the AWS Encryption SDK Message Header Format * is provided for the use of the Encryption SDK for JavaScript only. It can be used * as a reference but is not intended to be use by any packages other than the * Encryption SDK for JavaScript. * * See: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/message-format.html#header-structure */ const material_management_1 = __nccwpck_require__(77519); const read_element_1 = __nccwpck_require__(8385); // To deal with Browser and Node.js I inject a function to handle utf8 encoding. function deserializeEncryptedDataKeysFactory(toUtf8) { return deserializeEncryptedDataKeys; /** * Exported for testing. Used by deserializeMessageHeader to compose a complete solution. * @param buffer Uint8Array * @param startPos number * @param deserializeOptions DeserializeOptions */ function deserializeEncryptedDataKeys(buffer, startPos, { maxEncryptedDataKeys } = { maxEncryptedDataKeys: false, }) { /* Precondition: startPos must be within the byte length of the buffer given. */ (0, material_management_1.needs)(buffer.byteLength >= startPos && startPos >= 0, 'startPos out of bounds.'); /* Precondition: deserializeEncryptedDataKeys needs a valid maxEncryptedDataKeys. */ (0, material_management_1.needs)(maxEncryptedDataKeys === false || maxEncryptedDataKeys >= 1, 'Invalid maxEncryptedDataKeys value.'); /* Check for early return (Postcondition): Need to have at least Uint16 (2) bytes of data. */ if (startPos + 2 > buffer.byteLength) return false; /* Uint8Array is a view on top of the underlying ArrayBuffer. * This means that raw underlying memory stored in the ArrayBuffer * may be larger than the Uint8Array. This is especially true of * the Node.js Buffer object. The offset and length *must* be * passed to the DataView otherwise I will get unexpected results. */ const dataView = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength); const encryptedDataKeysCount = dataView.getUint16(startPos, false); // big endian /* Precondition: There must be at least 1 EncryptedDataKey element. */ (0, material_management_1.needs)(encryptedDataKeysCount, 'No EncryptedDataKey found.'); /* Precondition: encryptedDataKeysCount must not exceed maxEncryptedDataKeys. */ (0, material_management_1.needs)(maxEncryptedDataKeys === false || encryptedDataKeysCount <= maxEncryptedDataKeys, 'maxEncryptedDataKeys exceeded.'); const elementInfo = (0, read_element_1.readElements)(encryptedDataKeysCount, 3, buffer, startPos + 2); /* Check for early return (Postcondition): readElement will return false if there is not enough data. * I can only continue if I have at least the entire EDK section. */ if (!elementInfo) return false; const { elements, readPos } = elementInfo; const encryptedDataKeys = elements.map(([rawId, rawInfo, encryptedDataKey]) => { const providerId = toUtf8(rawId); const providerInfo = toUtf8(rawInfo); return new material_management_1.EncryptedDataKey({ providerInfo, providerId, encryptedDataKey, rawInfo, }); }); Object.freeze(encryptedDataKeys); return { encryptedDataKeys, readPos }; } } exports.deserializeEncryptedDataKeysFactory = deserializeEncryptedDataKeysFactory; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVzZXJpYWxpemVfZW5jcnlwdGVkX2RhdGFfa2V5cy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9kZXNlcmlhbGl6ZV9lbmNyeXB0ZWRfZGF0YV9rZXlzLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7QUFFdEM7Ozs7Ozs7R0FPRztBQUVILHlFQUF5RTtBQUV6RSxpREFBNkM7QUFFN0MsZ0ZBQWdGO0FBQ2hGLFNBQWdCLG1DQUFtQyxDQUNqRCxNQUFxQztJQUVyQyxPQUFPLDRCQUE0QixDQUFBO0lBRW5DOzs7OztPQUtHO0lBQ0gsU0FBUyw0QkFBNEIsQ0FDbkMsTUFBa0IsRUFDbEIsUUFBZ0IsRUFDaEIsRUFBRSxvQkFBb0IsS0FBeUI7UUFDN0Msb0JBQW9CLEVBQUUsS0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xLQUFLLENBQUE7UUFDOUIsTUFBTSxFQUFFLFFBQVEsRUFBRSxPQUFPLEVBQUUsR0FBRyxXQUFXLENBQUE7UUFFekMsTUFBTSxpQkFBaUIsR0FBRyxRQUFRLENBQUMsR0FBRyxDQUNwQyxDQUFDLENBQUMsS0FBSyxFQUFFLE9BQU8sRUFBRSxnQkFBZ0IsQ0FBQyxFQUFFLEVBQUU7WUFDckMsTUFBTSxVQUFVLEdBQUcsTUFBTSxDQUFDLEtBQUssQ0FBQyxDQUFBO1lBQ2hDLE1BQU0sWUFBWSxHQUFHLE1BQU0sQ0FBQyxPQUFPLENBQUMsQ0FBQTtZQUNwQyxPQUFPLElBQUksc0NBQWdCLENBQUM7Z0JBQzFCLFlBQVk7Z0JBQ1osVUFBVTtnQkFDVixnQkFBZ0I7Z0JBQ2hCLE9BQU87YUFDUixDQUFDLENBQUE7UUFDSixDQUFDLENBQ0YsQ0FBQTtRQUNELE1BQU0sQ0FBQyxNQUFNLENBQUMsaUJBQWlCLENBQUMsQ0FBQTtRQUNoQyxPQUFPLEVBQUUsaUJBQWlCLEVBQUUsT0FBTyxFQUFFLENBQUE7SUFDdkMsQ0FBQztBQUNILENBQUM7QUFyRkQsa0ZBcUZDIn0= /***/ }), /***/ 25851: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.deserializeFactory = void 0; /* * This public interface for parsing the AWS Encryption SDK Message Header Format * is provided for the use of the Encryption SDK for JavaScript only. It can be used * as a reference but is not intended to be use by any packages other than the * Encryption SDK for JavaScript. * * See: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/message-format.html#header-structure */ const material_management_1 = __nccwpck_require__(77519); const decode_encryption_context_1 = __nccwpck_require__(84745); const deserialize_encrypted_data_keys_1 = __nccwpck_require__(18210); const deserialize_header_v1_1 = __nccwpck_require__(27258); const deserialize_header_v2_1 = __nccwpck_require__(75026); // To deal with Browser and Node.js I inject a function to handle utf8 encoding. function deserializeFactory(toUtf8, SdkSuite) { const decodeEncryptionContext = (0, decode_encryption_context_1.decodeEncryptionContextFactory)(toUtf8); const deserializeEncryptedDataKeys = (0, deserialize_encrypted_data_keys_1.deserializeEncryptedDataKeysFactory)(toUtf8); const deserializeHeaderV1 = (0, deserialize_header_v1_1.deserializeHeaderV1Factory)({ decodeEncryptionContext, deserializeEncryptedDataKeys, SdkSuite, }); const deserializeHeaderV2 = (0, deserialize_header_v2_1.deserializeHeaderV2Factory)({ decodeEncryptionContext, deserializeEncryptedDataKeys, SdkSuite, }); /* The first byte holds the message format version. * So this maps a version to a deserializer. */ const deserializeMap = new Map([ /* I have no idea why someone * is going to call me with an empty buffer. * But since that is clearly not enough data * the right thing seems to be to ask for more data. * An unknown version can't be invalid. */ [undefined, (_) => false], [1, deserializeHeaderV1], [2, deserializeHeaderV2], ]); return { deserializeMessageHeader, deserializeEncryptedDataKeys, decodeEncryptionContext, }; function deserializeMessageHeader(messageBuffer, deserializeOptions = { maxEncryptedDataKeys: false }) { const messageFormatVersion = messageBuffer[0]; const deserializer = deserializeMap.get(messageFormatVersion); /* Precondition: A valid deserializer must exist. */ (0, material_management_1.needs)(deserializer, 'Not a supported message format version.'); return deserializer(messageBuffer, deserializeOptions); } } exports.deserializeFactory = deserializeFactory; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVzZXJpYWxpemVfZmFjdG9yeS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9kZXNlcmlhbGl6ZV9mYWN0b3J5LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxvRUFBb0U7QUFDcEUsc0NBQXNDOzs7QUFFdEM7Ozs7Ozs7R0FPRztBQUVILHlFQUF1RTtBQU12RSwyRUFBNEU7QUFDNUUsdUZBQXVG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LENBQUMsR0FBRyxDQUFDLG9CQUFvQixDQUFDLENBQUE7UUFDN0Qsb0RBQW9EO1FBQ3BELElBQUEsMkJBQUssRUFBQyxZQUFZLEVBQUUseUNBQXlDLENBQUMsQ0FBQTtRQUU5RCxPQUFPLFlBQVksQ0FBQyxhQUFhLEVBQUUsa0JBQWtCLENBQUMsQ0FBQTtJQUN4RCxDQUFDO0FBQ0gsQ0FBQztBQXBERCxnREFvREMifQ== /***/ }), /***/ 27258: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.deserializeHeaderV1Factory = void 0; /* * This public interface for parsing the AWS Encryption SDK Message Header Format * is provided for the use of the Encryption SDK for JavaScript only. It can be used * as a reference but is not intended to be use by any packages other than the * Encryption SDK for JavaScript. * * See: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/message-format.html#header-structure */ const material_management_1 = __nccwpck_require__(77519); // To deal with Browser and Node.js I inject a function to handle utf8 encoding. function deserializeHeaderV1Factory({ decodeEncryptionContext, deserializeEncryptedDataKeys, SdkSuite, }) { return deserializeMessageHeaderV1; /** * deserializeMessageHeaderV1 * * I need to be able to parse the MessageHeader, but since the data may be streamed * I may not have all the data yet. The caller is expected to maintain and append * to the buffer and call this function with the same readPos until the function * returns a HeaderInfo. * * @param messageBuffer * @param deserializeOptions * @returns HeaderInfo|undefined */ function deserializeMessageHeaderV1(messageBuffer, deserializeOptions = { maxEncryptedDataKeys: false }) { /* Uint8Array is a view on top of the underlying ArrayBuffer. * This means that raw underlying memory stored in the ArrayBuffer * may be larger than the Uint8Array. This is especially true of * the Node.js Buffer object. The offset and length *must* be * passed to the DataView otherwise I will get unexpected results. */ const dataView = new DataView(messageBuffer.buffer, messageBuffer.byteOffset, messageBuffer.byteLength); /* Check for early return (Postcondition): Not Enough Data. Need to have at least 22 bytes of data to begin parsing. * The first 22 bytes of the header are fixed length. After that * there are 2 variable length sections. */ if (dataView.byteLength < 22) return false; // not enough data const version = dataView.getUint8(0); const type = dataView.getUint8(1); /* Precondition: version and type must be the required values. */ (0, material_management_1.needs)(version === material_management_1.MessageFormat.V1 && type === 128, version === 65 && type === 89 ? 'Malformed Header: This blob may be base64 encoded.' : 'Malformed Header.'); const suiteId = dataView.getUint16(2, false); // big endian /* Precondition: suiteId must be a non-committing algorithm suite. */ (0, material_management_1.needs)(material_management_1.NonCommittingAlgorithmSuiteIdentifier[suiteId], 'Unsupported algorithm suite.'); const messageId = messageBuffer.slice(4, 20); const contextLength = dataView.getUint16(20, false); // big endian /* Check for early return (Postcondition): Not Enough Data. Need to have all of the context in bytes before we can parse the next section. * This is the first variable length section. */ if (22 + contextLength > dataView.byteLength) return false; // not enough data const encryptionContext = decodeEncryptionContext(messageBuffer.slice(22, 22 + contextLength)); const dataKeyInfo = deserializeEncryptedDataKeys(messageBuffer, 22 + contextLength, deserializeOptions); /* Check for early return (Postcondition): Not Enough Data. deserializeEncryptedDataKeys will return false if it does not have enough data. * This is the second variable length section. */ if (!dataKeyInfo) return false; // not enough data const { encryptedDataKeys, readPos } = dataKeyInfo; /* I'm doing this here, after decodeEncryptionContext and deserializeEncryptedDataKeys * because they are the bulk of the header section. */ const algorithmSuite = new SdkSuite(suiteId); const { ivLength, tagLength } = algorithmSuite; const tagLengthBytes = tagLength / 8; const headerLength = readPos + 1 + 4 + 1 + 4; /* Check for early return (Postcondition): Not Enough Data. Need to have the remaining fixed length data to parse. */ if (headerLength + ivLength + tagLengthBytes > dataView.byteLength) return false; // not enough data const contentType = dataView.getUint8(readPos); const reservedBytes = dataView.getUint32(readPos + 1, false); // big endian /* Postcondition: reservedBytes are defined as 0,0,0,0 * See: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/message-format.html#header-reserved */ (0, material_management_1.needs)(reservedBytes === 0, 'Malformed Header'); const headerIvLength = dataView.getUint8(readPos + 1 + 4); /* Postcondition: The headerIvLength must match the algorithm suite specification. */ (0, material_management_1.needs)(headerIvLength === ivLength, 'Malformed Header'); const frameLength = dataView.getUint32(readPos + 1 + 4 + 1, false); // big endian const rawHeader = messageBuffer.slice(0, headerLength); const messageHeader = { version, type, suiteId, messageId, encryptionContext, encryptedDataKeys, contentType, headerIvLength, frameLength, }; const headerIv = messageBuffer.slice(headerLength, headerLength + ivLength); const headerAuthTag = messageBuffer.slice(headerLength + ivLength, headerLength + ivLength + tagLengthBytes); return { messageHeader, headerLength, rawHeader, algorithmSuite, headerAuth: { headerIv, headerAuthTag, headerAuthLength: headerIv.byteLength + headerAuthTag.byteLength, }, }; } } exports.deserializeHeaderV1Factory = deserializeHeaderV1Factory; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVzZXJpYWxpemVfaGVhZGVyX3YxLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL2Rlc2VyaWFsaXplX2hlYWRlcl92MS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUEsb0VBQW9FO0FBQ3BFLHNDQUFzQzs7O0FBRXRDOzs7Ozs7O0dBT0c7QUFFSCx5RUFRd0M7QUFReEMsZ0ZBQWdGO0FBQ2hGLFNBQWdCLDBCQUEwQixDQUErQixFQUN2RSx1QkFBdUIsRUFDdkIsNEJBQTRCLEVBQzVCLFFBQVEsR0FnQlQ7SUFDQyxPQUFPLDBCQUEwQixDQUFBO0lBRWpDOzs7Ozs7Ozs7OztPQVdHO0lBQ0gsU0FBUywwQkFBMEIsQ0FDakMsYUFBeUIsRUFDekIscUJBQXlDLEVBQUUsb0JBQW9CLEVBQUUsS0FBSyxFQUFFO1FBRXhFOzs7OztXQUtHO1FBQ0gsTUFBTSxRQUFRLEdBQUcsSUFBSSxRQUFRLENBQzNCLGFBQWEsQ0FBQyxNQUFNLEVBQ3BCLGFBQWEsQ0FBQyxVQUFVLEVBQ3hCL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UFhO2dCQUNiLGdCQUFnQixFQUFFLFFBQVEsQ0FBQyxVQUFVLEdBQUcsYUFBYSxDQUFDLFVBQVU7YUFDakU7U0FDRixDQUFBO0lBQ0gsQ0FBQztBQUNILENBQUM7QUF6SkQsZ0VBeUpDIn0= /***/ }), /***/ 75026: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.deserializeHeaderV2Factory = void 0; /* * This public interface for parsing the AWS Encryption SDK Message Header Format * is provided for the use of the Encryption SDK for JavaScript only. It can be used * as a reference but is not intended to be use by any packages other than the * Encryption SDK for JavaScript. * * See: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/message-format.html#header-structure */ const material_management_1 = __nccwpck_require__(77519); const identifiers_1 = __nccwpck_require__(79044); // To deal with Browser and Node.js I inject a function to handle utf8 encoding. function deserializeHeaderV2Factory({ decodeEncryptionContext, deserializeEncryptedDataKeys, SdkSuite, }) { return deserializeMessageHeaderV2; /** * deserializeMessageHeaderV2 * * I need to be able to parse the MessageHeader, but since the data may be streamed * I may not have all the data yet. The caller is expected to maintain and append * to the buffer and call this function with the same readPos until the function * returns a HeaderInfo. * * @param messageBuffer * @param deserializeOptions * @returns HeaderInfo|undefined */ function deserializeMessageHeaderV2(messageBuffer, deserializeOptions = { maxEncryptedDataKeys: false }) { /* Uint8Array is a view on top of the underlying ArrayBuffer. * This means that raw underlying memory stored in the ArrayBuffer * may be larger than the Uint8Array. This is especially true of * the Node.js Buffer object. The offset and length *must* be * passed to the DataView otherwise I will get unexpected results. */ const dataView = new DataView(messageBuffer.buffer, messageBuffer.byteOffset, messageBuffer.byteLength); /* Check for early return (Postcondition): Not Enough Data. Need to have at least 37 bytes of data to begin parsing. * The first 37 bytes of the header are fixed length. After that * there are 2 variable length sections. */ const fixedLengthHeaderPrefix = 1 + 2 + identifiers_1.MessageIdLength.V2 + 2; if (dataView.byteLength < fixedLengthHeaderPrefix) return false; // not enough data let headerReadPos = 0; const version = dataView.getUint8(headerReadPos); // Move pos Uint8 bytes headerReadPos += 1; /* Precondition: version must be the required value. */ (0, material_management_1.needs)(version === material_management_1.MessageFormat.V2, version === 65 ? 'Malformed Header: This blob may be base64 encoded.' : 'Malformed Header.'); // Read second and third bytes const suiteId = dataView.getUint16(headerReadPos, false); // big endian /* Precondition: suiteId must be a committing algorithm suite. */ (0, material_management_1.needs)(material_management_1.CommittingAlgorithmSuiteIdentifier[suiteId], 'Unsupported algorithm suite.'); // Move pos Uint16 bytes headerReadPos += 2; const messageId = messageBuffer.slice(headerReadPos, headerReadPos + identifiers_1.MessageIdLength.V2); // Move pos MessageIdLength.V2 bytes headerReadPos += identifiers_1.MessageIdLength.V2; const contextLength = dataView.getUint16(headerReadPos, false); // big endian // Move pos Uint16 bytes headerReadPos += 2; /* Check for early return (Postcondition): Not Enough Data. Caller must buffer all of the context before we can parse the next section. * This is the first variable length section. */ if (fixedLengthHeaderPrefix + contextLength > dataView.byteLength) return false; // not enough data const encryptionContext = decodeEncryptionContext(messageBuffer.slice(fixedLengthHeaderPrefix, fixedLengthHeaderPrefix + contextLength)); const dataKeyInfo = deserializeEncryptedDataKeys(messageBuffer, fixedLengthHeaderPrefix + contextLength, deserializeOptions); /* Check for early return (Postcondition): Not Enough Data. Caller must buffer all of the encrypted data keys before we can parse the next section. * deserializeEncryptedDataKeys will return false if it does not have enough data. * This is the second variable length section. */ if (!dataKeyInfo) return false; // not enough data const { encryptedDataKeys, readPos } = dataKeyInfo; /* I'm doing this here, after decodeEncryptionContext and deserializeEncryptedDataKeys * because they are the bulk of the header section. */ const algorithmSuite = new SdkSuite(suiteId); const { tagLength, suiteDataLength, ivLength } = algorithmSuite; /* Precondition UNTESTED: suiteId must match supported algorithm suite. * I'm doing this here to double up the check on suiteDataLength. * Ideally the types would all match up, * since all CommittingAlgorithmSuiteIdentifier will have `suiteDataLength`. * But my typescript foo is still not strong enough. */ (0, material_management_1.needs)(material_management_1.CommittingAlgorithmSuiteIdentifier[suiteId] && suiteDataLength, 'Unsupported algorithm suite.'); const tagLengthBytes = tagLength / 8; const headerLength = readPos + 1 + 4 + suiteDataLength; /* Check for early return (Postcondition): Not Enough Data. Need to have the header auth section. */ if (headerLength + tagLengthBytes > dataView.byteLength) return false; // not enough data // update to current position headerReadPos = readPos; const contentType = dataView.getUint8(headerReadPos); // Move pos Uint8 bytes headerReadPos += 1; const frameLength = dataView.getUint32(headerReadPos, false); // big endian // Move pos Uint32 bytes headerReadPos += 4; const suiteData = messageBuffer.slice(headerReadPos, headerReadPos + suiteDataLength); // Move pos suiteDataLength bytes headerReadPos += suiteDataLength; const rawHeader = messageBuffer.slice(0, headerLength); const messageHeader = { version, suiteId, messageId, encryptionContext, encryptedDataKeys, contentType, frameLength, suiteData, }; /* The V2 format is explicit about the IV. */ const headerIv = new Uint8Array(ivLength); const headerAuthTag = messageBuffer.slice(headerLength, headerLength + tagLengthBytes); return { messageHeader, headerLength, rawHeader, algorithmSuite, headerAuth: { headerIv, headerAuthTag, headerAuthLength: headerAuthTag.byteLength, }, }; } } exports.deserializeHeaderV2Factory = deserializeHeaderV2Factory; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVzZXJpYWxpemVfaGVhZGVyX3YyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL2Rlc2VyaWFsaXplX2hlYWRlcl92Mi50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUEsb0VBQW9FO0FBQ3BFLHNDQUFzQzs7O0FBRXRDOzs7Ozs7O0dBT0c7QUFFSCx5RUFPd0M7QUFDeEMsK0NBQStDO0FBUS9DLGdGQUFnRjtBQUNoRixTQUFnQiwwQkFBMEIsQ0FBK0IsRUFDdkUsdUJBQXVCLEVBQ3ZCLDRCQUE0QixFQUM1QixRQUFRLEd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0FBQyxFQUFFLFlBQVksQ0FBQyxDQUFBO1FBRXRELE1BQU0sYUFBYSxHQUFvQjtZQUNyQyxPQUFPO1lBQ1AsT0FBTztZQUNQLFNBQVM7WUFDVCxpQkFBaUI7WUFDakIsaUJBQWlCO1lBQ2pCLFdBQVc7WUFDWCxXQUFXO1lBQ1gsU0FBUztTQUNWLENBQUE7UUFFRCw2Q0FBNkM7UUFDN0MsTUFBTSxRQUFRLEdBQUcsSUFBSSxVQUFVLENBQUMsUUFBUSxDQUFDLENBQUE7UUFDekMsTUFBTSxhQUFhLEdBQUcsYUFBYSxDQUFDLEtBQUssQ0FDdkMsWUFBWSxFQUNaLFlBQVksR0FBRyxjQUFjLENBQzlCLENBQUE7UUFFRCxPQUFPO1lBQ0wsYUFBYTtZQUNiLFlBQVk7WUFDWixTQUFTO1lBQ1QsY0FBYztZQUNkLFVBQVUsRUFBRTtnQkFDVixRQUFRO2dCQUNSLGFBQWE7Z0JBQ2IsZ0JBQWdCLEVBQUUsYUFBYSxDQUFDLFVBQVU7YUFDM0M7U0FDRixDQUFBO0lBQ0gsQ0FBQztBQUNILENBQUM7QUF4TEQsZ0VBd0xDIn0= /***/ }), /***/ 45670: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.raw2der = exports.der2raw = void 0; /* WebCrypto expects the ECDSA signature to be "raw" formated. * e.g. concat(r,s) where r and s are padded to key length bytes. * The AWS Encryption SDK expects the signature to be DER encoded. * https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/message-format.html#footer-structure */ // @ts-ignore const asn1_js_1 = __importDefault(__nccwpck_require__(14293)); const concat_buffers_1 = __nccwpck_require__(29097); const material_management_1 = __nccwpck_require__(77519); // https://tools.ietf.org/html/rfc3279#section-2.2.2 const ECDSASignature = asn1_js_1.default.define('ECDSASignature', function () { this.seq().obj(this.key('r').int(), this.key('s').int()); }); // Map the ECDSA Curve to key lengths const keyLengthBytes = Object.freeze({ 'P-256': 32, 'P-384': 48, }); /** * WebCrypto subtle.verify expect the signature to be "raw" formated e.g. concat(r,s) * where r and s are padded to the key length in bytes. * * @param derSignature [Uint8Array] The DER formated signature from an Encryption SDK formated blob * @param suite [WebCryptoAlgorithmSuite] The Algorithm suite used to create the signature * @returns Uint8Array The raw formated signature (r,s) used to verify in WebCrypto */ function der2raw(derSignature, { signatureCurve }) { /* Precondition: Do not attempt to RAW format if the suite does not support signing. */ if (!signatureCurve) throw new Error('AlgorithmSuite does not support signing'); const _keyLengthBytes = keyLengthBytes[signatureCurve]; // A little more portable than Buffer.from, but not much const { r, s } = ECDSASignature.decode(new asn1_js_1.default.bignum.BN(derSignature).toArrayLike(Buffer), 'der'); const rLength = r.byteLength(); const sLength = s.byteLength(); return (0, concat_buffers_1.concatBuffers)(new Uint8Array(_keyLengthBytes - rLength), r.toArrayLike(Uint8Array), new Uint8Array(_keyLengthBytes - sLength), s.toArrayLike(Uint8Array)); } exports.der2raw = der2raw; /** * WebCrypto subtle.sign returns the signature "raw" formated e.g. concat(r,s) * where r and s are padded to the key length in bytes. * The Encryption SDK expects the signature to be DER encoded. * * @param rawSignature [Uint8Array] The "raw" formated signature from WebCrypto subtle.sign * @param suite [WebCryptoAlgorithmSuite] The Algorithm suite used to create the signature * @returns Uint8Array The DER formated signature */ function raw2der(rawSignature, { signatureCurve }) { /* Precondition: Do not attempt to DER format if the suite does not support signing. */ if (!signatureCurve) throw new Error('AlgorithmSuite does not support signing'); const { byteLength } = rawSignature; const _keyLengthBytes = keyLengthBytes[signatureCurve]; /* Precondition: The total raw signature length is twice the key length bytes. */ (0, material_management_1.needs)(byteLength === 2 * _keyLengthBytes, 'Malformed signature.'); /* A little more portable than Buffer.from, but not much. * DER encoding stores integers as signed values. * This means if the first bit is a 1, * the value will be interpreted as negative. * So an extra byte needs to be added on. * This is a problem because "raw" encoding is just r|s. * Without this "extra logic" a given DER signature `sig` *may* * raw2der(der2raw(sig)) !== sig * see: https://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf 8.3 * All of this means that s and r **MUST** be passed as BN, * and NOT bytes. * Otherwise you need to interpret this padding yourself. */ const r = new asn1_js_1.default.bignum.BN(rawSignature.slice(0, _keyLengthBytes)); const s = new asn1_js_1.default.bignum.BN(rawSignature.slice(_keyLengthBytes)); return ECDSASignature.encode({ r, s }, 'der'); } exports.raw2der = raw2der; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZWNkc2Ffc2lnbmF0dXJlLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL2VjZHNhX3NpZ25hdHVyZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUEsb0VBQW9FO0FBQ3BFLHNDQUFzQzs7Ozs7O0FBRXRDOzs7O0dBSUc7QUFFSCxhQUFhO0FBQ2Isc0RBQXlCO0FBQ3pCLHFEQUFnRDtBQUNoRCx5RUFJd0M7QUFFeEMsb0RBQW9EO0FBQ3BELE1BQU0sY0FBYyxHQUFHLGlCQUFHLENBQUMsTUFBTSxDQUFDLGdCQUFnQixFQUFFO0lBQ2xELElBQUksQ0FBQyxHQUFHLEVBQUUsQ0FBQyxHQUFHLENBQUMsSUFBSSxDQUFDLEdBQUcsQ0FBQyxHQUFHLENBQUMsQ0FBQyxHQUFHLEVBQUUsRUFBRSxJQUFJLENBQUMsR0FBRyxDQUFDLEdBQUcsQ0FBQyxDQUFDLEdBQUcsRUFBRSxDQUFDLENBQUE7QUFDMUQsQ0FBQyxDQUFDLENBQUE7QUFFRixxQ0FBcUM7QUFDckMsTUFBTSxjQUFjLEdBQTRDLE1BQU0sQ0FBQyxNQUFNLENBQUM7SUFDNUUsT0FBTyxFQUFFLEVBQ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0lBQ3ZGLElBQUksQ0FBQyxjQUFjO1FBQ2pCLE1BQU0sSUFBSSxLQUFLLENBQUMseUNBQXlDLENBQUMsQ0FBQTtJQUU1RCxNQUFNLEVBQUUsVUFBVSxFQUFFLEdBQUcsWUFBWSxDQUFBO0lBRW5DLE1BQU0sZUFBZSxHQUFHLGNBQWMsQ0FBQyxjQUFjLENBQUMsQ0FBQTtJQUV0RCxpRkFBaUY7SUFDakYsSUFBQSwyQkFBSyxFQUFDLFVBQVUsS0FBSyxDQUFDLEdBQUcsZUFBZSxFQUFFLHNCQUFzQixDQUFDLENBQUE7SUFFakU7Ozs7Ozs7Ozs7OztPQVlHO0lBQ0gsTUFBTSxDQUFDLEdBQUcsSUFBSSxpQkFBRyxDQUFDLE1BQU0sQ0FBQyxFQUFFLENBQUMsWUFBWSxDQUFDLEtBQUssQ0FBQyxDQUFDLEVBQUUsZUFBZSxDQUFDLENBQUMsQ0FBQTtJQUNuRSxNQUFNLENBQUMsR0FBRyxJQUFJLGlCQUFHLENBQUMsTUFBTSxDQUFDLEVBQUUsQ0FBQyxZQUFZLENBQUMsS0FBSyxDQUFDLGVBQWUsQ0FBQyxDQUFDLENBQUE7SUFFaEUsT0FBTyxjQUFjLENBQUMsTUFBTSxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsRUFBRSxFQUFFLEtBQUssQ0FBQyxDQUFBO0FBQy9DLENBQUM7QUFoQ0QsMEJBZ0NDIn0= /***/ }), /***/ 79044: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MESSAGE_ID_LENGTH = exports.MessageIdLength = exports.FRAME_LENGTH = exports.Maximum = exports.SequenceIdentifier = exports.ObjectType = exports.ContentAADString = exports.ContentType = exports.SerializationVersion = exports.ENCODED_SIGNER_KEY = void 0; /* * This public interface for constants is provided for * the use of the Encryption SDK for JavaScript only. It can be used * as a reference but is not intended to be use by any packages other * than the Encryption SDK for JavaScript. * * See: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/reference.html * * https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/message-format.html#header-aad (algorithms with signing) * https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/message-format.html#header-version * https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/message-format.html#header-content-type * https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/body-aad-reference.html (Body AAD Content) * https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/message-format.html#header-type * https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/body-aad-reference.html#body-aad-sequence-number */ exports.ENCODED_SIGNER_KEY = 'aws-crypto-public-key'; /** @deprecated use import { MessageFormat } from '@aws-crypto/material-management' */ var material_management_1 = __nccwpck_require__(77519); Object.defineProperty(exports, "SerializationVersion", ({ enumerable: true, get: function () { return material_management_1.MessageFormat; } })); var ContentType; (function (ContentType) { ContentType[ContentType["NO_FRAMING"] = 1] = "NO_FRAMING"; ContentType[ContentType["FRAMED_DATA"] = 2] = "FRAMED_DATA"; })(ContentType = exports.ContentType || (exports.ContentType = {})); Object.freeze(ContentType); var ContentAADString; (function (ContentAADString) { ContentAADString["FRAME_STRING_ID"] = "AWSKMSEncryptionClient Frame"; ContentAADString["FINAL_FRAME_STRING_ID"] = "AWSKMSEncryptionClient Final Frame"; ContentAADString["NON_FRAMED_STRING_ID"] = "AWSKMSEncryptionClient Single Block"; })(ContentAADString = exports.ContentAADString || (exports.ContentAADString = {})); Object.freeze(ContentAADString); var ObjectType; (function (ObjectType) { ObjectType[ObjectType["CUSTOMER_AE_DATA"] = 128] = "CUSTOMER_AE_DATA"; })(ObjectType = exports.ObjectType || (exports.ObjectType = {})); Object.freeze(ObjectType); var SequenceIdentifier; (function (SequenceIdentifier) { SequenceIdentifier[SequenceIdentifier["SEQUENCE_NUMBER_END"] = 4294967295] = "SEQUENCE_NUMBER_END"; })(SequenceIdentifier = exports.SequenceIdentifier || (exports.SequenceIdentifier = {})); Object.freeze(SequenceIdentifier); var Maximum; (function (Maximum) { // Maximum number of messages which are allowed to be encrypted under a single cached data key Maximum[Maximum["MESSAGES_PER_CACHED_KEY_LIMIT"] = 4294967296] = "MESSAGES_PER_CACHED_KEY_LIMIT"; /* Maximum number of bytes that are allowed to be encrypted * under a single cached data key across messages. * The maximum value defined in the AWS Encryption SDK specification is 2 ** 63 - 1. * However Javascript can only perform safe operations on values * up to Number.MAX_SAFE_INTEGER === 9007199254740991 === 2 ** 53 - 1. * e.g * Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2 => true * Number.MAX_SAFE_INTEGER + 1 > Number.MAX_SAFE_INTEGER + 2 => false * Number.MAX_SAFE_INTEGER + 1 < Number.MAX_SAFE_INTEGER + 2 => false * * This means that after 2 ** 53 - 1 the process of accumulating a byte count * will never yield an accurate comparison and so, never halt. * * The choice here to use 2 ** 53 - 1 instead of Number.MAX_SAFE_INTEGER is deliberate. * This is because in the future Number.MAX_SAFE_INTEGER could be raised to 2 ** 66 * or some value larger 2 ** 63. */ Maximum[Maximum["BYTES_PER_CACHED_KEY_LIMIT"] = 9007199254740991] = "BYTES_PER_CACHED_KEY_LIMIT"; /* This value should be Maximum.FRAME_COUNT * Maximum.FRAME_SIZE. * However this would be ~ 2 ** 64, much larger than Number.MAX_SAFE_INTEGER. * For the same reasons outlined above in BYTES_PER_CACHED_KEY_LIMIT * this value is set to 2 ** 53 - 1. */ Maximum[Maximum["BYTES_PER_MESSAGE"] = 9007199254740991] = "BYTES_PER_MESSAGE"; /* Maximum number of bytes for a single AES-GCM "operation." * This is related to the GHASH block size, * and can be thought of as the maximum bytes * that can be encrypted with a single key/IV pair. * The AWS Encryption SDK for Javascript * does not support non-framed encrypt * https://github.com/awslabs/aws-encryption-sdk-specification/blob/master/data-format/message-body.md#non-framed-data * So this value is only needed to ensure * that messages submitted for decrypt * are well formed. */ Maximum[Maximum["BYTES_PER_AES_GCM_NONCE"] = 68719476704] = "BYTES_PER_AES_GCM_NONCE"; // Maximum number of frames allowed in one message as defined in specification Maximum[Maximum["FRAME_COUNT"] = 4294967295] = "FRAME_COUNT"; // Maximum bytes allowed in a single frame as defined in specification Maximum[Maximum["FRAME_SIZE"] = 4294967295] = "FRAME_SIZE"; // Maximum bytes allowed in a non-framed message ciphertext as defined in specification Maximum[Maximum["GCM_CONTENT_SIZE"] = 4294967295] = "GCM_CONTENT_SIZE"; Maximum[Maximum["NON_FRAMED_SIZE"] = 4294967295] = "NON_FRAMED_SIZE"; // Maximum number of AAD bytes allowed as defined in specification Maximum[Maximum["AAD_BYTE_SIZE"] = 65535] = "AAD_BYTE_SIZE"; })(Maximum = exports.Maximum || (exports.Maximum = {})); Object.freeze(Maximum); // Default frame length when using framing exports.FRAME_LENGTH = 4096; // Message ID length as defined in specification var MessageIdLength; (function (MessageIdLength) { MessageIdLength[MessageIdLength["V1"] = 16] = "V1"; MessageIdLength[MessageIdLength["V2"] = 32] = "V2"; })(MessageIdLength = exports.MessageIdLength || (exports.MessageIdLength = {})); Object.freeze(MessageIdLength); /** @deprecated use MessageIdLength */ exports.MESSAGE_ID_LENGTH = MessageIdLength.V1; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaWRlbnRpZmllcnMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaWRlbnRpZmllcnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7OztBQUV0Qzs7Ozs7Ozs7Ozs7Ozs7R0FjRztBQUVVLFFBQUEsa0JBQWtCLEdBQUcsdUJBQXVCLENBQUE7QUFDekQsc0ZBQXNGO0FBQ3RGLHVFQUF1RjtBQUE5RSwySEFBQSxhQUFhLE9BQXdCO0FBRTlDLElBQVksV0FHWDtBQUhELFdBQVks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O0lBQ3RDLDhFQUE4RTtJQUM5RSw0REFBeUIsQ0FBQTtJQUN6QixzRUFBc0U7SUFDdEUsMERBQXdCLENBQUE7SUFDeEIsdUZBQXVGO0lBQ3ZGLHNFQUE4QixDQUFBO0lBQzlCLG9FQUE2QixDQUFBO0lBQzdCLGtFQUFrRTtJQUNsRSwyREFBMkIsQ0FBQTtBQUM3QixDQUFDLEVBaERXLE9BQU8sR0FBUCxlQUFPLEtBQVAsZUFBTyxRQWdEbEI7QUFDRCxNQUFNLENBQUMsTUFBTSxDQUFDLE9BQU8sQ0FBQyxDQUFBO0FBRXRCLDBDQUEwQztBQUM3QixRQUFBLFlBQVksR0FBRyxJQUFJLENBQUE7QUFDaEMsZ0RBQWdEO0FBQ2hELElBQVksZUFHWDtBQUhELFdBQVksZUFBZTtJQUN6QixrREFBTyxDQUFBO0lBQ1Asa0RBQU8sQ0FBQTtBQUNULENBQUMsRUFIVyxlQUFlLEdBQWYsdUJBQWUsS0FBZix1QkFBZSxRQUcxQjtBQUNELE1BQU0sQ0FBQyxNQUFNLENBQUMsZUFBZSxDQUFDLENBQUE7QUFFOUIsc0NBQXNDO0FBQ3pCLFFBQUEsaUJBQWlCLEdBQUcsZUFBZSxDQUFDLEVBQUUsQ0FBQSJ9 /***/ }), /***/ 26683: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 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__(38822), exports); __exportStar(__nccwpck_require__(29097), exports); __exportStar(__nccwpck_require__(93696), exports); __exportStar(__nccwpck_require__(25851), exports); __exportStar(__nccwpck_require__(68797), exports); __exportStar(__nccwpck_require__(81942), exports); __exportStar(__nccwpck_require__(19617), exports); __exportStar(__nccwpck_require__(79044), exports); __exportStar(__nccwpck_require__(57715), exports); __exportStar(__nccwpck_require__(30959), exports); __exportStar(__nccwpck_require__(45670), exports); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7Ozs7Ozs7Ozs7Ozs7Ozs7QUFFdEMsZ0RBQTZCO0FBQzdCLG1EQUFnQztBQUNoQyx1REFBb0M7QUFDcEMsd0RBQXFDO0FBQ3JDLDZDQUEwQjtBQUMxQixzREFBbUM7QUFDbkMsMENBQXVCO0FBQ3ZCLGdEQUE2QjtBQUM3Qiw4Q0FBMkI7QUFDM0IsbURBQWdDO0FBQ2hDLG9EQUFpQyJ9 /***/ }), /***/ 68797: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.kdfCommitKeyInfo = exports.kdfInfo = void 0; /* * This public interface for constructing info for the extract step of the KDF * is provided for the use of the Encryption SDK for JavaScript only. It can be used * as a reference but is not intended to be use by any packages other than the * Encryption SDK for JavaScript. * * See: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/algorithms-reference.html * The Key Derivation Algorithm section */ const material_management_1 = __nccwpck_require__(77519); const concat_buffers_1 = __nccwpck_require__(29097); const uint_util_1 = __nccwpck_require__(57715); function kdfInfo(suiteId, messageId) { /* Precondition: Info for non-committing suites *only*. */ (0, material_management_1.needs)(material_management_1.NonCommittingAlgorithmSuiteIdentifier[suiteId], 'Committing algorithm suite not supported.'); return (0, concat_buffers_1.concatBuffers)((0, uint_util_1.uInt16BE)(suiteId), messageId); } exports.kdfInfo = kdfInfo; /* Since these values are static * there is no need to import * a fromUtf8 function to convert them. * * [...Buffer.from('DERIVEKEY')] * 1. KeyLabel := DERIVEKEY as UTF-8 encoded bytes * [...Buffer.from('COMMITKEY')] * 2. CommitLabel := COMMITKEY as UTF-8 encoded bytes */ const KEY_LABEL = new Uint8Array([68, 69, 82, 73, 86, 69, 75, 69, 89]); const COMMIT_LABEL = new Uint8Array([67, 79, 77, 77, 73, 84, 75, 69, 89]); function kdfCommitKeyInfo(suite) { /* Precondition: Info for committing algorithm suites only. */ (0, material_management_1.needs)(suite.commitment === 'KEY', 'Non committing algorithm suite not supported.'); return { keyLabel: (0, concat_buffers_1.concatBuffers)((0, uint_util_1.uInt16BE)(suite.id), KEY_LABEL), commitLabel: COMMIT_LABEL.slice(), }; } exports.kdfCommitKeyInfo = kdfCommitKeyInfo; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoia2RmX2luZm8uanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMva2RmX2luZm8udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7OztBQUV0Qzs7Ozs7Ozs7R0FRRztBQUVILHlFQUt3QztBQUV4QyxxREFBZ0Q7QUFDaEQsMkNBQXNDO0FBRXRDLFNBQWdCLE9BQU8sQ0FDckIsT0FBaUMsRUFDakMsU0FBcUI7SUFFckIsMERBQTBEO0lBQzFELElBQUEsMkJBQUssRUFDSCwyREFBcUMsQ0FBQyxPQUFPLENBQUMsRUFDOUMsMkNBQTJDLENBQzVDLENBQUE7SUFDRCxPQUFPLElBQUEsOEJBQWEsRUFBQyxJQUFBLG9CQUFRLEVBQUMsT0FBTyxDQUFDLEVBQUUsU0FBUyxDQUFDLENBQUE7QUFDcEQsQ0FBQztBQVZELDBCQVVDO0FBRUQ7Ozs7Ozs7O0dBUUc7QUFDSCxNQUFNLFNBQVMsR0FBRyxJQUFJLFVBQVUsQ0FBQyxDQUFDLEVBQUUsRUFBRSxFQUFFLEVBQUUsRUFBRSxFQUFFLEVBQUUsRUFBRSxFQUFFLEVBQUUsRUFBRSxFQUFFLEVBQUUsRUFBRSxFQUFFLEVBQUUsRUFBRSxDQUFDLENBQUMsQ0FBQTtBQUN0RSxNQUFNLFlBQVksR0FBRyxJQUFJLFVBQVUsQ0FBQyxDQUFDLEVBQUUsRUFBRSxFQUFFLEVBQUUsRUFBRSxFQUFFLEVBQUUsRUFBRSxFQUFFLEVBQUUsRUFBRSxFQUFFLEVBQUUsRUFBRSxFQUFFLEVBQUUsRUFBRSxDQUFDLENBQUMsQ0FBQTtBQUV6RSxTQUFnQixnQkFBZ0IsQ0FBQyxLQUFxQjtJQUNwRCw4REFBOEQ7SUFDOUQsSUFBQSwyQkFBSyxFQUNILEtBQUssQ0FBQyxVQUFVLEtBQUssS0FBSyxFQUMxQiwrQ0FBK0MsQ0FDaEQsQ0FBQTtJQUNELE9BQU87UUFDTCxRQUFRLEVBQUUsSUFBQSw4QkFBYSxFQUFDLElBQUEsb0JBQVEsRUFBQyxLQUFLLENBQUMsRUFBRSxDQUFDLEVBQUUsU0FBUyxDQUFDO1FBQ3RELFdBQVcsRUFBRSxZQUFZLENBQUMsS0FBSyxFQUFFO0tBQ2xDLENBQUE7QUFDSCxDQUFDO0FBVkQsNENBVUMifQ== /***/ }), /***/ 8385: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.readElements = void 0; /* * This public interface for reading part of the encrypted header is provided for * the use of the Encryption SDK for JavaScript only. It can be used * as a reference but is not intended to be use by any packages other * than the Encryption SDK for JavaScript. * * This is used to read the AAD Section and the Encrypted Data Key(s) section. * * See: * https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/message-format.html#header-aad * https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/message-format.html#header-data-keys */ const material_management_1 = __nccwpck_require__(77519); /** * * The encryption SDK stores elements in the form of length data. * e.g. 04data. The length element is Uint16 Big Endian. * So knowing the number of elements of this form I can * advance through a buffer. The rub comes when streaming * data. The I may know the number of elements, but not * yet have all the data. In this case I check the lengths and * return false. * * @param elementCount * @param buffer * @param readPos */ function readElements(elementCount, fieldsPerElement, buffer, readPos = 0) { /* Uint8Array is a view on top of the underlying ArrayBuffer. * This means that raw underlying memory stored in the ArrayBuffer * may be larger than the Uint8Array. This is especially true of * the Node.js Buffer object. The offset and length *must* be * passed to the DataView otherwise I will get unexpected results. */ const dataView = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength); const elements = []; /* Precondition: readPos must be non-negative and within the byte length of the buffer given. */ (0, material_management_1.needs)(readPos >= 0 && dataView.byteLength >= readPos, 'readPos out of bounds.'); /* Precondition: elementCount and fieldsPerElement must be non-negative. */ (0, material_management_1.needs)(elementCount >= 0 && fieldsPerElement >= 0, 'elementCount and fieldsPerElement must be positive.'); while (elementCount--) { const element = []; let fieldCount = fieldsPerElement; while (fieldCount--) { /* Check for early return (Postcondition): Enough data must exist to read the Uint16 length value. */ if (readPos + 2 > dataView.byteLength) return false; const length = dataView.getUint16(readPos, false); // big endian readPos += 2; /* Check for early return (Postcondition): Enough data must exist length of the value. */ if (readPos + length > dataView.byteLength) return false; const fieldBinary = buffer.slice(readPos, readPos + length); element.push(fieldBinary); readPos += length; } elements.push(element); } return { elements, readPos }; } exports.readElements = readElements; //# sourceMappingURL=data:application/json;base64,eyJ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BUSxDQUFDLFVBQVU7Z0JBQUUsT0FBTyxLQUFLLENBQUE7WUFDbkQsTUFBTSxNQUFNLEdBQUcsUUFBUSxDQUFDLFNBQVMsQ0FBQyxPQUFPLEVBQUUsS0FBSyxDQUFDLENBQUEsQ0FBQyxhQUFhO1lBQy9ELE9BQU8sSUFBSSxDQUFDLENBQUE7WUFDWix5RkFBeUY7WUFDekYsSUFBSSxPQUFPLEdBQUcsTUFBTSxHQUFHLFFBQVEsQ0FBQyxVQUFVO2dCQUFFLE9BQU8sS0FBSyxDQUFBO1lBQ3hELE1BQU0sV0FBVyxHQUFHLE1BQU0sQ0FBQyxLQUFLLENBQUMsT0FBTyxFQUFFLE9BQU8sR0FBRyxNQUFNLENBQUMsQ0FBQTtZQUMzRCxPQUFPLENBQUMsSUFBSSxDQUFDLFdBQVcsQ0FBQyxDQUFBO1lBQ3pCLE9BQU8sSUFBSSxNQUFNLENBQUE7U0FDbEI7UUFDRCxRQUFRLENBQUMsSUFBSSxDQUFDLE9BQU8sQ0FBQyxDQUFBO0tBQ3ZCO0lBQ0QsT0FBTyxFQUFFLFFBQVEsRUFBRSxPQUFPLEVBQUUsQ0FBQTtBQUM5QixDQUFDO0FBaERELG9DQWdEQyJ9 /***/ }), /***/ 81942: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.serializeMessageHeaderAuth = exports.serializeFactory = void 0; /* * This public interface for serializing the AWS Encryption SDK Message Header Format * is provided for the use of the Encryption SDK for JavaScript only. It can be used * as a reference but is not intended to be use by any packages other than the * Encryption SDK for JavaScript. * * See: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/message-format.html#header-structure */ const concat_buffers_1 = __nccwpck_require__(29097); const material_management_1 = __nccwpck_require__(77519); const identifiers_1 = __nccwpck_require__(79044); const uint_util_1 = __nccwpck_require__(57715); function serializeFactory(fromUtf8) { return { frameIv, nonFramedBodyIv, headerAuthIv, frameHeader, finalFrameHeader, encodeEncryptionContext, serializeEncryptionContext, serializeEncryptedDataKeys, serializeEncryptedDataKey, serializeMessageHeader, buildMessageHeader, }; function frameIv(ivLength, sequenceNumber) { /* Precondition: sequenceNumber must conform to the specification. i.e. 1 - (2^32 - 1) * The sequence number starts at 1 * https://github.com/awslabs/aws-encryption-sdk-specification/blob/master/data-format/message-body.md#sequence-number */ (0, material_management_1.needs)(sequenceNumber > 0 && identifiers_1.SequenceIdentifier.SEQUENCE_NUMBER_END >= sequenceNumber, 'sequenceNumber out of bounds'); const buff = new Uint8Array(ivLength); const view = new DataView(buff.buffer, buff.byteOffset, buff.byteLength); view.setUint32(ivLength - 4, sequenceNumber, false); // big-endian return buff; } function nonFramedBodyIv(ivLength) { return frameIv(ivLength, 1); } function headerAuthIv(ivLength) { return new Uint8Array(ivLength); // new Uint8Array is 0 filled by default } function frameHeader(sequenceNumber, iv) { return (0, concat_buffers_1.concatBuffers)((0, uint_util_1.uInt32BE)(sequenceNumber), iv); } function finalFrameHeader(sequenceNumber, iv, contentLength) { return (0, concat_buffers_1.concatBuffers)((0, uint_util_1.uInt32BE)(identifiers_1.SequenceIdentifier.SEQUENCE_NUMBER_END), // Final Frame identifier (0, uint_util_1.uInt32BE)(sequenceNumber), iv, (0, uint_util_1.uInt32BE)(contentLength)); } function encodeEncryptionContext(encryptionContext) { return (Object.entries(encryptionContext) /* Precondition: The serialized encryption context entries must be sorted by UTF-8 key value. */ .sort(([aKey], [bKey]) => aKey.localeCompare(bKey)) .map((entries) => entries.map(fromUtf8)) .map(([key, value]) => (0, concat_buffers_1.concatBuffers)((0, uint_util_1.uInt16BE)(key.byteLength), key, (0, uint_util_1.uInt16BE)(value.byteLength), value))); } function serializeEncryptionContext(encryptionContext) { const encryptionContextElements = encodeEncryptionContext(encryptionContext); /* Check for early return (Postcondition): If there is no context then the length of the _whole_ serialized portion is 0. * This is part of the specification of the AWS Encryption SDK Message Format. * It is not 0 for length and 0 for count. The count element is omitted. */ if (!encryptionContextElements.length) return (0, uint_util_1.uInt16BE)(0); const aadData = (0, concat_buffers_1.concatBuffers)((0, uint_util_1.uInt16BE)(encryptionContextElements.length), ...encryptionContextElements); const aadLength = (0, uint_util_1.uInt16BE)(aadData.byteLength); return (0, concat_buffers_1.concatBuffers)(aadLength, aadData); } function serializeEncryptedDataKeys(encryptedDataKeys) { const encryptedKeyInfo = encryptedDataKeys.map(serializeEncryptedDataKey); return (0, concat_buffers_1.concatBuffers)((0, uint_util_1.uInt16BE)(encryptedDataKeys.length), ...encryptedKeyInfo); } function serializeEncryptedDataKey(edk) { const { providerId, providerInfo, encryptedDataKey, rawInfo } = edk; const providerIdBytes = fromUtf8(providerId); // The providerInfo is technically a binary field, so I prefer rawInfo const providerInfoBytes = rawInfo || fromUtf8(providerInfo); return (0, concat_buffers_1.concatBuffers)((0, uint_util_1.uInt16BE)(providerIdBytes.byteLength), providerIdBytes, (0, uint_util_1.uInt16BE)(providerInfoBytes.byteLength), providerInfoBytes, (0, uint_util_1.uInt16BE)(encryptedDataKey.byteLength), encryptedDataKey); } function serializeMessageHeader(messageHeader) { /* Precondition: Must be a version that can be serialized. */ (0, material_management_1.needs)(identifiers_1.SerializationVersion[messageHeader.version], 'Unsupported version.'); if (messageHeader.version === 1) { return serializeMessageHeaderV1(messageHeader); } else { return serializeMessageHeaderV2(messageHeader); } } function serializeMessageHeaderV1(messageHeader) { return (0, concat_buffers_1.concatBuffers)((0, uint_util_1.uInt8)(messageHeader.version), (0, uint_util_1.uInt8)(messageHeader.type), (0, uint_util_1.uInt16BE)(messageHeader.suiteId), messageHeader.messageId, serializeEncryptionContext(messageHeader.encryptionContext), serializeEncryptedDataKeys(messageHeader.encryptedDataKeys), new Uint8Array([messageHeader.contentType]), new Uint8Array([0, 0, 0, 0]), (0, uint_util_1.uInt8)(messageHeader.headerIvLength), (0, uint_util_1.uInt32BE)(messageHeader.frameLength)); } function serializeMessageHeaderV2(messageHeader) { return (0, concat_buffers_1.concatBuffers)((0, uint_util_1.uInt8)(messageHeader.version), (0, uint_util_1.uInt16BE)(messageHeader.suiteId), messageHeader.messageId, serializeEncryptionContext(messageHeader.encryptionContext), serializeEncryptedDataKeys(messageHeader.encryptedDataKeys), new Uint8Array([messageHeader.contentType]), (0, uint_util_1.uInt32BE)(messageHeader.frameLength), messageHeader.suiteData); } /* This _could_ take the material directly. * But I don't do that on purpose. * It may be overly paranoid, * but this way once the material is created, * it has a minimum of egress. */ function buildMessageHeader({ encryptionContext, encryptedDataKeys, suite, messageId, frameLength, suiteData, }) { const { messageFormat: version, id: suiteId } = suite; const contentType = identifiers_1.ContentType.FRAMED_DATA; if (version === material_management_1.MessageFormat.V1) { const type = identifiers_1.ObjectType.CUSTOMER_AE_DATA; const { ivLength: headerIvLength } = suite; return { version, type, suiteId, messageId, encryptionContext, encryptedDataKeys, contentType, headerIvLength, frameLength, }; } else if (version === material_management_1.MessageFormat.V2) { return { version, suiteId, messageId, encryptionContext: encryptionContext, encryptedDataKeys: encryptedDataKeys, contentType, frameLength, suiteData, }; } (0, material_management_1.needs)(false, 'Unsupported message format version.'); } } exports.serializeFactory = serializeFactory; function serializeMessageHeaderAuth({ headerIv, headerAuthTag, messageHeader, }) { if (messageHeader.version === material_management_1.MessageFormat.V1) { return (0, concat_buffers_1.concatBuffers)(headerIv, headerAuthTag); } return headerAuthTag; } exports.serializeMessageHeaderAuth = serializeMessageHeaderAuth; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2VyaWFsaXplX2ZhY3RvcnkuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvc2VyaWFsaXplX2ZhY3RvcnkudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0M7OztBQUV0Qzs7Ozs7OztHQU9HO0FBRUgscURBQWdEO0F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xPQUFPLElBQUEsOEJBQWEsRUFBQyxRQUFRLEVBQUUsYUFBYSxDQUFDLENBQUE7S0FDOUM7SUFFRCxPQUFPLGFBQWEsQ0FBQTtBQUN0QixDQUFDO0FBZEQsZ0VBY0MifQ== /***/ }), /***/ 30959: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.deserializeSignature = exports.serializeSignatureInfo = void 0; /* * This public interface for serializing the AWS Encryption SDK Message Footer Format * is provided for the use of the Encryption SDK for JavaScript only. It can be used * as a reference but is not intended to be use by any packages other than the * Encryption SDK for JavaScript. * * See: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/message-format.html#footer-structure */ const concat_buffers_1 = __nccwpck_require__(29097); const uint_util_1 = __nccwpck_require__(57715); const material_management_1 = __nccwpck_require__(77519); function serializeSignatureInfo(signature) { return (0, concat_buffers_1.concatBuffers)((0, uint_util_1.uInt16BE)(signature.byteLength), signature); } exports.serializeSignatureInfo = serializeSignatureInfo; function deserializeSignature({ buffer, byteOffset, byteLength, }) { /* Precondition: There must be information for a signature. */ (0, material_management_1.needs)(byteLength && byteLength > 2, 'Invalid Signature'); /* Uint8Array is a view on top of the underlying ArrayBuffer. * This means that raw underlying memory stored in the ArrayBuffer * may be larger than the Uint8Array. This is especially true of * the Node.js Buffer object. The offset and length *must* be * passed to the DataView otherwise I will get unexpected results. */ const dataView = new DataView(buffer, byteOffset, byteLength); const signatureLength = dataView.getUint16(0, false); // big endian /* Precondition: The signature length must be positive. */ (0, material_management_1.needs)(signatureLength > 0, 'Invalid Signature'); /* Precondition: The data must match the serialized length. */ (0, material_management_1.needs)(byteLength === signatureLength + 2, 'Invalid Signature'); return new Uint8Array(buffer, byteOffset + 2, signatureLength); } exports.deserializeSignature = deserializeSignature; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozL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0FBQTtJQUM5RCxPQUFPLElBQUksVUFBVSxDQUFDLE1BQU0sRUFBRSxVQUFVLEdBQUcsQ0FBQyxFQUFFLGVBQWUsQ0FBQyxDQUFBO0FBQ2hFLENBQUM7QUFwQkQsb0RBb0JDIn0= /***/ }), /***/ 19617: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidHlwZXMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvdHlwZXMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLG9FQUFvRTtBQUNwRSxzQ0FBc0MifQ== /***/ }), /***/ 57715: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.uInt32BE = exports.uInt16BE = exports.uInt8 = void 0; const material_management_1 = __nccwpck_require__(77519); const UINT8_OVERFLOW = 2 ** 8; function uInt8(number) { /* Precondition: Number must be 0-(2^8 - 1). */ (0, material_management_1.needs)(number < UINT8_OVERFLOW && number >= 0, 'number out of bounds.'); const buff = new Uint8Array(1); const view = new DataView(buff.buffer, buff.byteOffset, buff.byteLength); view.setUint8(0, number); return buff; } exports.uInt8 = uInt8; const UINT16__OVERFLOW = 2 ** 16; function uInt16BE(number) { /* Precondition: Number must be 0-(2^16 - 1). */ (0, material_management_1.needs)(number < UINT16__OVERFLOW && number >= 0, 'number out of bounds.'); const buff = new Uint8Array(2); const view = new DataView(buff.buffer, buff.byteOffset, buff.byteLength); view.setUint16(0, number, false); // big-endian return buff; } exports.uInt16BE = uInt16BE; const UINT32__OVERFLOW = 2 ** 32; function uInt32BE(number) { /* Precondition: Number must be 0-(2^32 - 1). */ (0, material_management_1.needs)(number < UINT32__OVERFLOW && number >= 0, 'number out of bounds.'); const buff = new Uint8Array(4); const view = new DataView(buff.buffer, buff.byteOffset, buff.byteLength); view.setUint32(0, number, false); // big-endian return buff; } exports.uInt32BE = uInt32BE; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidWludF91dGlsLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL3VpbnRfdXRpbC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUEsb0VBQW9FO0FBQ3BFLHNDQUFzQzs7O0FBRXRDLHlFQUF1RDtBQUV2RCxNQUFNLGNBQWMsR0FBRyxDQUFDLElBQUksQ0FBQyxDQUFBO0FBQzdCLFNBQWdCLEtBQUssQ0FBQyxNQUFjO0lBQ2xDLCtDQUErQztJQUMvQyxJQUFBLDJCQUFLLEVBQUMsTUFBTSxHQUFHLGNBQWMsSUFBSSxNQUFNLElBQUksQ0FBQyxFQUFFLHVCQUF1QixDQUFDLENBQUE7SUFFdEUsTUFBTSxJQUFJLEdBQUcsSUFBSSxVQUFVLENBQUMsQ0FBQyxDQUFDLENBQUE7SUFDOUIsTUFBTSxJQUFJLEdBQUcsSUFBSSxRQUFRLENBQUMsSUFBSSxDQUFDLE1BQU0sRUFBRSxJQUFJLENBQUMsVUFBVSxFQUFFLElBQUksQ0FBQyxVQUFVLENBQUMsQ0FBQTtJQUN4RSxJQUFJLENBQUMsUUFBUSxDQUFDLENBQUMsRUFBRSxNQUFNLENBQUMsQ0FBQTtJQUN4QixPQUFPLElBQUksQ0FBQTtBQUNiLENBQUM7QUFSRCxzQkFRQztBQUVELE1BQU0sZ0JBQWdCLEdBQUcsQ0FBQyxJQUFJLEVBQUUsQ0FBQTtBQUNoQyxTQUFnQixRQUFRLENBQUMsTUFBYztJQUNyQyxnREFBZ0Q7SUFDaEQsSUF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: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.convertToBuffer = void 0; var util_utf8_browser_1 = __nccwpck_require__(28172); // Quick polyfill var fromUtf8 = typeof Buffer !== "undefined" && Buffer.from ? function (input) { return Buffer.from(input, "utf8"); } : util_utf8_browser_1.fromUtf8; function convertToBuffer(data) { // Already a Uint8, do nothing if (data instanceof Uint8Array) return data; if (typeof data === "string") { return fromUtf8(data); } if (ArrayBuffer.isView(data)) { return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); } return new Uint8Array(data); } exports.convertToBuffer = convertToBuffer; //# sourceMappingURL=convertToBuffer.js.map /***/ }), /***/ 41236: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.uint32ArrayFrom = exports.numToUint8 = exports.isEmptyData = exports.convertToBuffer = void 0; var convertToBuffer_1 = __nccwpck_require__(43228); Object.defineProperty(exports, "convertToBuffer", ({ enumerable: true, get: function () { return convertToBuffer_1.convertToBuffer; } })); var isEmptyData_1 = __nccwpck_require__(18275); Object.defineProperty(exports, "isEmptyData", ({ enumerable: true, get: function () { return isEmptyData_1.isEmptyData; } })); var numToUint8_1 = __nccwpck_require__(93775); Object.defineProperty(exports, "numToUint8", ({ enumerable: true, get: function () { return numToUint8_1.numToUint8; } })); var uint32ArrayFrom_1 = __nccwpck_require__(39404); Object.defineProperty(exports, "uint32ArrayFrom", ({ enumerable: true, get: function () { return uint32ArrayFrom_1.uint32ArrayFrom; } })); //# sourceMappingURL=index.js.map /***/ }), /***/ 18275: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isEmptyData = void 0; function isEmptyData(data) { if (typeof data === "string") { return data.length === 0; } return data.byteLength === 0; } exports.isEmptyData = isEmptyData; //# sourceMappingURL=isEmptyData.js.map /***/ }), /***/ 93775: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.numToUint8 = void 0; function numToUint8(num) { return new Uint8Array([ (num & 0xff000000) >> 24, (num & 0x00ff0000) >> 16, (num & 0x0000ff00) >> 8, num & 0x000000ff, ]); } exports.numToUint8 = numToUint8; //# sourceMappingURL=numToUint8.js.map /***/ }), /***/ 39404: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", ({ value: true })); exports.uint32ArrayFrom = void 0; // IE 11 does not support Array.from, so we do it manually function uint32ArrayFrom(a_lookUpTable) { if (!Uint32Array.from) { var return_array = new Uint32Array(a_lookUpTable.length); var a_index = 0; while (a_index < a_lookUpTable.length) { return_array[a_index] = a_lookUpTable[a_index]; a_index += 1; } return return_array; } return Uint32Array.from(a_lookUpTable); } exports.uint32ArrayFrom = uint32ArrayFrom; //# sourceMappingURL=uint32ArrayFrom.js.map /***/ }), /***/ 24873: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.KMS = void 0; const smithy_client_1 = __nccwpck_require__(63570); const CancelKeyDeletionCommand_1 = __nccwpck_require__(87623); const ConnectCustomKeyStoreCommand_1 = __nccwpck_require__(4182); const CreateAliasCommand_1 = __nccwpck_require__(24718); const CreateCustomKeyStoreCommand_1 = __nccwpck_require__(15613); const CreateGrantCommand_1 = __nccwpck_require__(45517); const CreateKeyCommand_1 = __nccwpck_require__(25364); const DecryptCommand_1 = __nccwpck_require__(64640); const DeleteAliasCommand_1 = __nccwpck_require__(47690); const DeleteCustomKeyStoreCommand_1 = __nccwpck_require__(88877); const DeleteImportedKeyMaterialCommand_1 = __nccwpck_require__(14646); const DescribeCustomKeyStoresCommand_1 = __nccwpck_require__(25454); const DescribeKeyCommand_1 = __nccwpck_require__(67765); const DisableKeyCommand_1 = __nccwpck_require__(48803); const DisableKeyRotationCommand_1 = __nccwpck_require__(64999); const DisconnectCustomKeyStoreCommand_1 = __nccwpck_require__(80343); const EnableKeyCommand_1 = __nccwpck_require__(83624); const EnableKeyRotationCommand_1 = __nccwpck_require__(9719); const EncryptCommand_1 = __nccwpck_require__(71839); const GenerateDataKeyCommand_1 = __nccwpck_require__(79009); const GenerateDataKeyPairCommand_1 = __nccwpck_require__(18248); const GenerateDataKeyPairWithoutPlaintextCommand_1 = __nccwpck_require__(53547); const GenerateDataKeyWithoutPlaintextCommand_1 = __nccwpck_require__(2614); const GenerateMacCommand_1 = __nccwpck_require__(14975); const GenerateRandomCommand_1 = __nccwpck_require__(73823); const GetKeyPolicyCommand_1 = __nccwpck_require__(62288); const GetKeyRotationStatusCommand_1 = __nccwpck_require__(48516); const GetParametersForImportCommand_1 = __nccwpck_require__(50190); const GetPublicKeyCommand_1 = __nccwpck_require__(49730); const ImportKeyMaterialCommand_1 = __nccwpck_require__(80274); const ListAliasesCommand_1 = __nccwpck_require__(99534); const ListGrantsCommand_1 = __nccwpck_require__(13372); const ListKeyPoliciesCommand_1 = __nccwpck_require__(54788); const ListKeysCommand_1 = __nccwpck_require__(76274); const ListResourceTagsCommand_1 = __nccwpck_require__(33207); const ListRetirableGrantsCommand_1 = __nccwpck_require__(14898); const PutKeyPolicyCommand_1 = __nccwpck_require__(23975); const ReEncryptCommand_1 = __nccwpck_require__(1362); const ReplicateKeyCommand_1 = __nccwpck_require__(46026); const RetireGrantCommand_1 = __nccwpck_require__(63404); const RevokeGrantCommand_1 = __nccwpck_require__(25645); const ScheduleKeyDeletionCommand_1 = __nccwpck_require__(8669); const SignCommand_1 = __nccwpck_require__(26780); const TagResourceCommand_1 = __nccwpck_require__(4736); const UntagResourceCommand_1 = __nccwpck_require__(5268); const UpdateAliasCommand_1 = __nccwpck_require__(48070); const UpdateCustomKeyStoreCommand_1 = __nccwpck_require__(59864); const UpdateKeyDescriptionCommand_1 = __nccwpck_require__(2054); const UpdatePrimaryRegionCommand_1 = __nccwpck_require__(17862); const VerifyCommand_1 = __nccwpck_require__(31249); const VerifyMacCommand_1 = __nccwpck_require__(32854); const KMSClient_1 = __nccwpck_require__(33690); const commands = { CancelKeyDeletionCommand: CancelKeyDeletionCommand_1.CancelKeyDeletionCommand, ConnectCustomKeyStoreCommand: ConnectCustomKeyStoreCommand_1.ConnectCustomKeyStoreCommand, CreateAliasCommand: CreateAliasCommand_1.CreateAliasCommand, CreateCustomKeyStoreCommand: CreateCustomKeyStoreCommand_1.CreateCustomKeyStoreCommand, CreateGrantCommand: CreateGrantCommand_1.CreateGrantCommand, CreateKeyCommand: CreateKeyCommand_1.CreateKeyCommand, DecryptCommand: DecryptCommand_1.DecryptCommand, DeleteAliasCommand: DeleteAliasCommand_1.DeleteAliasCommand, DeleteCustomKeyStoreCommand: DeleteCustomKeyStoreCommand_1.DeleteCustomKeyStoreCommand, DeleteImportedKeyMaterialCommand: DeleteImportedKeyMaterialCommand_1.DeleteImportedKeyMaterialCommand, DescribeCustomKeyStoresCommand: DescribeCustomKeyStoresCommand_1.DescribeCustomKeyStoresCommand, DescribeKeyCommand: DescribeKeyCommand_1.DescribeKeyCommand, DisableKeyCommand: DisableKeyCommand_1.DisableKeyCommand, DisableKeyRotationCommand: DisableKeyRotationCommand_1.DisableKeyRotationCommand, DisconnectCustomKeyStoreCommand: DisconnectCustomKeyStoreCommand_1.DisconnectCustomKeyStoreCommand, EnableKeyCommand: EnableKeyCommand_1.EnableKeyCommand, EnableKeyRotationCommand: EnableKeyRotationCommand_1.EnableKeyRotationCommand, EncryptCommand: EncryptCommand_1.EncryptCommand, GenerateDataKeyCommand: GenerateDataKeyCommand_1.GenerateDataKeyCommand, GenerateDataKeyPairCommand: GenerateDataKeyPairCommand_1.GenerateDataKeyPairCommand, GenerateDataKeyPairWithoutPlaintextCommand: GenerateDataKeyPairWithoutPlaintextCommand_1.GenerateDataKeyPairWithoutPlaintextCommand, GenerateDataKeyWithoutPlaintextCommand: GenerateDataKeyWithoutPlaintextCommand_1.GenerateDataKeyWithoutPlaintextCommand, GenerateMacCommand: GenerateMacCommand_1.GenerateMacCommand, GenerateRandomCommand: GenerateRandomCommand_1.GenerateRandomCommand, GetKeyPolicyCommand: GetKeyPolicyCommand_1.GetKeyPolicyCommand, GetKeyRotationStatusCommand: GetKeyRotationStatusCommand_1.GetKeyRotationStatusCommand, GetParametersForImportCommand: GetParametersForImportCommand_1.GetParametersForImportCommand, GetPublicKeyCommand: GetPublicKeyCommand_1.GetPublicKeyCommand, ImportKeyMaterialCommand: ImportKeyMaterialCommand_1.ImportKeyMaterialCommand, ListAliasesCommand: ListAliasesCommand_1.ListAliasesCommand, ListGrantsCommand: ListGrantsCommand_1.ListGrantsCommand, ListKeyPoliciesCommand: ListKeyPoliciesCommand_1.ListKeyPoliciesCommand, ListKeysCommand: ListKeysCommand_1.ListKeysCommand, ListResourceTagsCommand: ListResourceTagsCommand_1.ListResourceTagsCommand, ListRetirableGrantsCommand: ListRetirableGrantsCommand_1.ListRetirableGrantsCommand, PutKeyPolicyCommand: PutKeyPolicyCommand_1.PutKeyPolicyCommand, ReEncryptCommand: ReEncryptCommand_1.ReEncryptCommand, ReplicateKeyCommand: ReplicateKeyCommand_1.ReplicateKeyCommand, RetireGrantCommand: RetireGrantCommand_1.RetireGrantCommand, RevokeGrantCommand: RevokeGrantCommand_1.RevokeGrantCommand, ScheduleKeyDeletionCommand: ScheduleKeyDeletionCommand_1.ScheduleKeyDeletionCommand, SignCommand: SignCommand_1.SignCommand, TagResourceCommand: TagResourceCommand_1.TagResourceCommand, UntagResourceCommand: UntagResourceCommand_1.UntagResourceCommand, UpdateAliasCommand: UpdateAliasCommand_1.UpdateAliasCommand, UpdateCustomKeyStoreCommand: UpdateCustomKeyStoreCommand_1.UpdateCustomKeyStoreCommand, UpdateKeyDescriptionCommand: UpdateKeyDescriptionCommand_1.UpdateKeyDescriptionCommand, UpdatePrimaryRegionCommand: UpdatePrimaryRegionCommand_1.UpdatePrimaryRegionCommand, VerifyCommand: VerifyCommand_1.VerifyCommand, VerifyMacCommand: VerifyMacCommand_1.VerifyMacCommand, }; class KMS extends KMSClient_1.KMSClient { } exports.KMS = KMS; (0, smithy_client_1.createAggregatedClient)(commands, KMS); /***/ }), /***/ 33690: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.KMSClient = exports.__Client = void 0; const middleware_host_header_1 = __nccwpck_require__(22545); const middleware_logger_1 = __nccwpck_require__(20014); const middleware_recursion_detection_1 = __nccwpck_require__(85525); const middleware_signing_1 = __nccwpck_require__(14935); const middleware_user_agent_1 = __nccwpck_require__(64688); const config_resolver_1 = __nccwpck_require__(53098); const middleware_content_length_1 = __nccwpck_require__(82800); const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_retry_1 = __nccwpck_require__(96039); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "__Client", ({ enumerable: true, get: function () { return smithy_client_1.Client; } })); const EndpointParameters_1 = __nccwpck_require__(57421); const runtimeConfig_1 = __nccwpck_require__(19916); const runtimeExtensions_1 = __nccwpck_require__(93012); class KMSClient extends smithy_client_1.Client { constructor(...[configuration]) { const _config_0 = (0, runtimeConfig_1.getRuntimeConfig)(configuration || {}); const _config_1 = (0, EndpointParameters_1.resolveClientEndpointParameters)(_config_0); const _config_2 = (0, config_resolver_1.resolveRegionConfig)(_config_1); const _config_3 = (0, middleware_endpoint_1.resolveEndpointConfig)(_config_2); const _config_4 = (0, middleware_retry_1.resolveRetryConfig)(_config_3); const _config_5 = (0, middleware_host_header_1.resolveHostHeaderConfig)(_config_4); const _config_6 = (0, middleware_signing_1.resolveAwsAuthConfig)(_config_5); const _config_7 = (0, middleware_user_agent_1.resolveUserAgentConfig)(_config_6); const _config_8 = (0, runtimeExtensions_1.resolveRuntimeExtensions)(_config_7, configuration?.extensions || []); super(_config_8); this.config = _config_8; this.middlewareStack.use((0, middleware_retry_1.getRetryPlugin)(this.config)); this.middlewareStack.use((0, middleware_content_length_1.getContentLengthPlugin)(this.config)); this.middlewareStack.use((0, middleware_host_header_1.getHostHeaderPlugin)(this.config)); this.middlewareStack.use((0, middleware_logger_1.getLoggerPlugin)(this.config)); this.middlewareStack.use((0, middleware_recursion_detection_1.getRecursionDetectionPlugin)(this.config)); this.middlewareStack.use((0, middleware_signing_1.getAwsAuthPlugin)(this.config)); this.middlewareStack.use((0, middleware_user_agent_1.getUserAgentPlugin)(this.config)); } destroy() { super.destroy(); } } exports.KMSClient = KMSClient; /***/ }), /***/ 87623: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CancelKeyDeletionCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class CancelKeyDeletionCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, CancelKeyDeletionCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "CancelKeyDeletionCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "CancelKeyDeletion", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_CancelKeyDeletionCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_CancelKeyDeletionCommand)(output, context); } } exports.CancelKeyDeletionCommand = CancelKeyDeletionCommand; /***/ }), /***/ 4182: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ConnectCustomKeyStoreCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class ConnectCustomKeyStoreCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, ConnectCustomKeyStoreCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "ConnectCustomKeyStoreCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "ConnectCustomKeyStore", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_ConnectCustomKeyStoreCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_ConnectCustomKeyStoreCommand)(output, context); } } exports.ConnectCustomKeyStoreCommand = ConnectCustomKeyStoreCommand; /***/ }), /***/ 24718: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CreateAliasCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class CreateAliasCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, CreateAliasCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "CreateAliasCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "CreateAlias", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_CreateAliasCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_CreateAliasCommand)(output, context); } } exports.CreateAliasCommand = CreateAliasCommand; /***/ }), /***/ 15613: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CreateCustomKeyStoreCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const models_0_1 = __nccwpck_require__(52249); const Aws_json1_1_1 = __nccwpck_require__(90056); class CreateCustomKeyStoreCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, CreateCustomKeyStoreCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "CreateCustomKeyStoreCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: models_0_1.CreateCustomKeyStoreRequestFilterSensitiveLog, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "CreateCustomKeyStore", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_CreateCustomKeyStoreCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_CreateCustomKeyStoreCommand)(output, context); } } exports.CreateCustomKeyStoreCommand = CreateCustomKeyStoreCommand; /***/ }), /***/ 45517: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CreateGrantCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class CreateGrantCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, CreateGrantCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "CreateGrantCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "CreateGrant", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_CreateGrantCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_CreateGrantCommand)(output, context); } } exports.CreateGrantCommand = CreateGrantCommand; /***/ }), /***/ 25364: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CreateKeyCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class CreateKeyCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, CreateKeyCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "CreateKeyCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "CreateKey", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_CreateKeyCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_CreateKeyCommand)(output, context); } } exports.CreateKeyCommand = CreateKeyCommand; /***/ }), /***/ 64640: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DecryptCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const models_0_1 = __nccwpck_require__(52249); const Aws_json1_1_1 = __nccwpck_require__(90056); class DecryptCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, DecryptCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "DecryptCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: models_0_1.DecryptResponseFilterSensitiveLog, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "Decrypt", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_DecryptCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_DecryptCommand)(output, context); } } exports.DecryptCommand = DecryptCommand; /***/ }), /***/ 47690: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DeleteAliasCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class DeleteAliasCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, DeleteAliasCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "DeleteAliasCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "DeleteAlias", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_DeleteAliasCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_DeleteAliasCommand)(output, context); } } exports.DeleteAliasCommand = DeleteAliasCommand; /***/ }), /***/ 88877: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DeleteCustomKeyStoreCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class DeleteCustomKeyStoreCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, DeleteCustomKeyStoreCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "DeleteCustomKeyStoreCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "DeleteCustomKeyStore", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_DeleteCustomKeyStoreCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_DeleteCustomKeyStoreCommand)(output, context); } } exports.DeleteCustomKeyStoreCommand = DeleteCustomKeyStoreCommand; /***/ }), /***/ 14646: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DeleteImportedKeyMaterialCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class DeleteImportedKeyMaterialCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, DeleteImportedKeyMaterialCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "DeleteImportedKeyMaterialCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "DeleteImportedKeyMaterial", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_DeleteImportedKeyMaterialCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_DeleteImportedKeyMaterialCommand)(output, context); } } exports.DeleteImportedKeyMaterialCommand = DeleteImportedKeyMaterialCommand; /***/ }), /***/ 25454: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DescribeCustomKeyStoresCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const models_0_1 = __nccwpck_require__(52249); const Aws_json1_1_1 = __nccwpck_require__(90056); class DescribeCustomKeyStoresCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, DescribeCustomKeyStoresCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "DescribeCustomKeyStoresCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: models_0_1.DescribeCustomKeyStoresResponseFilterSensitiveLog, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "DescribeCustomKeyStores", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_DescribeCustomKeyStoresCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_DescribeCustomKeyStoresCommand)(output, context); } } exports.DescribeCustomKeyStoresCommand = DescribeCustomKeyStoresCommand; /***/ }), /***/ 67765: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DescribeKeyCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class DescribeKeyCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, DescribeKeyCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "DescribeKeyCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "DescribeKey", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_DescribeKeyCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_DescribeKeyCommand)(output, context); } } exports.DescribeKeyCommand = DescribeKeyCommand; /***/ }), /***/ 48803: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DisableKeyCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class DisableKeyCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, DisableKeyCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "DisableKeyCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "DisableKey", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_DisableKeyCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_DisableKeyCommand)(output, context); } } exports.DisableKeyCommand = DisableKeyCommand; /***/ }), /***/ 64999: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DisableKeyRotationCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class DisableKeyRotationCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, DisableKeyRotationCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "DisableKeyRotationCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "DisableKeyRotation", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_DisableKeyRotationCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_DisableKeyRotationCommand)(output, context); } } exports.DisableKeyRotationCommand = DisableKeyRotationCommand; /***/ }), /***/ 80343: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DisconnectCustomKeyStoreCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class DisconnectCustomKeyStoreCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, DisconnectCustomKeyStoreCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "DisconnectCustomKeyStoreCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "DisconnectCustomKeyStore", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_DisconnectCustomKeyStoreCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_DisconnectCustomKeyStoreCommand)(output, context); } } exports.DisconnectCustomKeyStoreCommand = DisconnectCustomKeyStoreCommand; /***/ }), /***/ 83624: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.EnableKeyCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class EnableKeyCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, EnableKeyCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "EnableKeyCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "EnableKey", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_EnableKeyCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_EnableKeyCommand)(output, context); } } exports.EnableKeyCommand = EnableKeyCommand; /***/ }), /***/ 9719: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.EnableKeyRotationCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class EnableKeyRotationCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, EnableKeyRotationCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "EnableKeyRotationCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "EnableKeyRotation", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_EnableKeyRotationCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_EnableKeyRotationCommand)(output, context); } } exports.EnableKeyRotationCommand = EnableKeyRotationCommand; /***/ }), /***/ 71839: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.EncryptCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const models_0_1 = __nccwpck_require__(52249); const Aws_json1_1_1 = __nccwpck_require__(90056); class EncryptCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, EncryptCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "EncryptCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: models_0_1.EncryptRequestFilterSensitiveLog, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "Encrypt", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_EncryptCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_EncryptCommand)(output, context); } } exports.EncryptCommand = EncryptCommand; /***/ }), /***/ 79009: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GenerateDataKeyCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const models_0_1 = __nccwpck_require__(52249); const Aws_json1_1_1 = __nccwpck_require__(90056); class GenerateDataKeyCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, GenerateDataKeyCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "GenerateDataKeyCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: models_0_1.GenerateDataKeyResponseFilterSensitiveLog, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "GenerateDataKey", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_GenerateDataKeyCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_GenerateDataKeyCommand)(output, context); } } exports.GenerateDataKeyCommand = GenerateDataKeyCommand; /***/ }), /***/ 18248: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GenerateDataKeyPairCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const models_0_1 = __nccwpck_require__(52249); const Aws_json1_1_1 = __nccwpck_require__(90056); class GenerateDataKeyPairCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, GenerateDataKeyPairCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "GenerateDataKeyPairCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: models_0_1.GenerateDataKeyPairResponseFilterSensitiveLog, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "GenerateDataKeyPair", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_GenerateDataKeyPairCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_GenerateDataKeyPairCommand)(output, context); } } exports.GenerateDataKeyPairCommand = GenerateDataKeyPairCommand; /***/ }), /***/ 53547: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GenerateDataKeyPairWithoutPlaintextCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class GenerateDataKeyPairWithoutPlaintextCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, GenerateDataKeyPairWithoutPlaintextCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "GenerateDataKeyPairWithoutPlaintextCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "GenerateDataKeyPairWithoutPlaintext", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_GenerateDataKeyPairWithoutPlaintextCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_GenerateDataKeyPairWithoutPlaintextCommand)(output, context); } } exports.GenerateDataKeyPairWithoutPlaintextCommand = GenerateDataKeyPairWithoutPlaintextCommand; /***/ }), /***/ 2614: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GenerateDataKeyWithoutPlaintextCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class GenerateDataKeyWithoutPlaintextCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, GenerateDataKeyWithoutPlaintextCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "GenerateDataKeyWithoutPlaintextCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "GenerateDataKeyWithoutPlaintext", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_GenerateDataKeyWithoutPlaintextCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_GenerateDataKeyWithoutPlaintextCommand)(output, context); } } exports.GenerateDataKeyWithoutPlaintextCommand = GenerateDataKeyWithoutPlaintextCommand; /***/ }), /***/ 14975: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GenerateMacCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const models_0_1 = __nccwpck_require__(52249); const Aws_json1_1_1 = __nccwpck_require__(90056); class GenerateMacCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, GenerateMacCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "GenerateMacCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: models_0_1.GenerateMacRequestFilterSensitiveLog, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "GenerateMac", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_GenerateMacCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_GenerateMacCommand)(output, context); } } exports.GenerateMacCommand = GenerateMacCommand; /***/ }), /***/ 73823: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GenerateRandomCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const models_0_1 = __nccwpck_require__(52249); const Aws_json1_1_1 = __nccwpck_require__(90056); class GenerateRandomCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, GenerateRandomCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "GenerateRandomCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: models_0_1.GenerateRandomResponseFilterSensitiveLog, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "GenerateRandom", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_GenerateRandomCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_GenerateRandomCommand)(output, context); } } exports.GenerateRandomCommand = GenerateRandomCommand; /***/ }), /***/ 62288: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GetKeyPolicyCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class GetKeyPolicyCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, GetKeyPolicyCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "GetKeyPolicyCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "GetKeyPolicy", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_GetKeyPolicyCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_GetKeyPolicyCommand)(output, context); } } exports.GetKeyPolicyCommand = GetKeyPolicyCommand; /***/ }), /***/ 48516: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GetKeyRotationStatusCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class GetKeyRotationStatusCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, GetKeyRotationStatusCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "GetKeyRotationStatusCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "GetKeyRotationStatus", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_GetKeyRotationStatusCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_GetKeyRotationStatusCommand)(output, context); } } exports.GetKeyRotationStatusCommand = GetKeyRotationStatusCommand; /***/ }), /***/ 50190: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GetParametersForImportCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const models_0_1 = __nccwpck_require__(52249); const Aws_json1_1_1 = __nccwpck_require__(90056); class GetParametersForImportCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, GetParametersForImportCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "GetParametersForImportCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: models_0_1.GetParametersForImportResponseFilterSensitiveLog, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "GetParametersForImport", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_GetParametersForImportCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_GetParametersForImportCommand)(output, context); } } exports.GetParametersForImportCommand = GetParametersForImportCommand; /***/ }), /***/ 49730: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GetPublicKeyCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class GetPublicKeyCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, GetPublicKeyCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "GetPublicKeyCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "GetPublicKey", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_GetPublicKeyCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_GetPublicKeyCommand)(output, context); } } exports.GetPublicKeyCommand = GetPublicKeyCommand; /***/ }), /***/ 80274: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ImportKeyMaterialCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class ImportKeyMaterialCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, ImportKeyMaterialCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "ImportKeyMaterialCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "ImportKeyMaterial", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_ImportKeyMaterialCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_ImportKeyMaterialCommand)(output, context); } } exports.ImportKeyMaterialCommand = ImportKeyMaterialCommand; /***/ }), /***/ 99534: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ListAliasesCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class ListAliasesCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, ListAliasesCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "ListAliasesCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "ListAliases", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_ListAliasesCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_ListAliasesCommand)(output, context); } } exports.ListAliasesCommand = ListAliasesCommand; /***/ }), /***/ 13372: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ListGrantsCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class ListGrantsCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, ListGrantsCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "ListGrantsCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "ListGrants", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_ListGrantsCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_ListGrantsCommand)(output, context); } } exports.ListGrantsCommand = ListGrantsCommand; /***/ }), /***/ 54788: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ListKeyPoliciesCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class ListKeyPoliciesCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, ListKeyPoliciesCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "ListKeyPoliciesCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "ListKeyPolicies", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_ListKeyPoliciesCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_ListKeyPoliciesCommand)(output, context); } } exports.ListKeyPoliciesCommand = ListKeyPoliciesCommand; /***/ }), /***/ 76274: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ListKeysCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class ListKeysCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, ListKeysCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "ListKeysCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "ListKeys", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_ListKeysCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_ListKeysCommand)(output, context); } } exports.ListKeysCommand = ListKeysCommand; /***/ }), /***/ 33207: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ListResourceTagsCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class ListResourceTagsCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, ListResourceTagsCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "ListResourceTagsCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "ListResourceTags", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_ListResourceTagsCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_ListResourceTagsCommand)(output, context); } } exports.ListResourceTagsCommand = ListResourceTagsCommand; /***/ }), /***/ 14898: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ListRetirableGrantsCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class ListRetirableGrantsCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, ListRetirableGrantsCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "ListRetirableGrantsCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "ListRetirableGrants", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_ListRetirableGrantsCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_ListRetirableGrantsCommand)(output, context); } } exports.ListRetirableGrantsCommand = ListRetirableGrantsCommand; /***/ }), /***/ 23975: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PutKeyPolicyCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class PutKeyPolicyCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, PutKeyPolicyCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "PutKeyPolicyCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "PutKeyPolicy", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_PutKeyPolicyCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_PutKeyPolicyCommand)(output, context); } } exports.PutKeyPolicyCommand = PutKeyPolicyCommand; /***/ }), /***/ 1362: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReEncryptCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class ReEncryptCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, ReEncryptCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "ReEncryptCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "ReEncrypt", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_ReEncryptCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_ReEncryptCommand)(output, context); } } exports.ReEncryptCommand = ReEncryptCommand; /***/ }), /***/ 46026: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReplicateKeyCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class ReplicateKeyCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, ReplicateKeyCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "ReplicateKeyCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "ReplicateKey", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_ReplicateKeyCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_ReplicateKeyCommand)(output, context); } } exports.ReplicateKeyCommand = ReplicateKeyCommand; /***/ }), /***/ 63404: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.RetireGrantCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class RetireGrantCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, RetireGrantCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "RetireGrantCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "RetireGrant", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_RetireGrantCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_RetireGrantCommand)(output, context); } } exports.RetireGrantCommand = RetireGrantCommand; /***/ }), /***/ 25645: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.RevokeGrantCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class RevokeGrantCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, RevokeGrantCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "RevokeGrantCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "RevokeGrant", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_RevokeGrantCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_RevokeGrantCommand)(output, context); } } exports.RevokeGrantCommand = RevokeGrantCommand; /***/ }), /***/ 8669: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ScheduleKeyDeletionCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class ScheduleKeyDeletionCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, ScheduleKeyDeletionCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "ScheduleKeyDeletionCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "ScheduleKeyDeletion", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_ScheduleKeyDeletionCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_ScheduleKeyDeletionCommand)(output, context); } } exports.ScheduleKeyDeletionCommand = ScheduleKeyDeletionCommand; /***/ }), /***/ 26780: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SignCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const models_0_1 = __nccwpck_require__(52249); const Aws_json1_1_1 = __nccwpck_require__(90056); class SignCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, SignCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "SignCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: models_0_1.SignRequestFilterSensitiveLog, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "Sign", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_SignCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_SignCommand)(output, context); } } exports.SignCommand = SignCommand; /***/ }), /***/ 4736: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TagResourceCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class TagResourceCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, TagResourceCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "TagResourceCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "TagResource", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_TagResourceCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_TagResourceCommand)(output, context); } } exports.TagResourceCommand = TagResourceCommand; /***/ }), /***/ 5268: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UntagResourceCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class UntagResourceCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, UntagResourceCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "UntagResourceCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "UntagResource", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_UntagResourceCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_UntagResourceCommand)(output, context); } } exports.UntagResourceCommand = UntagResourceCommand; /***/ }), /***/ 48070: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UpdateAliasCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class UpdateAliasCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, UpdateAliasCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "UpdateAliasCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "UpdateAlias", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_UpdateAliasCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_UpdateAliasCommand)(output, context); } } exports.UpdateAliasCommand = UpdateAliasCommand; /***/ }), /***/ 59864: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UpdateCustomKeyStoreCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const models_0_1 = __nccwpck_require__(52249); const Aws_json1_1_1 = __nccwpck_require__(90056); class UpdateCustomKeyStoreCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, UpdateCustomKeyStoreCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "UpdateCustomKeyStoreCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: models_0_1.UpdateCustomKeyStoreRequestFilterSensitiveLog, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "UpdateCustomKeyStore", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_UpdateCustomKeyStoreCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_UpdateCustomKeyStoreCommand)(output, context); } } exports.UpdateCustomKeyStoreCommand = UpdateCustomKeyStoreCommand; /***/ }), /***/ 2054: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UpdateKeyDescriptionCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class UpdateKeyDescriptionCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, UpdateKeyDescriptionCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "UpdateKeyDescriptionCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "UpdateKeyDescription", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_UpdateKeyDescriptionCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_UpdateKeyDescriptionCommand)(output, context); } } exports.UpdateKeyDescriptionCommand = UpdateKeyDescriptionCommand; /***/ }), /***/ 17862: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UpdatePrimaryRegionCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_json1_1_1 = __nccwpck_require__(90056); class UpdatePrimaryRegionCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, UpdatePrimaryRegionCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "UpdatePrimaryRegionCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "UpdatePrimaryRegion", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_UpdatePrimaryRegionCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_UpdatePrimaryRegionCommand)(output, context); } } exports.UpdatePrimaryRegionCommand = UpdatePrimaryRegionCommand; /***/ }), /***/ 31249: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.VerifyCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const models_0_1 = __nccwpck_require__(52249); const Aws_json1_1_1 = __nccwpck_require__(90056); class VerifyCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, VerifyCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "VerifyCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: models_0_1.VerifyRequestFilterSensitiveLog, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "Verify", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_VerifyCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_VerifyCommand)(output, context); } } exports.VerifyCommand = VerifyCommand; /***/ }), /***/ 32854: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.VerifyMacCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const models_0_1 = __nccwpck_require__(52249); const Aws_json1_1_1 = __nccwpck_require__(90056); class VerifyMacCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, VerifyMacCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "KMSClient"; const commandName = "VerifyMacCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: models_0_1.VerifyMacRequestFilterSensitiveLog, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "TrentService", operation: "VerifyMac", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_json1_1_1.se_VerifyMacCommand)(input, context); } deserialize(output, context) { return (0, Aws_json1_1_1.de_VerifyMacCommand)(output, context); } } exports.VerifyMacCommand = VerifyMacCommand; /***/ }), /***/ 68448: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(87623), exports); tslib_1.__exportStar(__nccwpck_require__(4182), exports); tslib_1.__exportStar(__nccwpck_require__(24718), exports); tslib_1.__exportStar(__nccwpck_require__(15613), exports); tslib_1.__exportStar(__nccwpck_require__(45517), exports); tslib_1.__exportStar(__nccwpck_require__(25364), exports); tslib_1.__exportStar(__nccwpck_require__(64640), exports); tslib_1.__exportStar(__nccwpck_require__(47690), exports); tslib_1.__exportStar(__nccwpck_require__(88877), exports); tslib_1.__exportStar(__nccwpck_require__(14646), exports); tslib_1.__exportStar(__nccwpck_require__(25454), exports); tslib_1.__exportStar(__nccwpck_require__(67765), exports); tslib_1.__exportStar(__nccwpck_require__(48803), exports); tslib_1.__exportStar(__nccwpck_require__(64999), exports); tslib_1.__exportStar(__nccwpck_require__(80343), exports); tslib_1.__exportStar(__nccwpck_require__(83624), exports); tslib_1.__exportStar(__nccwpck_require__(9719), exports); tslib_1.__exportStar(__nccwpck_require__(71839), exports); tslib_1.__exportStar(__nccwpck_require__(79009), exports); tslib_1.__exportStar(__nccwpck_require__(18248), exports); tslib_1.__exportStar(__nccwpck_require__(53547), exports); tslib_1.__exportStar(__nccwpck_require__(2614), exports); tslib_1.__exportStar(__nccwpck_require__(14975), exports); tslib_1.__exportStar(__nccwpck_require__(73823), exports); tslib_1.__exportStar(__nccwpck_require__(62288), exports); tslib_1.__exportStar(__nccwpck_require__(48516), exports); tslib_1.__exportStar(__nccwpck_require__(50190), exports); tslib_1.__exportStar(__nccwpck_require__(49730), exports); tslib_1.__exportStar(__nccwpck_require__(80274), exports); tslib_1.__exportStar(__nccwpck_require__(99534), exports); tslib_1.__exportStar(__nccwpck_require__(13372), exports); tslib_1.__exportStar(__nccwpck_require__(54788), exports); tslib_1.__exportStar(__nccwpck_require__(76274), exports); tslib_1.__exportStar(__nccwpck_require__(33207), exports); tslib_1.__exportStar(__nccwpck_require__(14898), exports); tslib_1.__exportStar(__nccwpck_require__(23975), exports); tslib_1.__exportStar(__nccwpck_require__(1362), exports); tslib_1.__exportStar(__nccwpck_require__(46026), exports); tslib_1.__exportStar(__nccwpck_require__(63404), exports); tslib_1.__exportStar(__nccwpck_require__(25645), exports); tslib_1.__exportStar(__nccwpck_require__(8669), exports); tslib_1.__exportStar(__nccwpck_require__(26780), exports); tslib_1.__exportStar(__nccwpck_require__(4736), exports); tslib_1.__exportStar(__nccwpck_require__(5268), exports); tslib_1.__exportStar(__nccwpck_require__(48070), exports); tslib_1.__exportStar(__nccwpck_require__(59864), exports); tslib_1.__exportStar(__nccwpck_require__(2054), exports); tslib_1.__exportStar(__nccwpck_require__(17862), exports); tslib_1.__exportStar(__nccwpck_require__(31249), exports); tslib_1.__exportStar(__nccwpck_require__(32854), exports); /***/ }), /***/ 57421: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveClientEndpointParameters = void 0; const resolveClientEndpointParameters = (options) => { return { ...options, useDualstackEndpoint: options.useDualstackEndpoint ?? false, useFipsEndpoint: options.useFipsEndpoint ?? false, defaultSigningName: "kms", }; }; exports.resolveClientEndpointParameters = resolveClientEndpointParameters; /***/ }), /***/ 40661: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.defaultEndpointResolver = void 0; const util_endpoints_1 = __nccwpck_require__(45473); const ruleset_1 = __nccwpck_require__(42498); const defaultEndpointResolver = (endpointParams, context = {}) => { return (0, util_endpoints_1.resolveEndpoint)(ruleset_1.ruleSet, { endpointParams: endpointParams, logger: context.logger, }); }; exports.defaultEndpointResolver = defaultEndpointResolver; /***/ }), /***/ 42498: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ruleSet = void 0; const s = "required", t = "fn", u = "argv", v = "ref"; const a = true, b = "isSet", c = "booleanEquals", d = "error", e = "endpoint", f = "tree", g = "PartitionResult", h = { [s]: false, "type": "String" }, i = { [s]: true, "default": false, "type": "Boolean" }, j = { [v]: "Endpoint" }, k = { [t]: c, [u]: [{ [v]: "UseFIPS" }, true] }, l = { [t]: c, [u]: [{ [v]: "UseDualStack" }, true] }, m = {}, n = { [t]: "getAttr", [u]: [{ [v]: g }, "supportsFIPS"] }, o = { [t]: c, [u]: [true, { [t]: "getAttr", [u]: [{ [v]: g }, "supportsDualStack"] }] }, p = [k], q = [l], r = [{ [v]: "Region" }]; const _data = { version: "1.0", parameters: { Region: h, UseDualStack: i, UseFIPS: i, Endpoint: h }, rules: [{ conditions: [{ [t]: b, [u]: [j] }], rules: [{ conditions: p, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { conditions: q, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: j, properties: m, headers: m }, type: e }], type: f }, { conditions: [{ [t]: b, [u]: r }], rules: [{ conditions: [{ [t]: "aws.partition", [u]: r, assign: g }], rules: [{ conditions: [k, l], rules: [{ conditions: [{ [t]: c, [u]: [a, n] }, o], rules: [{ endpoint: { url: "https://kms-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: m, headers: m }, type: e }], type: f }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f }, { conditions: p, rules: [{ conditions: [{ [t]: c, [u]: [n, a] }], rules: [{ endpoint: { url: "https://kms-fips.{Region}.{PartitionResult#dnsSuffix}", properties: m, headers: m }, type: e }], type: f }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f }, { conditions: q, rules: [{ conditions: [o], rules: [{ endpoint: { url: "https://kms.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: m, headers: m }, type: e }], type: f }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f }, { endpoint: { url: "https://kms.{Region}.{PartitionResult#dnsSuffix}", properties: m, headers: m }, type: e }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }] }; exports.ruleSet = _data; /***/ }), /***/ 86121: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.KMSServiceException = void 0; const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(33690), exports); tslib_1.__exportStar(__nccwpck_require__(24873), exports); tslib_1.__exportStar(__nccwpck_require__(68448), exports); tslib_1.__exportStar(__nccwpck_require__(55163), exports); tslib_1.__exportStar(__nccwpck_require__(83424), exports); __nccwpck_require__(13350); var KMSServiceException_1 = __nccwpck_require__(59602); Object.defineProperty(exports, "KMSServiceException", ({ enumerable: true, get: function () { return KMSServiceException_1.KMSServiceException; } })); /***/ }), /***/ 59602: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.KMSServiceException = exports.__ServiceException = void 0; const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "__ServiceException", ({ enumerable: true, get: function () { return smithy_client_1.ServiceException; } })); class KMSServiceException extends smithy_client_1.ServiceException { constructor(options) { super(options); Object.setPrototypeOf(this, KMSServiceException.prototype); } } exports.KMSServiceException = KMSServiceException; /***/ }), /***/ 83424: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(52249), exports); /***/ }), /***/ 52249: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.XksKeyAlreadyInUseException = exports.UnsupportedOperationException = exports.TagException = exports.MalformedPolicyDocumentException = exports.SigningAlgorithmSpec = exports.MultiRegionKeyType = exports.MacAlgorithmSpec = exports.KeyState = exports.KeyManagerType = exports.ExpirationModelType = exports.EncryptionAlgorithmSpec = exports.OriginType = exports.KeyUsageType = exports.KeySpec = exports.CustomerMasterKeySpec = exports.InvalidGrantTokenException = exports.DryRunOperationException = exports.DisabledException = exports.GrantOperation = exports.XksProxyVpcEndpointServiceNotFoundException = exports.XksProxyVpcEndpointServiceInvalidConfigurationException = exports.XksProxyVpcEndpointServiceInUseException = exports.XksProxyUriUnreachableException = exports.XksProxyUriInUseException = exports.XksProxyUriEndpointInUseException = exports.XksProxyInvalidResponseException = exports.XksProxyInvalidConfigurationException = exports.XksProxyIncorrectAuthenticationCredentialException = exports.IncorrectTrustAnchorException = exports.CustomKeyStoreNameInUseException = exports.XksProxyConnectivityType = exports.CustomKeyStoreType = exports.LimitExceededException = exports.InvalidAliasNameException = exports.ConnectionStateType = exports.ConnectionErrorCodeType = exports.CustomKeyStoreNotFoundException = exports.CustomKeyStoreInvalidStateException = exports.CloudHsmClusterNotRelatedException = exports.CloudHsmClusterNotFoundException = exports.CloudHsmClusterNotActiveException = exports.CloudHsmClusterInvalidConfigurationException = exports.CloudHsmClusterInUseException = exports.NotFoundException = exports.KMSInvalidStateException = exports.KMSInternalException = exports.InvalidArnException = exports.DependencyTimeoutException = exports.AlreadyExistsException = exports.AlgorithmSpec = void 0; exports.VerifyMacRequestFilterSensitiveLog = exports.VerifyRequestFilterSensitiveLog = exports.UpdateCustomKeyStoreRequestFilterSensitiveLog = exports.SignRequestFilterSensitiveLog = exports.GetParametersForImportResponseFilterSensitiveLog = exports.GenerateRandomResponseFilterSensitiveLog = exports.GenerateMacRequestFilterSensitiveLog = exports.GenerateDataKeyPairResponseFilterSensitiveLog = exports.GenerateDataKeyResponseFilterSensitiveLog = exports.EncryptRequestFilterSensitiveLog = exports.DescribeCustomKeyStoresResponseFilterSensitiveLog = exports.DecryptResponseFilterSensitiveLog = exports.CustomKeyStoresListEntryFilterSensitiveLog = exports.XksProxyConfigurationTypeFilterSensitiveLog = exports.CreateCustomKeyStoreRequestFilterSensitiveLog = exports.XksProxyAuthenticationCredentialTypeFilterSensitiveLog = exports.MessageType = exports.KMSInvalidSignatureException = exports.KMSInvalidMacException = exports.InvalidGrantIdException = exports.InvalidImportTokenException = exports.IncorrectKeyMaterialException = exports.WrappingKeySpec = exports.ExpiredImportTokenException = exports.InvalidMarkerException = exports.KeyUnavailableException = exports.InvalidKeyUsageException = exports.InvalidCiphertextException = exports.IncorrectKeyException = exports.KeyEncryptionMechanism = exports.DataKeySpec = exports.DataKeyPairSpec = exports.CustomKeyStoreHasCMKsException = exports.XksKeyNotFoundException = exports.XksKeyInvalidConfigurationException = void 0; const smithy_client_1 = __nccwpck_require__(63570); const KMSServiceException_1 = __nccwpck_require__(59602); exports.AlgorithmSpec = { RSAES_OAEP_SHA_1: "RSAES_OAEP_SHA_1", RSAES_OAEP_SHA_256: "RSAES_OAEP_SHA_256", RSAES_PKCS1_V1_5: "RSAES_PKCS1_V1_5", RSA_AES_KEY_WRAP_SHA_1: "RSA_AES_KEY_WRAP_SHA_1", RSA_AES_KEY_WRAP_SHA_256: "RSA_AES_KEY_WRAP_SHA_256", }; class AlreadyExistsException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "AlreadyExistsException", $fault: "client", ...opts, }); this.name = "AlreadyExistsException"; this.$fault = "client"; Object.setPrototypeOf(this, AlreadyExistsException.prototype); } } exports.AlreadyExistsException = AlreadyExistsException; class DependencyTimeoutException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "DependencyTimeoutException", $fault: "server", ...opts, }); this.name = "DependencyTimeoutException"; this.$fault = "server"; Object.setPrototypeOf(this, DependencyTimeoutException.prototype); } } exports.DependencyTimeoutException = DependencyTimeoutException; class InvalidArnException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "InvalidArnException", $fault: "client", ...opts, }); this.name = "InvalidArnException"; this.$fault = "client"; Object.setPrototypeOf(this, InvalidArnException.prototype); } } exports.InvalidArnException = InvalidArnException; class KMSInternalException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "KMSInternalException", $fault: "server", ...opts, }); this.name = "KMSInternalException"; this.$fault = "server"; Object.setPrototypeOf(this, KMSInternalException.prototype); } } exports.KMSInternalException = KMSInternalException; class KMSInvalidStateException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "KMSInvalidStateException", $fault: "client", ...opts, }); this.name = "KMSInvalidStateException"; this.$fault = "client"; Object.setPrototypeOf(this, KMSInvalidStateException.prototype); } } exports.KMSInvalidStateException = KMSInvalidStateException; class NotFoundException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "NotFoundException", $fault: "client", ...opts, }); this.name = "NotFoundException"; this.$fault = "client"; Object.setPrototypeOf(this, NotFoundException.prototype); } } exports.NotFoundException = NotFoundException; class CloudHsmClusterInUseException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "CloudHsmClusterInUseException", $fault: "client", ...opts, }); this.name = "CloudHsmClusterInUseException"; this.$fault = "client"; Object.setPrototypeOf(this, CloudHsmClusterInUseException.prototype); } } exports.CloudHsmClusterInUseException = CloudHsmClusterInUseException; class CloudHsmClusterInvalidConfigurationException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "CloudHsmClusterInvalidConfigurationException", $fault: "client", ...opts, }); this.name = "CloudHsmClusterInvalidConfigurationException"; this.$fault = "client"; Object.setPrototypeOf(this, CloudHsmClusterInvalidConfigurationException.prototype); } } exports.CloudHsmClusterInvalidConfigurationException = CloudHsmClusterInvalidConfigurationException; class CloudHsmClusterNotActiveException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "CloudHsmClusterNotActiveException", $fault: "client", ...opts, }); this.name = "CloudHsmClusterNotActiveException"; this.$fault = "client"; Object.setPrototypeOf(this, CloudHsmClusterNotActiveException.prototype); } } exports.CloudHsmClusterNotActiveException = CloudHsmClusterNotActiveException; class CloudHsmClusterNotFoundException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "CloudHsmClusterNotFoundException", $fault: "client", ...opts, }); this.name = "CloudHsmClusterNotFoundException"; this.$fault = "client"; Object.setPrototypeOf(this, CloudHsmClusterNotFoundException.prototype); } } exports.CloudHsmClusterNotFoundException = CloudHsmClusterNotFoundException; class CloudHsmClusterNotRelatedException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "CloudHsmClusterNotRelatedException", $fault: "client", ...opts, }); this.name = "CloudHsmClusterNotRelatedException"; this.$fault = "client"; Object.setPrototypeOf(this, CloudHsmClusterNotRelatedException.prototype); } } exports.CloudHsmClusterNotRelatedException = CloudHsmClusterNotRelatedException; class CustomKeyStoreInvalidStateException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "CustomKeyStoreInvalidStateException", $fault: "client", ...opts, }); this.name = "CustomKeyStoreInvalidStateException"; this.$fault = "client"; Object.setPrototypeOf(this, CustomKeyStoreInvalidStateException.prototype); } } exports.CustomKeyStoreInvalidStateException = CustomKeyStoreInvalidStateException; class CustomKeyStoreNotFoundException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "CustomKeyStoreNotFoundException", $fault: "client", ...opts, }); this.name = "CustomKeyStoreNotFoundException"; this.$fault = "client"; Object.setPrototypeOf(this, CustomKeyStoreNotFoundException.prototype); } } exports.CustomKeyStoreNotFoundException = CustomKeyStoreNotFoundException; exports.ConnectionErrorCodeType = { CLUSTER_NOT_FOUND: "CLUSTER_NOT_FOUND", INSUFFICIENT_CLOUDHSM_HSMS: "INSUFFICIENT_CLOUDHSM_HSMS", INSUFFICIENT_FREE_ADDRESSES_IN_SUBNET: "INSUFFICIENT_FREE_ADDRESSES_IN_SUBNET", INTERNAL_ERROR: "INTERNAL_ERROR", INVALID_CREDENTIALS: "INVALID_CREDENTIALS", NETWORK_ERRORS: "NETWORK_ERRORS", SUBNET_NOT_FOUND: "SUBNET_NOT_FOUND", USER_LOCKED_OUT: "USER_LOCKED_OUT", USER_LOGGED_IN: "USER_LOGGED_IN", USER_NOT_FOUND: "USER_NOT_FOUND", XKS_PROXY_ACCESS_DENIED: "XKS_PROXY_ACCESS_DENIED", XKS_PROXY_INVALID_CONFIGURATION: "XKS_PROXY_INVALID_CONFIGURATION", XKS_PROXY_INVALID_RESPONSE: "XKS_PROXY_INVALID_RESPONSE", XKS_PROXY_INVALID_TLS_CONFIGURATION: "XKS_PROXY_INVALID_TLS_CONFIGURATION", XKS_PROXY_NOT_REACHABLE: "XKS_PROXY_NOT_REACHABLE", XKS_PROXY_TIMED_OUT: "XKS_PROXY_TIMED_OUT", XKS_VPC_ENDPOINT_SERVICE_INVALID_CONFIGURATION: "XKS_VPC_ENDPOINT_SERVICE_INVALID_CONFIGURATION", XKS_VPC_ENDPOINT_SERVICE_NOT_FOUND: "XKS_VPC_ENDPOINT_SERVICE_NOT_FOUND", }; exports.ConnectionStateType = { CONNECTED: "CONNECTED", CONNECTING: "CONNECTING", DISCONNECTED: "DISCONNECTED", DISCONNECTING: "DISCONNECTING", FAILED: "FAILED", }; class InvalidAliasNameException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "InvalidAliasNameException", $fault: "client", ...opts, }); this.name = "InvalidAliasNameException"; this.$fault = "client"; Object.setPrototypeOf(this, InvalidAliasNameException.prototype); } } exports.InvalidAliasNameException = InvalidAliasNameException; class LimitExceededException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "LimitExceededException", $fault: "client", ...opts, }); this.name = "LimitExceededException"; this.$fault = "client"; Object.setPrototypeOf(this, LimitExceededException.prototype); } } exports.LimitExceededException = LimitExceededException; exports.CustomKeyStoreType = { AWS_CLOUDHSM: "AWS_CLOUDHSM", EXTERNAL_KEY_STORE: "EXTERNAL_KEY_STORE", }; exports.XksProxyConnectivityType = { PUBLIC_ENDPOINT: "PUBLIC_ENDPOINT", VPC_ENDPOINT_SERVICE: "VPC_ENDPOINT_SERVICE", }; class CustomKeyStoreNameInUseException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "CustomKeyStoreNameInUseException", $fault: "client", ...opts, }); this.name = "CustomKeyStoreNameInUseException"; this.$fault = "client"; Object.setPrototypeOf(this, CustomKeyStoreNameInUseException.prototype); } } exports.CustomKeyStoreNameInUseException = CustomKeyStoreNameInUseException; class IncorrectTrustAnchorException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "IncorrectTrustAnchorException", $fault: "client", ...opts, }); this.name = "IncorrectTrustAnchorException"; this.$fault = "client"; Object.setPrototypeOf(this, IncorrectTrustAnchorException.prototype); } } exports.IncorrectTrustAnchorException = IncorrectTrustAnchorException; class XksProxyIncorrectAuthenticationCredentialException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "XksProxyIncorrectAuthenticationCredentialException", $fault: "client", ...opts, }); this.name = "XksProxyIncorrectAuthenticationCredentialException"; this.$fault = "client"; Object.setPrototypeOf(this, XksProxyIncorrectAuthenticationCredentialException.prototype); } } exports.XksProxyIncorrectAuthenticationCredentialException = XksProxyIncorrectAuthenticationCredentialException; class XksProxyInvalidConfigurationException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "XksProxyInvalidConfigurationException", $fault: "client", ...opts, }); this.name = "XksProxyInvalidConfigurationException"; this.$fault = "client"; Object.setPrototypeOf(this, XksProxyInvalidConfigurationException.prototype); } } exports.XksProxyInvalidConfigurationException = XksProxyInvalidConfigurationException; class XksProxyInvalidResponseException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "XksProxyInvalidResponseException", $fault: "client", ...opts, }); this.name = "XksProxyInvalidResponseException"; this.$fault = "client"; Object.setPrototypeOf(this, XksProxyInvalidResponseException.prototype); } } exports.XksProxyInvalidResponseException = XksProxyInvalidResponseException; class XksProxyUriEndpointInUseException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "XksProxyUriEndpointInUseException", $fault: "client", ...opts, }); this.name = "XksProxyUriEndpointInUseException"; this.$fault = "client"; Object.setPrototypeOf(this, XksProxyUriEndpointInUseException.prototype); } } exports.XksProxyUriEndpointInUseException = XksProxyUriEndpointInUseException; class XksProxyUriInUseException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "XksProxyUriInUseException", $fault: "client", ...opts, }); this.name = "XksProxyUriInUseException"; this.$fault = "client"; Object.setPrototypeOf(this, XksProxyUriInUseException.prototype); } } exports.XksProxyUriInUseException = XksProxyUriInUseException; class XksProxyUriUnreachableException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "XksProxyUriUnreachableException", $fault: "client", ...opts, }); this.name = "XksProxyUriUnreachableException"; this.$fault = "client"; Object.setPrototypeOf(this, XksProxyUriUnreachableException.prototype); } } exports.XksProxyUriUnreachableException = XksProxyUriUnreachableException; class XksProxyVpcEndpointServiceInUseException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "XksProxyVpcEndpointServiceInUseException", $fault: "client", ...opts, }); this.name = "XksProxyVpcEndpointServiceInUseException"; this.$fault = "client"; Object.setPrototypeOf(this, XksProxyVpcEndpointServiceInUseException.prototype); } } exports.XksProxyVpcEndpointServiceInUseException = XksProxyVpcEndpointServiceInUseException; class XksProxyVpcEndpointServiceInvalidConfigurationException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "XksProxyVpcEndpointServiceInvalidConfigurationException", $fault: "client", ...opts, }); this.name = "XksProxyVpcEndpointServiceInvalidConfigurationException"; this.$fault = "client"; Object.setPrototypeOf(this, XksProxyVpcEndpointServiceInvalidConfigurationException.prototype); } } exports.XksProxyVpcEndpointServiceInvalidConfigurationException = XksProxyVpcEndpointServiceInvalidConfigurationException; class XksProxyVpcEndpointServiceNotFoundException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "XksProxyVpcEndpointServiceNotFoundException", $fault: "client", ...opts, }); this.name = "XksProxyVpcEndpointServiceNotFoundException"; this.$fault = "client"; Object.setPrototypeOf(this, XksProxyVpcEndpointServiceNotFoundException.prototype); } } exports.XksProxyVpcEndpointServiceNotFoundException = XksProxyVpcEndpointServiceNotFoundException; exports.GrantOperation = { CreateGrant: "CreateGrant", Decrypt: "Decrypt", DescribeKey: "DescribeKey", Encrypt: "Encrypt", GenerateDataKey: "GenerateDataKey", GenerateDataKeyPair: "GenerateDataKeyPair", GenerateDataKeyPairWithoutPlaintext: "GenerateDataKeyPairWithoutPlaintext", GenerateDataKeyWithoutPlaintext: "GenerateDataKeyWithoutPlaintext", GenerateMac: "GenerateMac", GetPublicKey: "GetPublicKey", ReEncryptFrom: "ReEncryptFrom", ReEncryptTo: "ReEncryptTo", RetireGrant: "RetireGrant", Sign: "Sign", Verify: "Verify", VerifyMac: "VerifyMac", }; class DisabledException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "DisabledException", $fault: "client", ...opts, }); this.name = "DisabledException"; this.$fault = "client"; Object.setPrototypeOf(this, DisabledException.prototype); } } exports.DisabledException = DisabledException; class DryRunOperationException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "DryRunOperationException", $fault: "client", ...opts, }); this.name = "DryRunOperationException"; this.$fault = "client"; Object.setPrototypeOf(this, DryRunOperationException.prototype); } } exports.DryRunOperationException = DryRunOperationException; class InvalidGrantTokenException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "InvalidGrantTokenException", $fault: "client", ...opts, }); this.name = "InvalidGrantTokenException"; this.$fault = "client"; Object.setPrototypeOf(this, InvalidGrantTokenException.prototype); } } exports.InvalidGrantTokenException = InvalidGrantTokenException; exports.CustomerMasterKeySpec = { ECC_NIST_P256: "ECC_NIST_P256", ECC_NIST_P384: "ECC_NIST_P384", ECC_NIST_P521: "ECC_NIST_P521", ECC_SECG_P256K1: "ECC_SECG_P256K1", HMAC_224: "HMAC_224", HMAC_256: "HMAC_256", HMAC_384: "HMAC_384", HMAC_512: "HMAC_512", RSA_2048: "RSA_2048", RSA_3072: "RSA_3072", RSA_4096: "RSA_4096", SM2: "SM2", SYMMETRIC_DEFAULT: "SYMMETRIC_DEFAULT", }; exports.KeySpec = { ECC_NIST_P256: "ECC_NIST_P256", ECC_NIST_P384: "ECC_NIST_P384", ECC_NIST_P521: "ECC_NIST_P521", ECC_SECG_P256K1: "ECC_SECG_P256K1", HMAC_224: "HMAC_224", HMAC_256: "HMAC_256", HMAC_384: "HMAC_384", HMAC_512: "HMAC_512", RSA_2048: "RSA_2048", RSA_3072: "RSA_3072", RSA_4096: "RSA_4096", SM2: "SM2", SYMMETRIC_DEFAULT: "SYMMETRIC_DEFAULT", }; exports.KeyUsageType = { ENCRYPT_DECRYPT: "ENCRYPT_DECRYPT", GENERATE_VERIFY_MAC: "GENERATE_VERIFY_MAC", SIGN_VERIFY: "SIGN_VERIFY", }; exports.OriginType = { AWS_CLOUDHSM: "AWS_CLOUDHSM", AWS_KMS: "AWS_KMS", EXTERNAL: "EXTERNAL", EXTERNAL_KEY_STORE: "EXTERNAL_KEY_STORE", }; exports.EncryptionAlgorithmSpec = { RSAES_OAEP_SHA_1: "RSAES_OAEP_SHA_1", RSAES_OAEP_SHA_256: "RSAES_OAEP_SHA_256", SM2PKE: "SM2PKE", SYMMETRIC_DEFAULT: "SYMMETRIC_DEFAULT", }; exports.ExpirationModelType = { KEY_MATERIAL_DOES_NOT_EXPIRE: "KEY_MATERIAL_DOES_NOT_EXPIRE", KEY_MATERIAL_EXPIRES: "KEY_MATERIAL_EXPIRES", }; exports.KeyManagerType = { AWS: "AWS", CUSTOMER: "CUSTOMER", }; exports.KeyState = { Creating: "Creating", Disabled: "Disabled", Enabled: "Enabled", PendingDeletion: "PendingDeletion", PendingImport: "PendingImport", PendingReplicaDeletion: "PendingReplicaDeletion", Unavailable: "Unavailable", Updating: "Updating", }; exports.MacAlgorithmSpec = { HMAC_SHA_224: "HMAC_SHA_224", HMAC_SHA_256: "HMAC_SHA_256", HMAC_SHA_384: "HMAC_SHA_384", HMAC_SHA_512: "HMAC_SHA_512", }; exports.MultiRegionKeyType = { PRIMARY: "PRIMARY", REPLICA: "REPLICA", }; exports.SigningAlgorithmSpec = { ECDSA_SHA_256: "ECDSA_SHA_256", ECDSA_SHA_384: "ECDSA_SHA_384", ECDSA_SHA_512: "ECDSA_SHA_512", RSASSA_PKCS1_V1_5_SHA_256: "RSASSA_PKCS1_V1_5_SHA_256", RSASSA_PKCS1_V1_5_SHA_384: "RSASSA_PKCS1_V1_5_SHA_384", RSASSA_PKCS1_V1_5_SHA_512: "RSASSA_PKCS1_V1_5_SHA_512", RSASSA_PSS_SHA_256: "RSASSA_PSS_SHA_256", RSASSA_PSS_SHA_384: "RSASSA_PSS_SHA_384", RSASSA_PSS_SHA_512: "RSASSA_PSS_SHA_512", SM2DSA: "SM2DSA", }; class MalformedPolicyDocumentException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "MalformedPolicyDocumentException", $fault: "client", ...opts, }); this.name = "MalformedPolicyDocumentException"; this.$fault = "client"; Object.setPrototypeOf(this, MalformedPolicyDocumentException.prototype); } } exports.MalformedPolicyDocumentException = MalformedPolicyDocumentException; class TagException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "TagException", $fault: "client", ...opts, }); this.name = "TagException"; this.$fault = "client"; Object.setPrototypeOf(this, TagException.prototype); } } exports.TagException = TagException; class UnsupportedOperationException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "UnsupportedOperationException", $fault: "client", ...opts, }); this.name = "UnsupportedOperationException"; this.$fault = "client"; Object.setPrototypeOf(this, UnsupportedOperationException.prototype); } } exports.UnsupportedOperationException = UnsupportedOperationException; class XksKeyAlreadyInUseException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "XksKeyAlreadyInUseException", $fault: "client", ...opts, }); this.name = "XksKeyAlreadyInUseException"; this.$fault = "client"; Object.setPrototypeOf(this, XksKeyAlreadyInUseException.prototype); } } exports.XksKeyAlreadyInUseException = XksKeyAlreadyInUseException; class XksKeyInvalidConfigurationException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "XksKeyInvalidConfigurationException", $fault: "client", ...opts, }); this.name = "XksKeyInvalidConfigurationException"; this.$fault = "client"; Object.setPrototypeOf(this, XksKeyInvalidConfigurationException.prototype); } } exports.XksKeyInvalidConfigurationException = XksKeyInvalidConfigurationException; class XksKeyNotFoundException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "XksKeyNotFoundException", $fault: "client", ...opts, }); this.name = "XksKeyNotFoundException"; this.$fault = "client"; Object.setPrototypeOf(this, XksKeyNotFoundException.prototype); } } exports.XksKeyNotFoundException = XksKeyNotFoundException; class CustomKeyStoreHasCMKsException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "CustomKeyStoreHasCMKsException", $fault: "client", ...opts, }); this.name = "CustomKeyStoreHasCMKsException"; this.$fault = "client"; Object.setPrototypeOf(this, CustomKeyStoreHasCMKsException.prototype); } } exports.CustomKeyStoreHasCMKsException = CustomKeyStoreHasCMKsException; exports.DataKeyPairSpec = { ECC_NIST_P256: "ECC_NIST_P256", ECC_NIST_P384: "ECC_NIST_P384", ECC_NIST_P521: "ECC_NIST_P521", ECC_SECG_P256K1: "ECC_SECG_P256K1", RSA_2048: "RSA_2048", RSA_3072: "RSA_3072", RSA_4096: "RSA_4096", SM2: "SM2", }; exports.DataKeySpec = { AES_128: "AES_128", AES_256: "AES_256", }; exports.KeyEncryptionMechanism = { RSAES_OAEP_SHA_256: "RSAES_OAEP_SHA_256", }; class IncorrectKeyException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "IncorrectKeyException", $fault: "client", ...opts, }); this.name = "IncorrectKeyException"; this.$fault = "client"; Object.setPrototypeOf(this, IncorrectKeyException.prototype); } } exports.IncorrectKeyException = IncorrectKeyException; class InvalidCiphertextException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "InvalidCiphertextException", $fault: "client", ...opts, }); this.name = "InvalidCiphertextException"; this.$fault = "client"; Object.setPrototypeOf(this, InvalidCiphertextException.prototype); } } exports.InvalidCiphertextException = InvalidCiphertextException; class InvalidKeyUsageException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "InvalidKeyUsageException", $fault: "client", ...opts, }); this.name = "InvalidKeyUsageException"; this.$fault = "client"; Object.setPrototypeOf(this, InvalidKeyUsageException.prototype); } } exports.InvalidKeyUsageException = InvalidKeyUsageException; class KeyUnavailableException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "KeyUnavailableException", $fault: "server", ...opts, }); this.name = "KeyUnavailableException"; this.$fault = "server"; Object.setPrototypeOf(this, KeyUnavailableException.prototype); } } exports.KeyUnavailableException = KeyUnavailableException; class InvalidMarkerException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "InvalidMarkerException", $fault: "client", ...opts, }); this.name = "InvalidMarkerException"; this.$fault = "client"; Object.setPrototypeOf(this, InvalidMarkerException.prototype); } } exports.InvalidMarkerException = InvalidMarkerException; class ExpiredImportTokenException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "ExpiredImportTokenException", $fault: "client", ...opts, }); this.name = "ExpiredImportTokenException"; this.$fault = "client"; Object.setPrototypeOf(this, ExpiredImportTokenException.prototype); } } exports.ExpiredImportTokenException = ExpiredImportTokenException; exports.WrappingKeySpec = { RSA_2048: "RSA_2048", RSA_3072: "RSA_3072", RSA_4096: "RSA_4096", }; class IncorrectKeyMaterialException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "IncorrectKeyMaterialException", $fault: "client", ...opts, }); this.name = "IncorrectKeyMaterialException"; this.$fault = "client"; Object.setPrototypeOf(this, IncorrectKeyMaterialException.prototype); } } exports.IncorrectKeyMaterialException = IncorrectKeyMaterialException; class InvalidImportTokenException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "InvalidImportTokenException", $fault: "client", ...opts, }); this.name = "InvalidImportTokenException"; this.$fault = "client"; Object.setPrototypeOf(this, InvalidImportTokenException.prototype); } } exports.InvalidImportTokenException = InvalidImportTokenException; class InvalidGrantIdException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "InvalidGrantIdException", $fault: "client", ...opts, }); this.name = "InvalidGrantIdException"; this.$fault = "client"; Object.setPrototypeOf(this, InvalidGrantIdException.prototype); } } exports.InvalidGrantIdException = InvalidGrantIdException; class KMSInvalidMacException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "KMSInvalidMacException", $fault: "client", ...opts, }); this.name = "KMSInvalidMacException"; this.$fault = "client"; Object.setPrototypeOf(this, KMSInvalidMacException.prototype); } } exports.KMSInvalidMacException = KMSInvalidMacException; class KMSInvalidSignatureException extends KMSServiceException_1.KMSServiceException { constructor(opts) { super({ name: "KMSInvalidSignatureException", $fault: "client", ...opts, }); this.name = "KMSInvalidSignatureException"; this.$fault = "client"; Object.setPrototypeOf(this, KMSInvalidSignatureException.prototype); } } exports.KMSInvalidSignatureException = KMSInvalidSignatureException; exports.MessageType = { DIGEST: "DIGEST", RAW: "RAW", }; const XksProxyAuthenticationCredentialTypeFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.AccessKeyId && { AccessKeyId: smithy_client_1.SENSITIVE_STRING }), ...(obj.RawSecretAccessKey && { RawSecretAccessKey: smithy_client_1.SENSITIVE_STRING }), }); exports.XksProxyAuthenticationCredentialTypeFilterSensitiveLog = XksProxyAuthenticationCredentialTypeFilterSensitiveLog; const CreateCustomKeyStoreRequestFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.KeyStorePassword && { KeyStorePassword: smithy_client_1.SENSITIVE_STRING }), ...(obj.XksProxyAuthenticationCredential && { XksProxyAuthenticationCredential: (0, exports.XksProxyAuthenticationCredentialTypeFilterSensitiveLog)(obj.XksProxyAuthenticationCredential), }), }); exports.CreateCustomKeyStoreRequestFilterSensitiveLog = CreateCustomKeyStoreRequestFilterSensitiveLog; const XksProxyConfigurationTypeFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.AccessKeyId && { AccessKeyId: smithy_client_1.SENSITIVE_STRING }), }); exports.XksProxyConfigurationTypeFilterSensitiveLog = XksProxyConfigurationTypeFilterSensitiveLog; const CustomKeyStoresListEntryFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.XksProxyConfiguration && { XksProxyConfiguration: (0, exports.XksProxyConfigurationTypeFilterSensitiveLog)(obj.XksProxyConfiguration), }), }); exports.CustomKeyStoresListEntryFilterSensitiveLog = CustomKeyStoresListEntryFilterSensitiveLog; const DecryptResponseFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.Plaintext && { Plaintext: smithy_client_1.SENSITIVE_STRING }), }); exports.DecryptResponseFilterSensitiveLog = DecryptResponseFilterSensitiveLog; const DescribeCustomKeyStoresResponseFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.CustomKeyStores && { CustomKeyStores: obj.CustomKeyStores.map((item) => (0, exports.CustomKeyStoresListEntryFilterSensitiveLog)(item)), }), }); exports.DescribeCustomKeyStoresResponseFilterSensitiveLog = DescribeCustomKeyStoresResponseFilterSensitiveLog; const EncryptRequestFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.Plaintext && { Plaintext: smithy_client_1.SENSITIVE_STRING }), }); exports.EncryptRequestFilterSensitiveLog = EncryptRequestFilterSensitiveLog; const GenerateDataKeyResponseFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.Plaintext && { Plaintext: smithy_client_1.SENSITIVE_STRING }), }); exports.GenerateDataKeyResponseFilterSensitiveLog = GenerateDataKeyResponseFilterSensitiveLog; const GenerateDataKeyPairResponseFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.PrivateKeyPlaintext && { PrivateKeyPlaintext: smithy_client_1.SENSITIVE_STRING }), }); exports.GenerateDataKeyPairResponseFilterSensitiveLog = GenerateDataKeyPairResponseFilterSensitiveLog; const GenerateMacRequestFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.Message && { Message: smithy_client_1.SENSITIVE_STRING }), }); exports.GenerateMacRequestFilterSensitiveLog = GenerateMacRequestFilterSensitiveLog; const GenerateRandomResponseFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.Plaintext && { Plaintext: smithy_client_1.SENSITIVE_STRING }), }); exports.GenerateRandomResponseFilterSensitiveLog = GenerateRandomResponseFilterSensitiveLog; const GetParametersForImportResponseFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.PublicKey && { PublicKey: smithy_client_1.SENSITIVE_STRING }), }); exports.GetParametersForImportResponseFilterSensitiveLog = GetParametersForImportResponseFilterSensitiveLog; const SignRequestFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.Message && { Message: smithy_client_1.SENSITIVE_STRING }), }); exports.SignRequestFilterSensitiveLog = SignRequestFilterSensitiveLog; const UpdateCustomKeyStoreRequestFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.KeyStorePassword && { KeyStorePassword: smithy_client_1.SENSITIVE_STRING }), ...(obj.XksProxyAuthenticationCredential && { XksProxyAuthenticationCredential: (0, exports.XksProxyAuthenticationCredentialTypeFilterSensitiveLog)(obj.XksProxyAuthenticationCredential), }), }); exports.UpdateCustomKeyStoreRequestFilterSensitiveLog = UpdateCustomKeyStoreRequestFilterSensitiveLog; const VerifyRequestFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.Message && { Message: smithy_client_1.SENSITIVE_STRING }), }); exports.VerifyRequestFilterSensitiveLog = VerifyRequestFilterSensitiveLog; const VerifyMacRequestFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.Message && { Message: smithy_client_1.SENSITIVE_STRING }), }); exports.VerifyMacRequestFilterSensitiveLog = VerifyMacRequestFilterSensitiveLog; /***/ }), /***/ 104: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.paginateDescribeCustomKeyStores = void 0; const DescribeCustomKeyStoresCommand_1 = __nccwpck_require__(25454); const KMSClient_1 = __nccwpck_require__(33690); const makePagedClientRequest = async (client, input, ...args) => { return await client.send(new DescribeCustomKeyStoresCommand_1.DescribeCustomKeyStoresCommand(input), ...args); }; async function* paginateDescribeCustomKeyStores(config, input, ...additionalArguments) { let token = config.startingToken || undefined; let hasNext = true; let page; while (hasNext) { input.Marker = token; input["Limit"] = config.pageSize; if (config.client instanceof KMSClient_1.KMSClient) { page = await makePagedClientRequest(config.client, input, ...additionalArguments); } else { throw new Error("Invalid client, expected KMS | KMSClient"); } yield page; const prevToken = token; token = page.NextMarker; hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); } return undefined; } exports.paginateDescribeCustomKeyStores = paginateDescribeCustomKeyStores; /***/ }), /***/ 3597: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 23294: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.paginateListAliases = void 0; const ListAliasesCommand_1 = __nccwpck_require__(99534); const KMSClient_1 = __nccwpck_require__(33690); const makePagedClientRequest = async (client, input, ...args) => { return await client.send(new ListAliasesCommand_1.ListAliasesCommand(input), ...args); }; async function* paginateListAliases(config, input, ...additionalArguments) { let token = config.startingToken || undefined; let hasNext = true; let page; while (hasNext) { input.Marker = token; input["Limit"] = config.pageSize; if (config.client instanceof KMSClient_1.KMSClient) { page = await makePagedClientRequest(config.client, input, ...additionalArguments); } else { throw new Error("Invalid client, expected KMS | KMSClient"); } yield page; const prevToken = token; token = page.NextMarker; hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); } return undefined; } exports.paginateListAliases = paginateListAliases; /***/ }), /***/ 28289: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.paginateListGrants = void 0; const ListGrantsCommand_1 = __nccwpck_require__(13372); const KMSClient_1 = __nccwpck_require__(33690); const makePagedClientRequest = async (client, input, ...args) => { return await client.send(new ListGrantsCommand_1.ListGrantsCommand(input), ...args); }; async function* paginateListGrants(config, input, ...additionalArguments) { let token = config.startingToken || undefined; let hasNext = true; let page; while (hasNext) { input.Marker = token; input["Limit"] = config.pageSize; if (config.client instanceof KMSClient_1.KMSClient) { page = await makePagedClientRequest(config.client, input, ...additionalArguments); } else { throw new Error("Invalid client, expected KMS | KMSClient"); } yield page; const prevToken = token; token = page.NextMarker; hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); } return undefined; } exports.paginateListGrants = paginateListGrants; /***/ }), /***/ 56395: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.paginateListKeyPolicies = void 0; const ListKeyPoliciesCommand_1 = __nccwpck_require__(54788); const KMSClient_1 = __nccwpck_require__(33690); const makePagedClientRequest = async (client, input, ...args) => { return await client.send(new ListKeyPoliciesCommand_1.ListKeyPoliciesCommand(input), ...args); }; async function* paginateListKeyPolicies(config, input, ...additionalArguments) { let token = config.startingToken || undefined; let hasNext = true; let page; while (hasNext) { input.Marker = token; input["Limit"] = config.pageSize; if (config.client instanceof KMSClient_1.KMSClient) { page = await makePagedClientRequest(config.client, input, ...additionalArguments); } else { throw new Error("Invalid client, expected KMS | KMSClient"); } yield page; const prevToken = token; token = page.NextMarker; hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); } return undefined; } exports.paginateListKeyPolicies = paginateListKeyPolicies; /***/ }), /***/ 57480: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.paginateListKeys = void 0; const ListKeysCommand_1 = __nccwpck_require__(76274); const KMSClient_1 = __nccwpck_require__(33690); const makePagedClientRequest = async (client, input, ...args) => { return await client.send(new ListKeysCommand_1.ListKeysCommand(input), ...args); }; async function* paginateListKeys(config, input, ...additionalArguments) { let token = config.startingToken || undefined; let hasNext = true; let page; while (hasNext) { input.Marker = token; input["Limit"] = config.pageSize; if (config.client instanceof KMSClient_1.KMSClient) { page = await makePagedClientRequest(config.client, input, ...additionalArguments); } else { throw new Error("Invalid client, expected KMS | KMSClient"); } yield page; const prevToken = token; token = page.NextMarker; hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); } return undefined; } exports.paginateListKeys = paginateListKeys; /***/ }), /***/ 36042: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.paginateListResourceTags = void 0; const ListResourceTagsCommand_1 = __nccwpck_require__(33207); const KMSClient_1 = __nccwpck_require__(33690); const makePagedClientRequest = async (client, input, ...args) => { return await client.send(new ListResourceTagsCommand_1.ListResourceTagsCommand(input), ...args); }; async function* paginateListResourceTags(config, input, ...additionalArguments) { let token = config.startingToken || undefined; let hasNext = true; let page; while (hasNext) { input.Marker = token; input["Limit"] = config.pageSize; if (config.client instanceof KMSClient_1.KMSClient) { page = await makePagedClientRequest(config.client, input, ...additionalArguments); } else { throw new Error("Invalid client, expected KMS | KMSClient"); } yield page; const prevToken = token; token = page.NextMarker; hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); } return undefined; } exports.paginateListResourceTags = paginateListResourceTags; /***/ }), /***/ 95196: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.paginateListRetirableGrants = void 0; const ListRetirableGrantsCommand_1 = __nccwpck_require__(14898); const KMSClient_1 = __nccwpck_require__(33690); const makePagedClientRequest = async (client, input, ...args) => { return await client.send(new ListRetirableGrantsCommand_1.ListRetirableGrantsCommand(input), ...args); }; async function* paginateListRetirableGrants(config, input, ...additionalArguments) { let token = config.startingToken || undefined; let hasNext = true; let page; while (hasNext) { input.Marker = token; input["Limit"] = config.pageSize; if (config.client instanceof KMSClient_1.KMSClient) { page = await makePagedClientRequest(config.client, input, ...additionalArguments); } else { throw new Error("Invalid client, expected KMS | KMSClient"); } yield page; const prevToken = token; token = page.NextMarker; hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); } return undefined; } exports.paginateListRetirableGrants = paginateListRetirableGrants; /***/ }), /***/ 55163: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(104), exports); tslib_1.__exportStar(__nccwpck_require__(3597), exports); tslib_1.__exportStar(__nccwpck_require__(23294), exports); tslib_1.__exportStar(__nccwpck_require__(28289), exports); tslib_1.__exportStar(__nccwpck_require__(56395), exports); tslib_1.__exportStar(__nccwpck_require__(57480), exports); tslib_1.__exportStar(__nccwpck_require__(36042), exports); tslib_1.__exportStar(__nccwpck_require__(95196), exports); /***/ }), /***/ 90056: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.se_VerifyMacCommand = exports.se_VerifyCommand = exports.se_UpdatePrimaryRegionCommand = exports.se_UpdateKeyDescriptionCommand = exports.se_UpdateCustomKeyStoreCommand = exports.se_UpdateAliasCommand = exports.se_UntagResourceCommand = exports.se_TagResourceCommand = exports.se_SignCommand = exports.se_ScheduleKeyDeletionCommand = exports.se_RevokeGrantCommand = exports.se_RetireGrantCommand = exports.se_ReplicateKeyCommand = exports.se_ReEncryptCommand = exports.se_PutKeyPolicyCommand = exports.se_ListRetirableGrantsCommand = exports.se_ListResourceTagsCommand = exports.se_ListKeysCommand = exports.se_ListKeyPoliciesCommand = exports.se_ListGrantsCommand = exports.se_ListAliasesCommand = exports.se_ImportKeyMaterialCommand = exports.se_GetPublicKeyCommand = exports.se_GetParametersForImportCommand = exports.se_GetKeyRotationStatusCommand = exports.se_GetKeyPolicyCommand = exports.se_GenerateRandomCommand = exports.se_GenerateMacCommand = exports.se_GenerateDataKeyWithoutPlaintextCommand = exports.se_GenerateDataKeyPairWithoutPlaintextCommand = exports.se_GenerateDataKeyPairCommand = exports.se_GenerateDataKeyCommand = exports.se_EncryptCommand = exports.se_EnableKeyRotationCommand = exports.se_EnableKeyCommand = exports.se_DisconnectCustomKeyStoreCommand = exports.se_DisableKeyRotationCommand = exports.se_DisableKeyCommand = exports.se_DescribeKeyCommand = exports.se_DescribeCustomKeyStoresCommand = exports.se_DeleteImportedKeyMaterialCommand = exports.se_DeleteCustomKeyStoreCommand = exports.se_DeleteAliasCommand = exports.se_DecryptCommand = exports.se_CreateKeyCommand = exports.se_CreateGrantCommand = exports.se_CreateCustomKeyStoreCommand = exports.se_CreateAliasCommand = exports.se_ConnectCustomKeyStoreCommand = exports.se_CancelKeyDeletionCommand = void 0; exports.de_VerifyMacCommand = exports.de_VerifyCommand = exports.de_UpdatePrimaryRegionCommand = exports.de_UpdateKeyDescriptionCommand = exports.de_UpdateCustomKeyStoreCommand = exports.de_UpdateAliasCommand = exports.de_UntagResourceCommand = exports.de_TagResourceCommand = exports.de_SignCommand = exports.de_ScheduleKeyDeletionCommand = exports.de_RevokeGrantCommand = exports.de_RetireGrantCommand = exports.de_ReplicateKeyCommand = exports.de_ReEncryptCommand = exports.de_PutKeyPolicyCommand = exports.de_ListRetirableGrantsCommand = exports.de_ListResourceTagsCommand = exports.de_ListKeysCommand = exports.de_ListKeyPoliciesCommand = exports.de_ListGrantsCommand = exports.de_ListAliasesCommand = exports.de_ImportKeyMaterialCommand = exports.de_GetPublicKeyCommand = exports.de_GetParametersForImportCommand = exports.de_GetKeyRotationStatusCommand = exports.de_GetKeyPolicyCommand = exports.de_GenerateRandomCommand = exports.de_GenerateMacCommand = exports.de_GenerateDataKeyWithoutPlaintextCommand = exports.de_GenerateDataKeyPairWithoutPlaintextCommand = exports.de_GenerateDataKeyPairCommand = exports.de_GenerateDataKeyCommand = exports.de_EncryptCommand = exports.de_EnableKeyRotationCommand = exports.de_EnableKeyCommand = exports.de_DisconnectCustomKeyStoreCommand = exports.de_DisableKeyRotationCommand = exports.de_DisableKeyCommand = exports.de_DescribeKeyCommand = exports.de_DescribeCustomKeyStoresCommand = exports.de_DeleteImportedKeyMaterialCommand = exports.de_DeleteCustomKeyStoreCommand = exports.de_DeleteAliasCommand = exports.de_DecryptCommand = exports.de_CreateKeyCommand = exports.de_CreateGrantCommand = exports.de_CreateCustomKeyStoreCommand = exports.de_CreateAliasCommand = exports.de_ConnectCustomKeyStoreCommand = exports.de_CancelKeyDeletionCommand = void 0; const protocol_http_1 = __nccwpck_require__(64418); const smithy_client_1 = __nccwpck_require__(63570); const KMSServiceException_1 = __nccwpck_require__(59602); const models_0_1 = __nccwpck_require__(52249); const se_CancelKeyDeletionCommand = async (input, context) => { const headers = sharedHeaders("CancelKeyDeletion"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_CancelKeyDeletionCommand = se_CancelKeyDeletionCommand; const se_ConnectCustomKeyStoreCommand = async (input, context) => { const headers = sharedHeaders("ConnectCustomKeyStore"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_ConnectCustomKeyStoreCommand = se_ConnectCustomKeyStoreCommand; const se_CreateAliasCommand = async (input, context) => { const headers = sharedHeaders("CreateAlias"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_CreateAliasCommand = se_CreateAliasCommand; const se_CreateCustomKeyStoreCommand = async (input, context) => { const headers = sharedHeaders("CreateCustomKeyStore"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_CreateCustomKeyStoreCommand = se_CreateCustomKeyStoreCommand; const se_CreateGrantCommand = async (input, context) => { const headers = sharedHeaders("CreateGrant"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_CreateGrantCommand = se_CreateGrantCommand; const se_CreateKeyCommand = async (input, context) => { const headers = sharedHeaders("CreateKey"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_CreateKeyCommand = se_CreateKeyCommand; const se_DecryptCommand = async (input, context) => { const headers = sharedHeaders("Decrypt"); let body; body = JSON.stringify(se_DecryptRequest(input, context)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_DecryptCommand = se_DecryptCommand; const se_DeleteAliasCommand = async (input, context) => { const headers = sharedHeaders("DeleteAlias"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_DeleteAliasCommand = se_DeleteAliasCommand; const se_DeleteCustomKeyStoreCommand = async (input, context) => { const headers = sharedHeaders("DeleteCustomKeyStore"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_DeleteCustomKeyStoreCommand = se_DeleteCustomKeyStoreCommand; const se_DeleteImportedKeyMaterialCommand = async (input, context) => { const headers = sharedHeaders("DeleteImportedKeyMaterial"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_DeleteImportedKeyMaterialCommand = se_DeleteImportedKeyMaterialCommand; const se_DescribeCustomKeyStoresCommand = async (input, context) => { const headers = sharedHeaders("DescribeCustomKeyStores"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_DescribeCustomKeyStoresCommand = se_DescribeCustomKeyStoresCommand; const se_DescribeKeyCommand = async (input, context) => { const headers = sharedHeaders("DescribeKey"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_DescribeKeyCommand = se_DescribeKeyCommand; const se_DisableKeyCommand = async (input, context) => { const headers = sharedHeaders("DisableKey"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_DisableKeyCommand = se_DisableKeyCommand; const se_DisableKeyRotationCommand = async (input, context) => { const headers = sharedHeaders("DisableKeyRotation"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_DisableKeyRotationCommand = se_DisableKeyRotationCommand; const se_DisconnectCustomKeyStoreCommand = async (input, context) => { const headers = sharedHeaders("DisconnectCustomKeyStore"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_DisconnectCustomKeyStoreCommand = se_DisconnectCustomKeyStoreCommand; const se_EnableKeyCommand = async (input, context) => { const headers = sharedHeaders("EnableKey"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_EnableKeyCommand = se_EnableKeyCommand; const se_EnableKeyRotationCommand = async (input, context) => { const headers = sharedHeaders("EnableKeyRotation"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_EnableKeyRotationCommand = se_EnableKeyRotationCommand; const se_EncryptCommand = async (input, context) => { const headers = sharedHeaders("Encrypt"); let body; body = JSON.stringify(se_EncryptRequest(input, context)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_EncryptCommand = se_EncryptCommand; const se_GenerateDataKeyCommand = async (input, context) => { const headers = sharedHeaders("GenerateDataKey"); let body; body = JSON.stringify(se_GenerateDataKeyRequest(input, context)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_GenerateDataKeyCommand = se_GenerateDataKeyCommand; const se_GenerateDataKeyPairCommand = async (input, context) => { const headers = sharedHeaders("GenerateDataKeyPair"); let body; body = JSON.stringify(se_GenerateDataKeyPairRequest(input, context)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_GenerateDataKeyPairCommand = se_GenerateDataKeyPairCommand; const se_GenerateDataKeyPairWithoutPlaintextCommand = async (input, context) => { const headers = sharedHeaders("GenerateDataKeyPairWithoutPlaintext"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_GenerateDataKeyPairWithoutPlaintextCommand = se_GenerateDataKeyPairWithoutPlaintextCommand; const se_GenerateDataKeyWithoutPlaintextCommand = async (input, context) => { const headers = sharedHeaders("GenerateDataKeyWithoutPlaintext"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_GenerateDataKeyWithoutPlaintextCommand = se_GenerateDataKeyWithoutPlaintextCommand; const se_GenerateMacCommand = async (input, context) => { const headers = sharedHeaders("GenerateMac"); let body; body = JSON.stringify(se_GenerateMacRequest(input, context)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_GenerateMacCommand = se_GenerateMacCommand; const se_GenerateRandomCommand = async (input, context) => { const headers = sharedHeaders("GenerateRandom"); let body; body = JSON.stringify(se_GenerateRandomRequest(input, context)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_GenerateRandomCommand = se_GenerateRandomCommand; const se_GetKeyPolicyCommand = async (input, context) => { const headers = sharedHeaders("GetKeyPolicy"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_GetKeyPolicyCommand = se_GetKeyPolicyCommand; const se_GetKeyRotationStatusCommand = async (input, context) => { const headers = sharedHeaders("GetKeyRotationStatus"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_GetKeyRotationStatusCommand = se_GetKeyRotationStatusCommand; const se_GetParametersForImportCommand = async (input, context) => { const headers = sharedHeaders("GetParametersForImport"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_GetParametersForImportCommand = se_GetParametersForImportCommand; const se_GetPublicKeyCommand = async (input, context) => { const headers = sharedHeaders("GetPublicKey"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_GetPublicKeyCommand = se_GetPublicKeyCommand; const se_ImportKeyMaterialCommand = async (input, context) => { const headers = sharedHeaders("ImportKeyMaterial"); let body; body = JSON.stringify(se_ImportKeyMaterialRequest(input, context)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_ImportKeyMaterialCommand = se_ImportKeyMaterialCommand; const se_ListAliasesCommand = async (input, context) => { const headers = sharedHeaders("ListAliases"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_ListAliasesCommand = se_ListAliasesCommand; const se_ListGrantsCommand = async (input, context) => { const headers = sharedHeaders("ListGrants"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_ListGrantsCommand = se_ListGrantsCommand; const se_ListKeyPoliciesCommand = async (input, context) => { const headers = sharedHeaders("ListKeyPolicies"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_ListKeyPoliciesCommand = se_ListKeyPoliciesCommand; const se_ListKeysCommand = async (input, context) => { const headers = sharedHeaders("ListKeys"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_ListKeysCommand = se_ListKeysCommand; const se_ListResourceTagsCommand = async (input, context) => { const headers = sharedHeaders("ListResourceTags"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_ListResourceTagsCommand = se_ListResourceTagsCommand; const se_ListRetirableGrantsCommand = async (input, context) => { const headers = sharedHeaders("ListRetirableGrants"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_ListRetirableGrantsCommand = se_ListRetirableGrantsCommand; const se_PutKeyPolicyCommand = async (input, context) => { const headers = sharedHeaders("PutKeyPolicy"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_PutKeyPolicyCommand = se_PutKeyPolicyCommand; const se_ReEncryptCommand = async (input, context) => { const headers = sharedHeaders("ReEncrypt"); let body; body = JSON.stringify(se_ReEncryptRequest(input, context)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_ReEncryptCommand = se_ReEncryptCommand; const se_ReplicateKeyCommand = async (input, context) => { const headers = sharedHeaders("ReplicateKey"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_ReplicateKeyCommand = se_ReplicateKeyCommand; const se_RetireGrantCommand = async (input, context) => { const headers = sharedHeaders("RetireGrant"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_RetireGrantCommand = se_RetireGrantCommand; const se_RevokeGrantCommand = async (input, context) => { const headers = sharedHeaders("RevokeGrant"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_RevokeGrantCommand = se_RevokeGrantCommand; const se_ScheduleKeyDeletionCommand = async (input, context) => { const headers = sharedHeaders("ScheduleKeyDeletion"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_ScheduleKeyDeletionCommand = se_ScheduleKeyDeletionCommand; const se_SignCommand = async (input, context) => { const headers = sharedHeaders("Sign"); let body; body = JSON.stringify(se_SignRequest(input, context)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_SignCommand = se_SignCommand; const se_TagResourceCommand = async (input, context) => { const headers = sharedHeaders("TagResource"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_TagResourceCommand = se_TagResourceCommand; const se_UntagResourceCommand = async (input, context) => { const headers = sharedHeaders("UntagResource"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_UntagResourceCommand = se_UntagResourceCommand; const se_UpdateAliasCommand = async (input, context) => { const headers = sharedHeaders("UpdateAlias"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_UpdateAliasCommand = se_UpdateAliasCommand; const se_UpdateCustomKeyStoreCommand = async (input, context) => { const headers = sharedHeaders("UpdateCustomKeyStore"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_UpdateCustomKeyStoreCommand = se_UpdateCustomKeyStoreCommand; const se_UpdateKeyDescriptionCommand = async (input, context) => { const headers = sharedHeaders("UpdateKeyDescription"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_UpdateKeyDescriptionCommand = se_UpdateKeyDescriptionCommand; const se_UpdatePrimaryRegionCommand = async (input, context) => { const headers = sharedHeaders("UpdatePrimaryRegion"); let body; body = JSON.stringify((0, smithy_client_1._json)(input)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_UpdatePrimaryRegionCommand = se_UpdatePrimaryRegionCommand; const se_VerifyCommand = async (input, context) => { const headers = sharedHeaders("Verify"); let body; body = JSON.stringify(se_VerifyRequest(input, context)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_VerifyCommand = se_VerifyCommand; const se_VerifyMacCommand = async (input, context) => { const headers = sharedHeaders("VerifyMac"); let body; body = JSON.stringify(se_VerifyMacRequest(input, context)); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_VerifyMacCommand = se_VerifyMacCommand; const de_CancelKeyDeletionCommand = async (output, context) => { if (output.statusCode >= 300) { return de_CancelKeyDeletionCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = (0, smithy_client_1._json)(data); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_CancelKeyDeletionCommand = de_CancelKeyDeletionCommand; const de_CancelKeyDeletionCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_ConnectCustomKeyStoreCommand = async (output, context) => { if (output.statusCode >= 300) { return de_ConnectCustomKeyStoreCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = (0, smithy_client_1._json)(data); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_ConnectCustomKeyStoreCommand = de_ConnectCustomKeyStoreCommand; const de_ConnectCustomKeyStoreCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "CloudHsmClusterInvalidConfigurationException": case "com.amazonaws.kms#CloudHsmClusterInvalidConfigurationException": throw await de_CloudHsmClusterInvalidConfigurationExceptionRes(parsedOutput, context); case "CloudHsmClusterNotActiveException": case "com.amazonaws.kms#CloudHsmClusterNotActiveException": throw await de_CloudHsmClusterNotActiveExceptionRes(parsedOutput, context); case "CustomKeyStoreInvalidStateException": case "com.amazonaws.kms#CustomKeyStoreInvalidStateException": throw await de_CustomKeyStoreInvalidStateExceptionRes(parsedOutput, context); case "CustomKeyStoreNotFoundException": case "com.amazonaws.kms#CustomKeyStoreNotFoundException": throw await de_CustomKeyStoreNotFoundExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_CreateAliasCommand = async (output, context) => { if (output.statusCode >= 300) { return de_CreateAliasCommandError(output, context); } await (0, smithy_client_1.collectBody)(output.body, context); const response = { $metadata: deserializeMetadata(output), }; return response; }; exports.de_CreateAliasCommand = de_CreateAliasCommand; const de_CreateAliasCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "AlreadyExistsException": case "com.amazonaws.kms#AlreadyExistsException": throw await de_AlreadyExistsExceptionRes(parsedOutput, context); case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "InvalidAliasNameException": case "com.amazonaws.kms#InvalidAliasNameException": throw await de_InvalidAliasNameExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "LimitExceededException": case "com.amazonaws.kms#LimitExceededException": throw await de_LimitExceededExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_CreateCustomKeyStoreCommand = async (output, context) => { if (output.statusCode >= 300) { return de_CreateCustomKeyStoreCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = (0, smithy_client_1._json)(data); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_CreateCustomKeyStoreCommand = de_CreateCustomKeyStoreCommand; const de_CreateCustomKeyStoreCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "CloudHsmClusterInUseException": case "com.amazonaws.kms#CloudHsmClusterInUseException": throw await de_CloudHsmClusterInUseExceptionRes(parsedOutput, context); case "CloudHsmClusterInvalidConfigurationException": case "com.amazonaws.kms#CloudHsmClusterInvalidConfigurationException": throw await de_CloudHsmClusterInvalidConfigurationExceptionRes(parsedOutput, context); case "CloudHsmClusterNotActiveException": case "com.amazonaws.kms#CloudHsmClusterNotActiveException": throw await de_CloudHsmClusterNotActiveExceptionRes(parsedOutput, context); case "CloudHsmClusterNotFoundException": case "com.amazonaws.kms#CloudHsmClusterNotFoundException": throw await de_CloudHsmClusterNotFoundExceptionRes(parsedOutput, context); case "CustomKeyStoreNameInUseException": case "com.amazonaws.kms#CustomKeyStoreNameInUseException": throw await de_CustomKeyStoreNameInUseExceptionRes(parsedOutput, context); case "IncorrectTrustAnchorException": case "com.amazonaws.kms#IncorrectTrustAnchorException": throw await de_IncorrectTrustAnchorExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "LimitExceededException": case "com.amazonaws.kms#LimitExceededException": throw await de_LimitExceededExceptionRes(parsedOutput, context); case "XksProxyIncorrectAuthenticationCredentialException": case "com.amazonaws.kms#XksProxyIncorrectAuthenticationCredentialException": throw await de_XksProxyIncorrectAuthenticationCredentialExceptionRes(parsedOutput, context); case "XksProxyInvalidConfigurationException": case "com.amazonaws.kms#XksProxyInvalidConfigurationException": throw await de_XksProxyInvalidConfigurationExceptionRes(parsedOutput, context); case "XksProxyInvalidResponseException": case "com.amazonaws.kms#XksProxyInvalidResponseException": throw await de_XksProxyInvalidResponseExceptionRes(parsedOutput, context); case "XksProxyUriEndpointInUseException": case "com.amazonaws.kms#XksProxyUriEndpointInUseException": throw await de_XksProxyUriEndpointInUseExceptionRes(parsedOutput, context); case "XksProxyUriInUseException": case "com.amazonaws.kms#XksProxyUriInUseException": throw await de_XksProxyUriInUseExceptionRes(parsedOutput, context); case "XksProxyUriUnreachableException": case "com.amazonaws.kms#XksProxyUriUnreachableException": throw await de_XksProxyUriUnreachableExceptionRes(parsedOutput, context); case "XksProxyVpcEndpointServiceInUseException": case "com.amazonaws.kms#XksProxyVpcEndpointServiceInUseException": throw await de_XksProxyVpcEndpointServiceInUseExceptionRes(parsedOutput, context); case "XksProxyVpcEndpointServiceInvalidConfigurationException": case "com.amazonaws.kms#XksProxyVpcEndpointServiceInvalidConfigurationException": throw await de_XksProxyVpcEndpointServiceInvalidConfigurationExceptionRes(parsedOutput, context); case "XksProxyVpcEndpointServiceNotFoundException": case "com.amazonaws.kms#XksProxyVpcEndpointServiceNotFoundException": throw await de_XksProxyVpcEndpointServiceNotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_CreateGrantCommand = async (output, context) => { if (output.statusCode >= 300) { return de_CreateGrantCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = (0, smithy_client_1._json)(data); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_CreateGrantCommand = de_CreateGrantCommand; const de_CreateGrantCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "DisabledException": case "com.amazonaws.kms#DisabledException": throw await de_DisabledExceptionRes(parsedOutput, context); case "DryRunOperationException": case "com.amazonaws.kms#DryRunOperationException": throw await de_DryRunOperationExceptionRes(parsedOutput, context); case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "InvalidGrantTokenException": case "com.amazonaws.kms#InvalidGrantTokenException": throw await de_InvalidGrantTokenExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "LimitExceededException": case "com.amazonaws.kms#LimitExceededException": throw await de_LimitExceededExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_CreateKeyCommand = async (output, context) => { if (output.statusCode >= 300) { return de_CreateKeyCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_CreateKeyResponse(data, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_CreateKeyCommand = de_CreateKeyCommand; const de_CreateKeyCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "CloudHsmClusterInvalidConfigurationException": case "com.amazonaws.kms#CloudHsmClusterInvalidConfigurationException": throw await de_CloudHsmClusterInvalidConfigurationExceptionRes(parsedOutput, context); case "CustomKeyStoreInvalidStateException": case "com.amazonaws.kms#CustomKeyStoreInvalidStateException": throw await de_CustomKeyStoreInvalidStateExceptionRes(parsedOutput, context); case "CustomKeyStoreNotFoundException": case "com.amazonaws.kms#CustomKeyStoreNotFoundException": throw await de_CustomKeyStoreNotFoundExceptionRes(parsedOutput, context); case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "LimitExceededException": case "com.amazonaws.kms#LimitExceededException": throw await de_LimitExceededExceptionRes(parsedOutput, context); case "MalformedPolicyDocumentException": case "com.amazonaws.kms#MalformedPolicyDocumentException": throw await de_MalformedPolicyDocumentExceptionRes(parsedOutput, context); case "TagException": case "com.amazonaws.kms#TagException": throw await de_TagExceptionRes(parsedOutput, context); case "UnsupportedOperationException": case "com.amazonaws.kms#UnsupportedOperationException": throw await de_UnsupportedOperationExceptionRes(parsedOutput, context); case "XksKeyAlreadyInUseException": case "com.amazonaws.kms#XksKeyAlreadyInUseException": throw await de_XksKeyAlreadyInUseExceptionRes(parsedOutput, context); case "XksKeyInvalidConfigurationException": case "com.amazonaws.kms#XksKeyInvalidConfigurationException": throw await de_XksKeyInvalidConfigurationExceptionRes(parsedOutput, context); case "XksKeyNotFoundException": case "com.amazonaws.kms#XksKeyNotFoundException": throw await de_XksKeyNotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_DecryptCommand = async (output, context) => { if (output.statusCode >= 300) { return de_DecryptCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_DecryptResponse(data, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_DecryptCommand = de_DecryptCommand; const de_DecryptCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "DisabledException": case "com.amazonaws.kms#DisabledException": throw await de_DisabledExceptionRes(parsedOutput, context); case "DryRunOperationException": case "com.amazonaws.kms#DryRunOperationException": throw await de_DryRunOperationExceptionRes(parsedOutput, context); case "IncorrectKeyException": case "com.amazonaws.kms#IncorrectKeyException": throw await de_IncorrectKeyExceptionRes(parsedOutput, context); case "InvalidCiphertextException": case "com.amazonaws.kms#InvalidCiphertextException": throw await de_InvalidCiphertextExceptionRes(parsedOutput, context); case "InvalidGrantTokenException": case "com.amazonaws.kms#InvalidGrantTokenException": throw await de_InvalidGrantTokenExceptionRes(parsedOutput, context); case "InvalidKeyUsageException": case "com.amazonaws.kms#InvalidKeyUsageException": throw await de_InvalidKeyUsageExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "KeyUnavailableException": case "com.amazonaws.kms#KeyUnavailableException": throw await de_KeyUnavailableExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_DeleteAliasCommand = async (output, context) => { if (output.statusCode >= 300) { return de_DeleteAliasCommandError(output, context); } await (0, smithy_client_1.collectBody)(output.body, context); const response = { $metadata: deserializeMetadata(output), }; return response; }; exports.de_DeleteAliasCommand = de_DeleteAliasCommand; const de_DeleteAliasCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_DeleteCustomKeyStoreCommand = async (output, context) => { if (output.statusCode >= 300) { return de_DeleteCustomKeyStoreCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = (0, smithy_client_1._json)(data); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_DeleteCustomKeyStoreCommand = de_DeleteCustomKeyStoreCommand; const de_DeleteCustomKeyStoreCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "CustomKeyStoreHasCMKsException": case "com.amazonaws.kms#CustomKeyStoreHasCMKsException": throw await de_CustomKeyStoreHasCMKsExceptionRes(parsedOutput, context); case "CustomKeyStoreInvalidStateException": case "com.amazonaws.kms#CustomKeyStoreInvalidStateException": throw await de_CustomKeyStoreInvalidStateExceptionRes(parsedOutput, context); case "CustomKeyStoreNotFoundException": case "com.amazonaws.kms#CustomKeyStoreNotFoundException": throw await de_CustomKeyStoreNotFoundExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_DeleteImportedKeyMaterialCommand = async (output, context) => { if (output.statusCode >= 300) { return de_DeleteImportedKeyMaterialCommandError(output, context); } await (0, smithy_client_1.collectBody)(output.body, context); const response = { $metadata: deserializeMetadata(output), }; return response; }; exports.de_DeleteImportedKeyMaterialCommand = de_DeleteImportedKeyMaterialCommand; const de_DeleteImportedKeyMaterialCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); case "UnsupportedOperationException": case "com.amazonaws.kms#UnsupportedOperationException": throw await de_UnsupportedOperationExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_DescribeCustomKeyStoresCommand = async (output, context) => { if (output.statusCode >= 300) { return de_DescribeCustomKeyStoresCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_DescribeCustomKeyStoresResponse(data, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_DescribeCustomKeyStoresCommand = de_DescribeCustomKeyStoresCommand; const de_DescribeCustomKeyStoresCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "CustomKeyStoreNotFoundException": case "com.amazonaws.kms#CustomKeyStoreNotFoundException": throw await de_CustomKeyStoreNotFoundExceptionRes(parsedOutput, context); case "InvalidMarkerException": case "com.amazonaws.kms#InvalidMarkerException": throw await de_InvalidMarkerExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_DescribeKeyCommand = async (output, context) => { if (output.statusCode >= 300) { return de_DescribeKeyCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_DescribeKeyResponse(data, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_DescribeKeyCommand = de_DescribeKeyCommand; const de_DescribeKeyCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_DisableKeyCommand = async (output, context) => { if (output.statusCode >= 300) { return de_DisableKeyCommandError(output, context); } await (0, smithy_client_1.collectBody)(output.body, context); const response = { $metadata: deserializeMetadata(output), }; return response; }; exports.de_DisableKeyCommand = de_DisableKeyCommand; const de_DisableKeyCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_DisableKeyRotationCommand = async (output, context) => { if (output.statusCode >= 300) { return de_DisableKeyRotationCommandError(output, context); } await (0, smithy_client_1.collectBody)(output.body, context); const response = { $metadata: deserializeMetadata(output), }; return response; }; exports.de_DisableKeyRotationCommand = de_DisableKeyRotationCommand; const de_DisableKeyRotationCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "DisabledException": case "com.amazonaws.kms#DisabledException": throw await de_DisabledExceptionRes(parsedOutput, context); case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); case "UnsupportedOperationException": case "com.amazonaws.kms#UnsupportedOperationException": throw await de_UnsupportedOperationExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_DisconnectCustomKeyStoreCommand = async (output, context) => { if (output.statusCode >= 300) { return de_DisconnectCustomKeyStoreCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = (0, smithy_client_1._json)(data); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_DisconnectCustomKeyStoreCommand = de_DisconnectCustomKeyStoreCommand; const de_DisconnectCustomKeyStoreCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "CustomKeyStoreInvalidStateException": case "com.amazonaws.kms#CustomKeyStoreInvalidStateException": throw await de_CustomKeyStoreInvalidStateExceptionRes(parsedOutput, context); case "CustomKeyStoreNotFoundException": case "com.amazonaws.kms#CustomKeyStoreNotFoundException": throw await de_CustomKeyStoreNotFoundExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_EnableKeyCommand = async (output, context) => { if (output.statusCode >= 300) { return de_EnableKeyCommandError(output, context); } await (0, smithy_client_1.collectBody)(output.body, context); const response = { $metadata: deserializeMetadata(output), }; return response; }; exports.de_EnableKeyCommand = de_EnableKeyCommand; const de_EnableKeyCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "LimitExceededException": case "com.amazonaws.kms#LimitExceededException": throw await de_LimitExceededExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_EnableKeyRotationCommand = async (output, context) => { if (output.statusCode >= 300) { return de_EnableKeyRotationCommandError(output, context); } await (0, smithy_client_1.collectBody)(output.body, context); const response = { $metadata: deserializeMetadata(output), }; return response; }; exports.de_EnableKeyRotationCommand = de_EnableKeyRotationCommand; const de_EnableKeyRotationCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "DisabledException": case "com.amazonaws.kms#DisabledException": throw await de_DisabledExceptionRes(parsedOutput, context); case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); case "UnsupportedOperationException": case "com.amazonaws.kms#UnsupportedOperationException": throw await de_UnsupportedOperationExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_EncryptCommand = async (output, context) => { if (output.statusCode >= 300) { return de_EncryptCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_EncryptResponse(data, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_EncryptCommand = de_EncryptCommand; const de_EncryptCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "DisabledException": case "com.amazonaws.kms#DisabledException": throw await de_DisabledExceptionRes(parsedOutput, context); case "DryRunOperationException": case "com.amazonaws.kms#DryRunOperationException": throw await de_DryRunOperationExceptionRes(parsedOutput, context); case "InvalidGrantTokenException": case "com.amazonaws.kms#InvalidGrantTokenException": throw await de_InvalidGrantTokenExceptionRes(parsedOutput, context); case "InvalidKeyUsageException": case "com.amazonaws.kms#InvalidKeyUsageException": throw await de_InvalidKeyUsageExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "KeyUnavailableException": case "com.amazonaws.kms#KeyUnavailableException": throw await de_KeyUnavailableExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_GenerateDataKeyCommand = async (output, context) => { if (output.statusCode >= 300) { return de_GenerateDataKeyCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_GenerateDataKeyResponse(data, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_GenerateDataKeyCommand = de_GenerateDataKeyCommand; const de_GenerateDataKeyCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "DisabledException": case "com.amazonaws.kms#DisabledException": throw await de_DisabledExceptionRes(parsedOutput, context); case "DryRunOperationException": case "com.amazonaws.kms#DryRunOperationException": throw await de_DryRunOperationExceptionRes(parsedOutput, context); case "InvalidGrantTokenException": case "com.amazonaws.kms#InvalidGrantTokenException": throw await de_InvalidGrantTokenExceptionRes(parsedOutput, context); case "InvalidKeyUsageException": case "com.amazonaws.kms#InvalidKeyUsageException": throw await de_InvalidKeyUsageExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "KeyUnavailableException": case "com.amazonaws.kms#KeyUnavailableException": throw await de_KeyUnavailableExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_GenerateDataKeyPairCommand = async (output, context) => { if (output.statusCode >= 300) { return de_GenerateDataKeyPairCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_GenerateDataKeyPairResponse(data, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_GenerateDataKeyPairCommand = de_GenerateDataKeyPairCommand; const de_GenerateDataKeyPairCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "DisabledException": case "com.amazonaws.kms#DisabledException": throw await de_DisabledExceptionRes(parsedOutput, context); case "DryRunOperationException": case "com.amazonaws.kms#DryRunOperationException": throw await de_DryRunOperationExceptionRes(parsedOutput, context); case "InvalidGrantTokenException": case "com.amazonaws.kms#InvalidGrantTokenException": throw await de_InvalidGrantTokenExceptionRes(parsedOutput, context); case "InvalidKeyUsageException": case "com.amazonaws.kms#InvalidKeyUsageException": throw await de_InvalidKeyUsageExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "KeyUnavailableException": case "com.amazonaws.kms#KeyUnavailableException": throw await de_KeyUnavailableExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); case "UnsupportedOperationException": case "com.amazonaws.kms#UnsupportedOperationException": throw await de_UnsupportedOperationExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_GenerateDataKeyPairWithoutPlaintextCommand = async (output, context) => { if (output.statusCode >= 300) { return de_GenerateDataKeyPairWithoutPlaintextCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_GenerateDataKeyPairWithoutPlaintextResponse(data, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_GenerateDataKeyPairWithoutPlaintextCommand = de_GenerateDataKeyPairWithoutPlaintextCommand; const de_GenerateDataKeyPairWithoutPlaintextCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "DisabledException": case "com.amazonaws.kms#DisabledException": throw await de_DisabledExceptionRes(parsedOutput, context); case "DryRunOperationException": case "com.amazonaws.kms#DryRunOperationException": throw await de_DryRunOperationExceptionRes(parsedOutput, context); case "InvalidGrantTokenException": case "com.amazonaws.kms#InvalidGrantTokenException": throw await de_InvalidGrantTokenExceptionRes(parsedOutput, context); case "InvalidKeyUsageException": case "com.amazonaws.kms#InvalidKeyUsageException": throw await de_InvalidKeyUsageExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "KeyUnavailableException": case "com.amazonaws.kms#KeyUnavailableException": throw await de_KeyUnavailableExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); case "UnsupportedOperationException": case "com.amazonaws.kms#UnsupportedOperationException": throw await de_UnsupportedOperationExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_GenerateDataKeyWithoutPlaintextCommand = async (output, context) => { if (output.statusCode >= 300) { return de_GenerateDataKeyWithoutPlaintextCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_GenerateDataKeyWithoutPlaintextResponse(data, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_GenerateDataKeyWithoutPlaintextCommand = de_GenerateDataKeyWithoutPlaintextCommand; const de_GenerateDataKeyWithoutPlaintextCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "DisabledException": case "com.amazonaws.kms#DisabledException": throw await de_DisabledExceptionRes(parsedOutput, context); case "DryRunOperationException": case "com.amazonaws.kms#DryRunOperationException": throw await de_DryRunOperationExceptionRes(parsedOutput, context); case "InvalidGrantTokenException": case "com.amazonaws.kms#InvalidGrantTokenException": throw await de_InvalidGrantTokenExceptionRes(parsedOutput, context); case "InvalidKeyUsageException": case "com.amazonaws.kms#InvalidKeyUsageException": throw await de_InvalidKeyUsageExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "KeyUnavailableException": case "com.amazonaws.kms#KeyUnavailableException": throw await de_KeyUnavailableExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_GenerateMacCommand = async (output, context) => { if (output.statusCode >= 300) { return de_GenerateMacCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_GenerateMacResponse(data, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_GenerateMacCommand = de_GenerateMacCommand; const de_GenerateMacCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DisabledException": case "com.amazonaws.kms#DisabledException": throw await de_DisabledExceptionRes(parsedOutput, context); case "DryRunOperationException": case "com.amazonaws.kms#DryRunOperationException": throw await de_DryRunOperationExceptionRes(parsedOutput, context); case "InvalidGrantTokenException": case "com.amazonaws.kms#InvalidGrantTokenException": throw await de_InvalidGrantTokenExceptionRes(parsedOutput, context); case "InvalidKeyUsageException": case "com.amazonaws.kms#InvalidKeyUsageException": throw await de_InvalidKeyUsageExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "KeyUnavailableException": case "com.amazonaws.kms#KeyUnavailableException": throw await de_KeyUnavailableExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_GenerateRandomCommand = async (output, context) => { if (output.statusCode >= 300) { return de_GenerateRandomCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_GenerateRandomResponse(data, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_GenerateRandomCommand = de_GenerateRandomCommand; const de_GenerateRandomCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "CustomKeyStoreInvalidStateException": case "com.amazonaws.kms#CustomKeyStoreInvalidStateException": throw await de_CustomKeyStoreInvalidStateExceptionRes(parsedOutput, context); case "CustomKeyStoreNotFoundException": case "com.amazonaws.kms#CustomKeyStoreNotFoundException": throw await de_CustomKeyStoreNotFoundExceptionRes(parsedOutput, context); case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "UnsupportedOperationException": case "com.amazonaws.kms#UnsupportedOperationException": throw await de_UnsupportedOperationExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_GetKeyPolicyCommand = async (output, context) => { if (output.statusCode >= 300) { return de_GetKeyPolicyCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = (0, smithy_client_1._json)(data); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_GetKeyPolicyCommand = de_GetKeyPolicyCommand; const de_GetKeyPolicyCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_GetKeyRotationStatusCommand = async (output, context) => { if (output.statusCode >= 300) { return de_GetKeyRotationStatusCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = (0, smithy_client_1._json)(data); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_GetKeyRotationStatusCommand = de_GetKeyRotationStatusCommand; const de_GetKeyRotationStatusCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); case "UnsupportedOperationException": case "com.amazonaws.kms#UnsupportedOperationException": throw await de_UnsupportedOperationExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_GetParametersForImportCommand = async (output, context) => { if (output.statusCode >= 300) { return de_GetParametersForImportCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_GetParametersForImportResponse(data, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_GetParametersForImportCommand = de_GetParametersForImportCommand; const de_GetParametersForImportCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); case "UnsupportedOperationException": case "com.amazonaws.kms#UnsupportedOperationException": throw await de_UnsupportedOperationExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_GetPublicKeyCommand = async (output, context) => { if (output.statusCode >= 300) { return de_GetPublicKeyCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_GetPublicKeyResponse(data, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_GetPublicKeyCommand = de_GetPublicKeyCommand; const de_GetPublicKeyCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "DisabledException": case "com.amazonaws.kms#DisabledException": throw await de_DisabledExceptionRes(parsedOutput, context); case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "InvalidGrantTokenException": case "com.amazonaws.kms#InvalidGrantTokenException": throw await de_InvalidGrantTokenExceptionRes(parsedOutput, context); case "InvalidKeyUsageException": case "com.amazonaws.kms#InvalidKeyUsageException": throw await de_InvalidKeyUsageExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "KeyUnavailableException": case "com.amazonaws.kms#KeyUnavailableException": throw await de_KeyUnavailableExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); case "UnsupportedOperationException": case "com.amazonaws.kms#UnsupportedOperationException": throw await de_UnsupportedOperationExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_ImportKeyMaterialCommand = async (output, context) => { if (output.statusCode >= 300) { return de_ImportKeyMaterialCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = (0, smithy_client_1._json)(data); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_ImportKeyMaterialCommand = de_ImportKeyMaterialCommand; const de_ImportKeyMaterialCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "ExpiredImportTokenException": case "com.amazonaws.kms#ExpiredImportTokenException": throw await de_ExpiredImportTokenExceptionRes(parsedOutput, context); case "IncorrectKeyMaterialException": case "com.amazonaws.kms#IncorrectKeyMaterialException": throw await de_IncorrectKeyMaterialExceptionRes(parsedOutput, context); case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "InvalidCiphertextException": case "com.amazonaws.kms#InvalidCiphertextException": throw await de_InvalidCiphertextExceptionRes(parsedOutput, context); case "InvalidImportTokenException": case "com.amazonaws.kms#InvalidImportTokenException": throw await de_InvalidImportTokenExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); case "UnsupportedOperationException": case "com.amazonaws.kms#UnsupportedOperationException": throw await de_UnsupportedOperationExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_ListAliasesCommand = async (output, context) => { if (output.statusCode >= 300) { return de_ListAliasesCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_ListAliasesResponse(data, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_ListAliasesCommand = de_ListAliasesCommand; const de_ListAliasesCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "InvalidMarkerException": case "com.amazonaws.kms#InvalidMarkerException": throw await de_InvalidMarkerExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_ListGrantsCommand = async (output, context) => { if (output.statusCode >= 300) { return de_ListGrantsCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_ListGrantsResponse(data, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_ListGrantsCommand = de_ListGrantsCommand; const de_ListGrantsCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "InvalidGrantIdException": case "com.amazonaws.kms#InvalidGrantIdException": throw await de_InvalidGrantIdExceptionRes(parsedOutput, context); case "InvalidMarkerException": case "com.amazonaws.kms#InvalidMarkerException": throw await de_InvalidMarkerExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_ListKeyPoliciesCommand = async (output, context) => { if (output.statusCode >= 300) { return de_ListKeyPoliciesCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = (0, smithy_client_1._json)(data); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_ListKeyPoliciesCommand = de_ListKeyPoliciesCommand; const de_ListKeyPoliciesCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_ListKeysCommand = async (output, context) => { if (output.statusCode >= 300) { return de_ListKeysCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = (0, smithy_client_1._json)(data); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_ListKeysCommand = de_ListKeysCommand; const de_ListKeysCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "InvalidMarkerException": case "com.amazonaws.kms#InvalidMarkerException": throw await de_InvalidMarkerExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_ListResourceTagsCommand = async (output, context) => { if (output.statusCode >= 300) { return de_ListResourceTagsCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = (0, smithy_client_1._json)(data); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_ListResourceTagsCommand = de_ListResourceTagsCommand; const de_ListResourceTagsCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "InvalidMarkerException": case "com.amazonaws.kms#InvalidMarkerException": throw await de_InvalidMarkerExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_ListRetirableGrantsCommand = async (output, context) => { if (output.statusCode >= 300) { return de_ListRetirableGrantsCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_ListGrantsResponse(data, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_ListRetirableGrantsCommand = de_ListRetirableGrantsCommand; const de_ListRetirableGrantsCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "InvalidMarkerException": case "com.amazonaws.kms#InvalidMarkerException": throw await de_InvalidMarkerExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_PutKeyPolicyCommand = async (output, context) => { if (output.statusCode >= 300) { return de_PutKeyPolicyCommandError(output, context); } await (0, smithy_client_1.collectBody)(output.body, context); const response = { $metadata: deserializeMetadata(output), }; return response; }; exports.de_PutKeyPolicyCommand = de_PutKeyPolicyCommand; const de_PutKeyPolicyCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "LimitExceededException": case "com.amazonaws.kms#LimitExceededException": throw await de_LimitExceededExceptionRes(parsedOutput, context); case "MalformedPolicyDocumentException": case "com.amazonaws.kms#MalformedPolicyDocumentException": throw await de_MalformedPolicyDocumentExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); case "UnsupportedOperationException": case "com.amazonaws.kms#UnsupportedOperationException": throw await de_UnsupportedOperationExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_ReEncryptCommand = async (output, context) => { if (output.statusCode >= 300) { return de_ReEncryptCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_ReEncryptResponse(data, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_ReEncryptCommand = de_ReEncryptCommand; const de_ReEncryptCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "DisabledException": case "com.amazonaws.kms#DisabledException": throw await de_DisabledExceptionRes(parsedOutput, context); case "DryRunOperationException": case "com.amazonaws.kms#DryRunOperationException": throw await de_DryRunOperationExceptionRes(parsedOutput, context); case "IncorrectKeyException": case "com.amazonaws.kms#IncorrectKeyException": throw await de_IncorrectKeyExceptionRes(parsedOutput, context); case "InvalidCiphertextException": case "com.amazonaws.kms#InvalidCiphertextException": throw await de_InvalidCiphertextExceptionRes(parsedOutput, context); case "InvalidGrantTokenException": case "com.amazonaws.kms#InvalidGrantTokenException": throw await de_InvalidGrantTokenExceptionRes(parsedOutput, context); case "InvalidKeyUsageException": case "com.amazonaws.kms#InvalidKeyUsageException": throw await de_InvalidKeyUsageExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "KeyUnavailableException": case "com.amazonaws.kms#KeyUnavailableException": throw await de_KeyUnavailableExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_ReplicateKeyCommand = async (output, context) => { if (output.statusCode >= 300) { return de_ReplicateKeyCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_ReplicateKeyResponse(data, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_ReplicateKeyCommand = de_ReplicateKeyCommand; const de_ReplicateKeyCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "AlreadyExistsException": case "com.amazonaws.kms#AlreadyExistsException": throw await de_AlreadyExistsExceptionRes(parsedOutput, context); case "DisabledException": case "com.amazonaws.kms#DisabledException": throw await de_DisabledExceptionRes(parsedOutput, context); case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "LimitExceededException": case "com.amazonaws.kms#LimitExceededException": throw await de_LimitExceededExceptionRes(parsedOutput, context); case "MalformedPolicyDocumentException": case "com.amazonaws.kms#MalformedPolicyDocumentException": throw await de_MalformedPolicyDocumentExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); case "TagException": case "com.amazonaws.kms#TagException": throw await de_TagExceptionRes(parsedOutput, context); case "UnsupportedOperationException": case "com.amazonaws.kms#UnsupportedOperationException": throw await de_UnsupportedOperationExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_RetireGrantCommand = async (output, context) => { if (output.statusCode >= 300) { return de_RetireGrantCommandError(output, context); } await (0, smithy_client_1.collectBody)(output.body, context); const response = { $metadata: deserializeMetadata(output), }; return response; }; exports.de_RetireGrantCommand = de_RetireGrantCommand; const de_RetireGrantCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "DryRunOperationException": case "com.amazonaws.kms#DryRunOperationException": throw await de_DryRunOperationExceptionRes(parsedOutput, context); case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "InvalidGrantIdException": case "com.amazonaws.kms#InvalidGrantIdException": throw await de_InvalidGrantIdExceptionRes(parsedOutput, context); case "InvalidGrantTokenException": case "com.amazonaws.kms#InvalidGrantTokenException": throw await de_InvalidGrantTokenExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_RevokeGrantCommand = async (output, context) => { if (output.statusCode >= 300) { return de_RevokeGrantCommandError(output, context); } await (0, smithy_client_1.collectBody)(output.body, context); const response = { $metadata: deserializeMetadata(output), }; return response; }; exports.de_RevokeGrantCommand = de_RevokeGrantCommand; const de_RevokeGrantCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "DryRunOperationException": case "com.amazonaws.kms#DryRunOperationException": throw await de_DryRunOperationExceptionRes(parsedOutput, context); case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "InvalidGrantIdException": case "com.amazonaws.kms#InvalidGrantIdException": throw await de_InvalidGrantIdExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_ScheduleKeyDeletionCommand = async (output, context) => { if (output.statusCode >= 300) { return de_ScheduleKeyDeletionCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_ScheduleKeyDeletionResponse(data, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_ScheduleKeyDeletionCommand = de_ScheduleKeyDeletionCommand; const de_ScheduleKeyDeletionCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_SignCommand = async (output, context) => { if (output.statusCode >= 300) { return de_SignCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_SignResponse(data, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_SignCommand = de_SignCommand; const de_SignCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "DisabledException": case "com.amazonaws.kms#DisabledException": throw await de_DisabledExceptionRes(parsedOutput, context); case "DryRunOperationException": case "com.amazonaws.kms#DryRunOperationException": throw await de_DryRunOperationExceptionRes(parsedOutput, context); case "InvalidGrantTokenException": case "com.amazonaws.kms#InvalidGrantTokenException": throw await de_InvalidGrantTokenExceptionRes(parsedOutput, context); case "InvalidKeyUsageException": case "com.amazonaws.kms#InvalidKeyUsageException": throw await de_InvalidKeyUsageExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "KeyUnavailableException": case "com.amazonaws.kms#KeyUnavailableException": throw await de_KeyUnavailableExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_TagResourceCommand = async (output, context) => { if (output.statusCode >= 300) { return de_TagResourceCommandError(output, context); } await (0, smithy_client_1.collectBody)(output.body, context); const response = { $metadata: deserializeMetadata(output), }; return response; }; exports.de_TagResourceCommand = de_TagResourceCommand; const de_TagResourceCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "LimitExceededException": case "com.amazonaws.kms#LimitExceededException": throw await de_LimitExceededExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); case "TagException": case "com.amazonaws.kms#TagException": throw await de_TagExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_UntagResourceCommand = async (output, context) => { if (output.statusCode >= 300) { return de_UntagResourceCommandError(output, context); } await (0, smithy_client_1.collectBody)(output.body, context); const response = { $metadata: deserializeMetadata(output), }; return response; }; exports.de_UntagResourceCommand = de_UntagResourceCommand; const de_UntagResourceCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); case "TagException": case "com.amazonaws.kms#TagException": throw await de_TagExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_UpdateAliasCommand = async (output, context) => { if (output.statusCode >= 300) { return de_UpdateAliasCommandError(output, context); } await (0, smithy_client_1.collectBody)(output.body, context); const response = { $metadata: deserializeMetadata(output), }; return response; }; exports.de_UpdateAliasCommand = de_UpdateAliasCommand; const de_UpdateAliasCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "LimitExceededException": case "com.amazonaws.kms#LimitExceededException": throw await de_LimitExceededExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_UpdateCustomKeyStoreCommand = async (output, context) => { if (output.statusCode >= 300) { return de_UpdateCustomKeyStoreCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = (0, smithy_client_1._json)(data); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_UpdateCustomKeyStoreCommand = de_UpdateCustomKeyStoreCommand; const de_UpdateCustomKeyStoreCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "CloudHsmClusterInvalidConfigurationException": case "com.amazonaws.kms#CloudHsmClusterInvalidConfigurationException": throw await de_CloudHsmClusterInvalidConfigurationExceptionRes(parsedOutput, context); case "CloudHsmClusterNotActiveException": case "com.amazonaws.kms#CloudHsmClusterNotActiveException": throw await de_CloudHsmClusterNotActiveExceptionRes(parsedOutput, context); case "CloudHsmClusterNotFoundException": case "com.amazonaws.kms#CloudHsmClusterNotFoundException": throw await de_CloudHsmClusterNotFoundExceptionRes(parsedOutput, context); case "CloudHsmClusterNotRelatedException": case "com.amazonaws.kms#CloudHsmClusterNotRelatedException": throw await de_CloudHsmClusterNotRelatedExceptionRes(parsedOutput, context); case "CustomKeyStoreInvalidStateException": case "com.amazonaws.kms#CustomKeyStoreInvalidStateException": throw await de_CustomKeyStoreInvalidStateExceptionRes(parsedOutput, context); case "CustomKeyStoreNameInUseException": case "com.amazonaws.kms#CustomKeyStoreNameInUseException": throw await de_CustomKeyStoreNameInUseExceptionRes(parsedOutput, context); case "CustomKeyStoreNotFoundException": case "com.amazonaws.kms#CustomKeyStoreNotFoundException": throw await de_CustomKeyStoreNotFoundExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "XksProxyIncorrectAuthenticationCredentialException": case "com.amazonaws.kms#XksProxyIncorrectAuthenticationCredentialException": throw await de_XksProxyIncorrectAuthenticationCredentialExceptionRes(parsedOutput, context); case "XksProxyInvalidConfigurationException": case "com.amazonaws.kms#XksProxyInvalidConfigurationException": throw await de_XksProxyInvalidConfigurationExceptionRes(parsedOutput, context); case "XksProxyInvalidResponseException": case "com.amazonaws.kms#XksProxyInvalidResponseException": throw await de_XksProxyInvalidResponseExceptionRes(parsedOutput, context); case "XksProxyUriEndpointInUseException": case "com.amazonaws.kms#XksProxyUriEndpointInUseException": throw await de_XksProxyUriEndpointInUseExceptionRes(parsedOutput, context); case "XksProxyUriInUseException": case "com.amazonaws.kms#XksProxyUriInUseException": throw await de_XksProxyUriInUseExceptionRes(parsedOutput, context); case "XksProxyUriUnreachableException": case "com.amazonaws.kms#XksProxyUriUnreachableException": throw await de_XksProxyUriUnreachableExceptionRes(parsedOutput, context); case "XksProxyVpcEndpointServiceInUseException": case "com.amazonaws.kms#XksProxyVpcEndpointServiceInUseException": throw await de_XksProxyVpcEndpointServiceInUseExceptionRes(parsedOutput, context); case "XksProxyVpcEndpointServiceInvalidConfigurationException": case "com.amazonaws.kms#XksProxyVpcEndpointServiceInvalidConfigurationException": throw await de_XksProxyVpcEndpointServiceInvalidConfigurationExceptionRes(parsedOutput, context); case "XksProxyVpcEndpointServiceNotFoundException": case "com.amazonaws.kms#XksProxyVpcEndpointServiceNotFoundException": throw await de_XksProxyVpcEndpointServiceNotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_UpdateKeyDescriptionCommand = async (output, context) => { if (output.statusCode >= 300) { return de_UpdateKeyDescriptionCommandError(output, context); } await (0, smithy_client_1.collectBody)(output.body, context); const response = { $metadata: deserializeMetadata(output), }; return response; }; exports.de_UpdateKeyDescriptionCommand = de_UpdateKeyDescriptionCommand; const de_UpdateKeyDescriptionCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_UpdatePrimaryRegionCommand = async (output, context) => { if (output.statusCode >= 300) { return de_UpdatePrimaryRegionCommandError(output, context); } await (0, smithy_client_1.collectBody)(output.body, context); const response = { $metadata: deserializeMetadata(output), }; return response; }; exports.de_UpdatePrimaryRegionCommand = de_UpdatePrimaryRegionCommand; const de_UpdatePrimaryRegionCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DisabledException": case "com.amazonaws.kms#DisabledException": throw await de_DisabledExceptionRes(parsedOutput, context); case "InvalidArnException": case "com.amazonaws.kms#InvalidArnException": throw await de_InvalidArnExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); case "UnsupportedOperationException": case "com.amazonaws.kms#UnsupportedOperationException": throw await de_UnsupportedOperationExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_VerifyCommand = async (output, context) => { if (output.statusCode >= 300) { return de_VerifyCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = (0, smithy_client_1._json)(data); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_VerifyCommand = de_VerifyCommand; const de_VerifyCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DependencyTimeoutException": case "com.amazonaws.kms#DependencyTimeoutException": throw await de_DependencyTimeoutExceptionRes(parsedOutput, context); case "DisabledException": case "com.amazonaws.kms#DisabledException": throw await de_DisabledExceptionRes(parsedOutput, context); case "DryRunOperationException": case "com.amazonaws.kms#DryRunOperationException": throw await de_DryRunOperationExceptionRes(parsedOutput, context); case "InvalidGrantTokenException": case "com.amazonaws.kms#InvalidGrantTokenException": throw await de_InvalidGrantTokenExceptionRes(parsedOutput, context); case "InvalidKeyUsageException": case "com.amazonaws.kms#InvalidKeyUsageException": throw await de_InvalidKeyUsageExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidSignatureException": case "com.amazonaws.kms#KMSInvalidSignatureException": throw await de_KMSInvalidSignatureExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "KeyUnavailableException": case "com.amazonaws.kms#KeyUnavailableException": throw await de_KeyUnavailableExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_VerifyMacCommand = async (output, context) => { if (output.statusCode >= 300) { return de_VerifyMacCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = (0, smithy_client_1._json)(data); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_VerifyMacCommand = de_VerifyMacCommand; const de_VerifyMacCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "DisabledException": case "com.amazonaws.kms#DisabledException": throw await de_DisabledExceptionRes(parsedOutput, context); case "DryRunOperationException": case "com.amazonaws.kms#DryRunOperationException": throw await de_DryRunOperationExceptionRes(parsedOutput, context); case "InvalidGrantTokenException": case "com.amazonaws.kms#InvalidGrantTokenException": throw await de_InvalidGrantTokenExceptionRes(parsedOutput, context); case "InvalidKeyUsageException": case "com.amazonaws.kms#InvalidKeyUsageException": throw await de_InvalidKeyUsageExceptionRes(parsedOutput, context); case "KMSInternalException": case "com.amazonaws.kms#KMSInternalException": throw await de_KMSInternalExceptionRes(parsedOutput, context); case "KMSInvalidMacException": case "com.amazonaws.kms#KMSInvalidMacException": throw await de_KMSInvalidMacExceptionRes(parsedOutput, context); case "KMSInvalidStateException": case "com.amazonaws.kms#KMSInvalidStateException": throw await de_KMSInvalidStateExceptionRes(parsedOutput, context); case "KeyUnavailableException": case "com.amazonaws.kms#KeyUnavailableException": throw await de_KeyUnavailableExceptionRes(parsedOutput, context); case "NotFoundException": case "com.amazonaws.kms#NotFoundException": throw await de_NotFoundExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_AlreadyExistsExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.AlreadyExistsException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_CloudHsmClusterInUseExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.CloudHsmClusterInUseException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_CloudHsmClusterInvalidConfigurationExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.CloudHsmClusterInvalidConfigurationException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_CloudHsmClusterNotActiveExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.CloudHsmClusterNotActiveException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_CloudHsmClusterNotFoundExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.CloudHsmClusterNotFoundException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_CloudHsmClusterNotRelatedExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.CloudHsmClusterNotRelatedException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_CustomKeyStoreHasCMKsExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.CustomKeyStoreHasCMKsException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_CustomKeyStoreInvalidStateExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.CustomKeyStoreInvalidStateException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_CustomKeyStoreNameInUseExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.CustomKeyStoreNameInUseException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_CustomKeyStoreNotFoundExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.CustomKeyStoreNotFoundException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_DependencyTimeoutExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.DependencyTimeoutException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_DisabledExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.DisabledException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_DryRunOperationExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.DryRunOperationException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_ExpiredImportTokenExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.ExpiredImportTokenException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_IncorrectKeyExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.IncorrectKeyException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_IncorrectKeyMaterialExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.IncorrectKeyMaterialException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_IncorrectTrustAnchorExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.IncorrectTrustAnchorException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_InvalidAliasNameExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.InvalidAliasNameException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_InvalidArnExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.InvalidArnException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_InvalidCiphertextExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.InvalidCiphertextException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_InvalidGrantIdExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.InvalidGrantIdException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_InvalidGrantTokenExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.InvalidGrantTokenException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_InvalidImportTokenExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.InvalidImportTokenException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_InvalidKeyUsageExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.InvalidKeyUsageException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_InvalidMarkerExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.InvalidMarkerException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_KeyUnavailableExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.KeyUnavailableException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_KMSInternalExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.KMSInternalException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_KMSInvalidMacExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.KMSInvalidMacException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_KMSInvalidSignatureExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.KMSInvalidSignatureException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_KMSInvalidStateExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.KMSInvalidStateException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_LimitExceededExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.LimitExceededException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_MalformedPolicyDocumentExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.MalformedPolicyDocumentException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_NotFoundExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.NotFoundException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_TagExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.TagException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_UnsupportedOperationExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.UnsupportedOperationException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_XksKeyAlreadyInUseExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.XksKeyAlreadyInUseException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_XksKeyInvalidConfigurationExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.XksKeyInvalidConfigurationException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_XksKeyNotFoundExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.XksKeyNotFoundException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_XksProxyIncorrectAuthenticationCredentialExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.XksProxyIncorrectAuthenticationCredentialException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_XksProxyInvalidConfigurationExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.XksProxyInvalidConfigurationException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_XksProxyInvalidResponseExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.XksProxyInvalidResponseException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_XksProxyUriEndpointInUseExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.XksProxyUriEndpointInUseException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_XksProxyUriInUseExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.XksProxyUriInUseException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_XksProxyUriUnreachableExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.XksProxyUriUnreachableException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_XksProxyVpcEndpointServiceInUseExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.XksProxyVpcEndpointServiceInUseException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_XksProxyVpcEndpointServiceInvalidConfigurationExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.XksProxyVpcEndpointServiceInvalidConfigurationException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_XksProxyVpcEndpointServiceNotFoundExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = (0, smithy_client_1._json)(body); const exception = new models_0_1.XksProxyVpcEndpointServiceNotFoundException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const se_DecryptRequest = (input, context) => { return (0, smithy_client_1.take)(input, { CiphertextBlob: context.base64Encoder, DryRun: [], EncryptionAlgorithm: [], EncryptionContext: smithy_client_1._json, GrantTokens: smithy_client_1._json, KeyId: [], Recipient: (_) => se_RecipientInfo(_, context), }); }; const se_EncryptRequest = (input, context) => { return (0, smithy_client_1.take)(input, { DryRun: [], EncryptionAlgorithm: [], EncryptionContext: smithy_client_1._json, GrantTokens: smithy_client_1._json, KeyId: [], Plaintext: context.base64Encoder, }); }; const se_GenerateDataKeyPairRequest = (input, context) => { return (0, smithy_client_1.take)(input, { DryRun: [], EncryptionContext: smithy_client_1._json, GrantTokens: smithy_client_1._json, KeyId: [], KeyPairSpec: [], Recipient: (_) => se_RecipientInfo(_, context), }); }; const se_GenerateDataKeyRequest = (input, context) => { return (0, smithy_client_1.take)(input, { DryRun: [], EncryptionContext: smithy_client_1._json, GrantTokens: smithy_client_1._json, KeyId: [], KeySpec: [], NumberOfBytes: [], Recipient: (_) => se_RecipientInfo(_, context), }); }; const se_GenerateMacRequest = (input, context) => { return (0, smithy_client_1.take)(input, { DryRun: [], GrantTokens: smithy_client_1._json, KeyId: [], MacAlgorithm: [], Message: context.base64Encoder, }); }; const se_GenerateRandomRequest = (input, context) => { return (0, smithy_client_1.take)(input, { CustomKeyStoreId: [], NumberOfBytes: [], Recipient: (_) => se_RecipientInfo(_, context), }); }; const se_ImportKeyMaterialRequest = (input, context) => { return (0, smithy_client_1.take)(input, { EncryptedKeyMaterial: context.base64Encoder, ExpirationModel: [], ImportToken: context.base64Encoder, KeyId: [], ValidTo: (_) => Math.round(_.getTime() / 1000), }); }; const se_RecipientInfo = (input, context) => { return (0, smithy_client_1.take)(input, { AttestationDocument: context.base64Encoder, KeyEncryptionAlgorithm: [], }); }; const se_ReEncryptRequest = (input, context) => { return (0, smithy_client_1.take)(input, { CiphertextBlob: context.base64Encoder, DestinationEncryptionAlgorithm: [], DestinationEncryptionContext: smithy_client_1._json, DestinationKeyId: [], DryRun: [], GrantTokens: smithy_client_1._json, SourceEncryptionAlgorithm: [], SourceEncryptionContext: smithy_client_1._json, SourceKeyId: [], }); }; const se_SignRequest = (input, context) => { return (0, smithy_client_1.take)(input, { DryRun: [], GrantTokens: smithy_client_1._json, KeyId: [], Message: context.base64Encoder, MessageType: [], SigningAlgorithm: [], }); }; const se_VerifyMacRequest = (input, context) => { return (0, smithy_client_1.take)(input, { DryRun: [], GrantTokens: smithy_client_1._json, KeyId: [], Mac: context.base64Encoder, MacAlgorithm: [], Message: context.base64Encoder, }); }; const se_VerifyRequest = (input, context) => { return (0, smithy_client_1.take)(input, { DryRun: [], GrantTokens: smithy_client_1._json, KeyId: [], Message: context.base64Encoder, MessageType: [], Signature: context.base64Encoder, SigningAlgorithm: [], }); }; const de_AliasList = (output, context) => { const retVal = (output || []) .filter((e) => e != null) .map((entry) => { return de_AliasListEntry(entry, context); }); return retVal; }; const de_AliasListEntry = (output, context) => { return (0, smithy_client_1.take)(output, { AliasArn: smithy_client_1.expectString, AliasName: smithy_client_1.expectString, CreationDate: (_) => (0, smithy_client_1.expectNonNull)((0, smithy_client_1.parseEpochTimestamp)((0, smithy_client_1.expectNumber)(_))), LastUpdatedDate: (_) => (0, smithy_client_1.expectNonNull)((0, smithy_client_1.parseEpochTimestamp)((0, smithy_client_1.expectNumber)(_))), TargetKeyId: smithy_client_1.expectString, }); }; const de_CreateKeyResponse = (output, context) => { return (0, smithy_client_1.take)(output, { KeyMetadata: (_) => de_KeyMetadata(_, context), }); }; const de_CustomKeyStoresList = (output, context) => { const retVal = (output || []) .filter((e) => e != null) .map((entry) => { return de_CustomKeyStoresListEntry(entry, context); }); return retVal; }; const de_CustomKeyStoresListEntry = (output, context) => { return (0, smithy_client_1.take)(output, { CloudHsmClusterId: smithy_client_1.expectString, ConnectionErrorCode: smithy_client_1.expectString, ConnectionState: smithy_client_1.expectString, CreationDate: (_) => (0, smithy_client_1.expectNonNull)((0, smithy_client_1.parseEpochTimestamp)((0, smithy_client_1.expectNumber)(_))), CustomKeyStoreId: smithy_client_1.expectString, CustomKeyStoreName: smithy_client_1.expectString, CustomKeyStoreType: smithy_client_1.expectString, TrustAnchorCertificate: smithy_client_1.expectString, XksProxyConfiguration: smithy_client_1._json, }); }; const de_DecryptResponse = (output, context) => { return (0, smithy_client_1.take)(output, { CiphertextForRecipient: context.base64Decoder, EncryptionAlgorithm: smithy_client_1.expectString, KeyId: smithy_client_1.expectString, Plaintext: context.base64Decoder, }); }; const de_DescribeCustomKeyStoresResponse = (output, context) => { return (0, smithy_client_1.take)(output, { CustomKeyStores: (_) => de_CustomKeyStoresList(_, context), NextMarker: smithy_client_1.expectString, Truncated: smithy_client_1.expectBoolean, }); }; const de_DescribeKeyResponse = (output, context) => { return (0, smithy_client_1.take)(output, { KeyMetadata: (_) => de_KeyMetadata(_, context), }); }; const de_EncryptResponse = (output, context) => { return (0, smithy_client_1.take)(output, { CiphertextBlob: context.base64Decoder, EncryptionAlgorithm: smithy_client_1.expectString, KeyId: smithy_client_1.expectString, }); }; const de_GenerateDataKeyPairResponse = (output, context) => { return (0, smithy_client_1.take)(output, { CiphertextForRecipient: context.base64Decoder, KeyId: smithy_client_1.expectString, KeyPairSpec: smithy_client_1.expectString, PrivateKeyCiphertextBlob: context.base64Decoder, PrivateKeyPlaintext: context.base64Decoder, PublicKey: context.base64Decoder, }); }; const de_GenerateDataKeyPairWithoutPlaintextResponse = (output, context) => { return (0, smithy_client_1.take)(output, { KeyId: smithy_client_1.expectString, KeyPairSpec: smithy_client_1.expectString, PrivateKeyCiphertextBlob: context.base64Decoder, PublicKey: context.base64Decoder, }); }; const de_GenerateDataKeyResponse = (output, context) => { return (0, smithy_client_1.take)(output, { CiphertextBlob: context.base64Decoder, CiphertextForRecipient: context.base64Decoder, KeyId: smithy_client_1.expectString, Plaintext: context.base64Decoder, }); }; const de_GenerateDataKeyWithoutPlaintextResponse = (output, context) => { return (0, smithy_client_1.take)(output, { CiphertextBlob: context.base64Decoder, KeyId: smithy_client_1.expectString, }); }; const de_GenerateMacResponse = (output, context) => { return (0, smithy_client_1.take)(output, { KeyId: smithy_client_1.expectString, Mac: context.base64Decoder, MacAlgorithm: smithy_client_1.expectString, }); }; const de_GenerateRandomResponse = (output, context) => { return (0, smithy_client_1.take)(output, { CiphertextForRecipient: context.base64Decoder, Plaintext: context.base64Decoder, }); }; const de_GetParametersForImportResponse = (output, context) => { return (0, smithy_client_1.take)(output, { ImportToken: context.base64Decoder, KeyId: smithy_client_1.expectString, ParametersValidTo: (_) => (0, smithy_client_1.expectNonNull)((0, smithy_client_1.parseEpochTimestamp)((0, smithy_client_1.expectNumber)(_))), PublicKey: context.base64Decoder, }); }; const de_GetPublicKeyResponse = (output, context) => { return (0, smithy_client_1.take)(output, { CustomerMasterKeySpec: smithy_client_1.expectString, EncryptionAlgorithms: smithy_client_1._json, KeyId: smithy_client_1.expectString, KeySpec: smithy_client_1.expectString, KeyUsage: smithy_client_1.expectString, PublicKey: context.base64Decoder, SigningAlgorithms: smithy_client_1._json, }); }; const de_GrantList = (output, context) => { const retVal = (output || []) .filter((e) => e != null) .map((entry) => { return de_GrantListEntry(entry, context); }); return retVal; }; const de_GrantListEntry = (output, context) => { return (0, smithy_client_1.take)(output, { Constraints: smithy_client_1._json, CreationDate: (_) => (0, smithy_client_1.expectNonNull)((0, smithy_client_1.parseEpochTimestamp)((0, smithy_client_1.expectNumber)(_))), GrantId: smithy_client_1.expectString, GranteePrincipal: smithy_client_1.expectString, IssuingAccount: smithy_client_1.expectString, KeyId: smithy_client_1.expectString, Name: smithy_client_1.expectString, Operations: smithy_client_1._json, RetiringPrincipal: smithy_client_1.expectString, }); }; const de_KeyMetadata = (output, context) => { return (0, smithy_client_1.take)(output, { AWSAccountId: smithy_client_1.expectString, Arn: smithy_client_1.expectString, CloudHsmClusterId: smithy_client_1.expectString, CreationDate: (_) => (0, smithy_client_1.expectNonNull)((0, smithy_client_1.parseEpochTimestamp)((0, smithy_client_1.expectNumber)(_))), CustomKeyStoreId: smithy_client_1.expectString, CustomerMasterKeySpec: smithy_client_1.expectString, DeletionDate: (_) => (0, smithy_client_1.expectNonNull)((0, smithy_client_1.parseEpochTimestamp)((0, smithy_client_1.expectNumber)(_))), Description: smithy_client_1.expectString, Enabled: smithy_client_1.expectBoolean, EncryptionAlgorithms: smithy_client_1._json, ExpirationModel: smithy_client_1.expectString, KeyId: smithy_client_1.expectString, KeyManager: smithy_client_1.expectString, KeySpec: smithy_client_1.expectString, KeyState: smithy_client_1.expectString, KeyUsage: smithy_client_1.expectString, MacAlgorithms: smithy_client_1._json, MultiRegion: smithy_client_1.expectBoolean, MultiRegionConfiguration: smithy_client_1._json, Origin: smithy_client_1.expectString, PendingDeletionWindowInDays: smithy_client_1.expectInt32, SigningAlgorithms: smithy_client_1._json, ValidTo: (_) => (0, smithy_client_1.expectNonNull)((0, smithy_client_1.parseEpochTimestamp)((0, smithy_client_1.expectNumber)(_))), XksKeyConfiguration: smithy_client_1._json, }); }; const de_ListAliasesResponse = (output, context) => { return (0, smithy_client_1.take)(output, { Aliases: (_) => de_AliasList(_, context), NextMarker: smithy_client_1.expectString, Truncated: smithy_client_1.expectBoolean, }); }; const de_ListGrantsResponse = (output, context) => { return (0, smithy_client_1.take)(output, { Grants: (_) => de_GrantList(_, context), NextMarker: smithy_client_1.expectString, Truncated: smithy_client_1.expectBoolean, }); }; const de_ReEncryptResponse = (output, context) => { return (0, smithy_client_1.take)(output, { CiphertextBlob: context.base64Decoder, DestinationEncryptionAlgorithm: smithy_client_1.expectString, KeyId: smithy_client_1.expectString, SourceEncryptionAlgorithm: smithy_client_1.expectString, SourceKeyId: smithy_client_1.expectString, }); }; const de_ReplicateKeyResponse = (output, context) => { return (0, smithy_client_1.take)(output, { ReplicaKeyMetadata: (_) => de_KeyMetadata(_, context), ReplicaPolicy: smithy_client_1.expectString, ReplicaTags: smithy_client_1._json, }); }; const de_ScheduleKeyDeletionResponse = (output, context) => { return (0, smithy_client_1.take)(output, { DeletionDate: (_) => (0, smithy_client_1.expectNonNull)((0, smithy_client_1.parseEpochTimestamp)((0, smithy_client_1.expectNumber)(_))), KeyId: smithy_client_1.expectString, KeyState: smithy_client_1.expectString, PendingWindowInDays: smithy_client_1.expectInt32, }); }; const de_SignResponse = (output, context) => { return (0, smithy_client_1.take)(output, { KeyId: smithy_client_1.expectString, Signature: context.base64Decoder, SigningAlgorithm: smithy_client_1.expectString, }); }; const deserializeMetadata = (output) => ({ httpStatusCode: output.statusCode, requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], extendedRequestId: output.headers["x-amz-id-2"], cfId: output.headers["x-amz-cf-id"], }); const collectBodyString = (streamBody, context) => (0, smithy_client_1.collectBody)(streamBody, context).then((body) => context.utf8Encoder(body)); const throwDefaultError = (0, smithy_client_1.withBaseException)(KMSServiceException_1.KMSServiceException); const buildHttpRpcRequest = async (context, headers, path, resolvedHostname, body) => { const { hostname, protocol = "https", port, path: basePath } = await context.endpoint(); const contents = { protocol, hostname, port, method: "POST", path: basePath.endsWith("/") ? basePath.slice(0, -1) + path : basePath + path, headers, }; if (resolvedHostname !== undefined) { contents.hostname = resolvedHostname; } if (body !== undefined) { contents.body = body; } return new protocol_http_1.HttpRequest(contents); }; function sharedHeaders(operation) { return { "content-type": "application/x-amz-json-1.1", "x-amz-target": `TrentService.${operation}`, }; } const parseBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { if (encoded.length) { return JSON.parse(encoded); } return {}; }); const parseErrorBody = async (errorBody, context) => { const value = await parseBody(errorBody, context); value.message = value.message ?? value.Message; return value; }; const loadRestJsonErrorCode = (output, data) => { const findKey = (object, key) => Object.keys(object).find((k) => k.toLowerCase() === key.toLowerCase()); const sanitizeErrorCode = (rawValue) => { let cleanValue = rawValue; if (typeof cleanValue === "number") { cleanValue = cleanValue.toString(); } if (cleanValue.indexOf(",") >= 0) { cleanValue = cleanValue.split(",")[0]; } if (cleanValue.indexOf(":") >= 0) { cleanValue = cleanValue.split(":")[0]; } if (cleanValue.indexOf("#") >= 0) { cleanValue = cleanValue.split("#")[1]; } return cleanValue; }; const headerKey = findKey(output.headers, "x-amzn-errortype"); if (headerKey !== undefined) { return sanitizeErrorCode(output.headers[headerKey]); } if (data.code !== undefined) { return sanitizeErrorCode(data.code); } if (data["__type"] !== undefined) { return sanitizeErrorCode(data["__type"]); } }; /***/ }), /***/ 19916: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getRuntimeConfig = void 0; const tslib_1 = __nccwpck_require__(4351); const package_json_1 = tslib_1.__importDefault(__nccwpck_require__(19842)); const client_sts_1 = __nccwpck_require__(52209); const core_1 = __nccwpck_require__(59963); const credential_provider_node_1 = __nccwpck_require__(75531); const util_user_agent_node_1 = __nccwpck_require__(98095); const config_resolver_1 = __nccwpck_require__(53098); const hash_node_1 = __nccwpck_require__(3081); const middleware_retry_1 = __nccwpck_require__(96039); const node_config_provider_1 = __nccwpck_require__(33461); const node_http_handler_1 = __nccwpck_require__(20258); const util_body_length_node_1 = __nccwpck_require__(68075); const util_retry_1 = __nccwpck_require__(84902); const runtimeConfig_shared_1 = __nccwpck_require__(2920); const smithy_client_1 = __nccwpck_require__(63570); const util_defaults_mode_node_1 = __nccwpck_require__(72429); const smithy_client_2 = __nccwpck_require__(63570); const getRuntimeConfig = (config) => { (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version); const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config); const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode); const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config); (0, core_1.emitWarningIfUnsupportedVersion)(process.version); return { ...clientSharedValues, ...config, runtime: "node", defaultsMode, bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, credentialDefaultProvider: config?.credentialDefaultProvider ?? (0, client_sts_1.decorateDefaultCredentialProvider)(credential_provider_node_1.defaultProvider), defaultUserAgentProvider: config?.defaultUserAgentProvider ?? (0, util_user_agent_node_1.defaultUserAgent)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS), region: config?.region ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS), requestHandler: config?.requestHandler ?? new node_http_handler_1.NodeHttpHandler(defaultConfigProvider), retryMode: config?.retryMode ?? (0, node_config_provider_1.loadConfig)({ ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS, default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE, }), sha256: config?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"), streamCollector: config?.streamCollector ?? node_http_handler_1.streamCollector, useDualstackEndpoint: config?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS), useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS), }; }; exports.getRuntimeConfig = getRuntimeConfig; /***/ }), /***/ 2920: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getRuntimeConfig = void 0; const smithy_client_1 = __nccwpck_require__(63570); const url_parser_1 = __nccwpck_require__(14681); const util_base64_1 = __nccwpck_require__(75600); const util_utf8_1 = __nccwpck_require__(41895); const endpointResolver_1 = __nccwpck_require__(40661); const getRuntimeConfig = (config) => { return { apiVersion: "2014-11-01", base64Decoder: config?.base64Decoder ?? util_base64_1.fromBase64, base64Encoder: config?.base64Encoder ?? util_base64_1.toBase64, disableHostPrefix: config?.disableHostPrefix ?? false, endpointProvider: config?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver, extensions: config?.extensions ?? [], logger: config?.logger ?? new smithy_client_1.NoOpLogger(), serviceId: config?.serviceId ?? "KMS", urlParser: config?.urlParser ?? url_parser_1.parseUrl, utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, }; }; exports.getRuntimeConfig = getRuntimeConfig; /***/ }), /***/ 93012: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveRuntimeExtensions = void 0; const region_config_resolver_1 = __nccwpck_require__(18156); const protocol_http_1 = __nccwpck_require__(64418); const smithy_client_1 = __nccwpck_require__(63570); const asPartial = (t) => t; const resolveRuntimeExtensions = (runtimeConfig, extensions) => { const extensionConfiguration = { ...asPartial((0, region_config_resolver_1.getAwsRegionExtensionConfiguration)(runtimeConfig)), ...asPartial((0, smithy_client_1.getDefaultExtensionConfiguration)(runtimeConfig)), ...asPartial((0, protocol_http_1.getHttpHandlerExtensionConfiguration)(runtimeConfig)), }; extensions.forEach((extension) => extension.configure(extensionConfiguration)); return { ...runtimeConfig, ...(0, region_config_resolver_1.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), ...(0, smithy_client_1.resolveDefaultRuntimeConfig)(extensionConfiguration), ...(0, protocol_http_1.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), }; }; exports.resolveRuntimeExtensions = resolveRuntimeExtensions; /***/ }), /***/ 69838: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SSO = void 0; const smithy_client_1 = __nccwpck_require__(63570); const GetRoleCredentialsCommand_1 = __nccwpck_require__(18972); const ListAccountRolesCommand_1 = __nccwpck_require__(1513); const ListAccountsCommand_1 = __nccwpck_require__(64296); const LogoutCommand_1 = __nccwpck_require__(12586); const SSOClient_1 = __nccwpck_require__(71057); const commands = { GetRoleCredentialsCommand: GetRoleCredentialsCommand_1.GetRoleCredentialsCommand, ListAccountRolesCommand: ListAccountRolesCommand_1.ListAccountRolesCommand, ListAccountsCommand: ListAccountsCommand_1.ListAccountsCommand, LogoutCommand: LogoutCommand_1.LogoutCommand, }; class SSO extends SSOClient_1.SSOClient { } exports.SSO = SSO; (0, smithy_client_1.createAggregatedClient)(commands, SSO); /***/ }), /***/ 71057: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SSOClient = exports.__Client = void 0; const middleware_host_header_1 = __nccwpck_require__(22545); const middleware_logger_1 = __nccwpck_require__(20014); const middleware_recursion_detection_1 = __nccwpck_require__(85525); const middleware_user_agent_1 = __nccwpck_require__(64688); const config_resolver_1 = __nccwpck_require__(53098); const middleware_content_length_1 = __nccwpck_require__(82800); const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_retry_1 = __nccwpck_require__(96039); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "__Client", ({ enumerable: true, get: function () { return smithy_client_1.Client; } })); const EndpointParameters_1 = __nccwpck_require__(34214); const runtimeConfig_1 = __nccwpck_require__(19756); const runtimeExtensions_1 = __nccwpck_require__(63398); class SSOClient extends smithy_client_1.Client { constructor(...[configuration]) { const _config_0 = (0, runtimeConfig_1.getRuntimeConfig)(configuration || {}); const _config_1 = (0, EndpointParameters_1.resolveClientEndpointParameters)(_config_0); const _config_2 = (0, config_resolver_1.resolveRegionConfig)(_config_1); const _config_3 = (0, middleware_endpoint_1.resolveEndpointConfig)(_config_2); const _config_4 = (0, middleware_retry_1.resolveRetryConfig)(_config_3); const _config_5 = (0, middleware_host_header_1.resolveHostHeaderConfig)(_config_4); const _config_6 = (0, middleware_user_agent_1.resolveUserAgentConfig)(_config_5); const _config_7 = (0, runtimeExtensions_1.resolveRuntimeExtensions)(_config_6, configuration?.extensions || []); super(_config_7); this.config = _config_7; this.middlewareStack.use((0, middleware_retry_1.getRetryPlugin)(this.config)); this.middlewareStack.use((0, middleware_content_length_1.getContentLengthPlugin)(this.config)); this.middlewareStack.use((0, middleware_host_header_1.getHostHeaderPlugin)(this.config)); this.middlewareStack.use((0, middleware_logger_1.getLoggerPlugin)(this.config)); this.middlewareStack.use((0, middleware_recursion_detection_1.getRecursionDetectionPlugin)(this.config)); this.middlewareStack.use((0, middleware_user_agent_1.getUserAgentPlugin)(this.config)); } destroy() { super.destroy(); } } exports.SSOClient = SSOClient; /***/ }), /***/ 18972: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GetRoleCredentialsCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const models_0_1 = __nccwpck_require__(66390); const Aws_restJson1_1 = __nccwpck_require__(98507); class GetRoleCredentialsCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, GetRoleCredentialsCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "SSOClient"; const commandName = "GetRoleCredentialsCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: models_0_1.GetRoleCredentialsRequestFilterSensitiveLog, outputFilterSensitiveLog: models_0_1.GetRoleCredentialsResponseFilterSensitiveLog, [types_1.SMITHY_CONTEXT_KEY]: { service: "SWBPortalService", operation: "GetRoleCredentials", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_restJson1_1.se_GetRoleCredentialsCommand)(input, context); } deserialize(output, context) { return (0, Aws_restJson1_1.de_GetRoleCredentialsCommand)(output, context); } } exports.GetRoleCredentialsCommand = GetRoleCredentialsCommand; /***/ }), /***/ 1513: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ListAccountRolesCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const models_0_1 = __nccwpck_require__(66390); const Aws_restJson1_1 = __nccwpck_require__(98507); class ListAccountRolesCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, ListAccountRolesCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "SSOClient"; const commandName = "ListAccountRolesCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: models_0_1.ListAccountRolesRequestFilterSensitiveLog, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "SWBPortalService", operation: "ListAccountRoles", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_restJson1_1.se_ListAccountRolesCommand)(input, context); } deserialize(output, context) { return (0, Aws_restJson1_1.de_ListAccountRolesCommand)(output, context); } } exports.ListAccountRolesCommand = ListAccountRolesCommand; /***/ }), /***/ 64296: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ListAccountsCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const models_0_1 = __nccwpck_require__(66390); const Aws_restJson1_1 = __nccwpck_require__(98507); class ListAccountsCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, ListAccountsCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "SSOClient"; const commandName = "ListAccountsCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: models_0_1.ListAccountsRequestFilterSensitiveLog, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "SWBPortalService", operation: "ListAccounts", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_restJson1_1.se_ListAccountsCommand)(input, context); } deserialize(output, context) { return (0, Aws_restJson1_1.de_ListAccountsCommand)(output, context); } } exports.ListAccountsCommand = ListAccountsCommand; /***/ }), /***/ 12586: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LogoutCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const models_0_1 = __nccwpck_require__(66390); const Aws_restJson1_1 = __nccwpck_require__(98507); class LogoutCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, LogoutCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "SSOClient"; const commandName = "LogoutCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: models_0_1.LogoutRequestFilterSensitiveLog, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "SWBPortalService", operation: "Logout", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_restJson1_1.se_LogoutCommand)(input, context); } deserialize(output, context) { return (0, Aws_restJson1_1.de_LogoutCommand)(output, context); } } exports.LogoutCommand = LogoutCommand; /***/ }), /***/ 65706: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(18972), exports); tslib_1.__exportStar(__nccwpck_require__(1513), exports); tslib_1.__exportStar(__nccwpck_require__(64296), exports); tslib_1.__exportStar(__nccwpck_require__(12586), exports); /***/ }), /***/ 34214: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveClientEndpointParameters = void 0; const resolveClientEndpointParameters = (options) => { return { ...options, useDualstackEndpoint: options.useDualstackEndpoint ?? false, useFipsEndpoint: options.useFipsEndpoint ?? false, defaultSigningName: "awsssoportal", }; }; exports.resolveClientEndpointParameters = resolveClientEndpointParameters; /***/ }), /***/ 30898: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.defaultEndpointResolver = void 0; const util_endpoints_1 = __nccwpck_require__(45473); const ruleset_1 = __nccwpck_require__(13341); const defaultEndpointResolver = (endpointParams, context = {}) => { return (0, util_endpoints_1.resolveEndpoint)(ruleset_1.ruleSet, { endpointParams: endpointParams, logger: context.logger, }); }; exports.defaultEndpointResolver = defaultEndpointResolver; /***/ }), /***/ 13341: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ruleSet = void 0; const u = "required", v = "fn", w = "argv", x = "ref"; const a = true, b = "isSet", c = "booleanEquals", d = "error", e = "endpoint", f = "tree", g = "PartitionResult", h = "getAttr", i = { [u]: false, "type": "String" }, j = { [u]: true, "default": false, "type": "Boolean" }, k = { [x]: "Endpoint" }, l = { [v]: c, [w]: [{ [x]: "UseFIPS" }, true] }, m = { [v]: c, [w]: [{ [x]: "UseDualStack" }, true] }, n = {}, o = { [v]: h, [w]: [{ [x]: g }, "supportsFIPS"] }, p = { [x]: g }, q = { [v]: c, [w]: [true, { [v]: h, [w]: [p, "supportsDualStack"] }] }, r = [l], s = [m], t = [{ [x]: "Region" }]; const _data = { version: "1.0", parameters: { Region: i, UseDualStack: j, UseFIPS: j, Endpoint: i }, rules: [{ conditions: [{ [v]: b, [w]: [k] }], rules: [{ conditions: r, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { conditions: s, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: k, properties: n, headers: n }, type: e }], type: f }, { conditions: [{ [v]: b, [w]: t }], rules: [{ conditions: [{ [v]: "aws.partition", [w]: t, assign: g }], rules: [{ conditions: [l, m], rules: [{ conditions: [{ [v]: c, [w]: [a, o] }, q], rules: [{ endpoint: { url: "https://portal.sso-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f }, { conditions: r, rules: [{ conditions: [{ [v]: c, [w]: [o, a] }], rules: [{ conditions: [{ [v]: "stringEquals", [w]: [{ [v]: h, [w]: [p, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://portal.sso.{Region}.amazonaws.com", properties: n, headers: n }, type: e }, { endpoint: { url: "https://portal.sso-fips.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f }, { conditions: s, rules: [{ conditions: [q], rules: [{ endpoint: { url: "https://portal.sso.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f }, { endpoint: { url: "https://portal.sso.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }] }; exports.ruleSet = _data; /***/ }), /***/ 82666: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SSOServiceException = void 0; const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(71057), exports); tslib_1.__exportStar(__nccwpck_require__(69838), exports); tslib_1.__exportStar(__nccwpck_require__(65706), exports); tslib_1.__exportStar(__nccwpck_require__(36773), exports); tslib_1.__exportStar(__nccwpck_require__(14952), exports); __nccwpck_require__(13350); var SSOServiceException_1 = __nccwpck_require__(81517); Object.defineProperty(exports, "SSOServiceException", ({ enumerable: true, get: function () { return SSOServiceException_1.SSOServiceException; } })); /***/ }), /***/ 81517: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SSOServiceException = exports.__ServiceException = void 0; const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "__ServiceException", ({ enumerable: true, get: function () { return smithy_client_1.ServiceException; } })); class SSOServiceException extends smithy_client_1.ServiceException { constructor(options) { super(options); Object.setPrototypeOf(this, SSOServiceException.prototype); } } exports.SSOServiceException = SSOServiceException; /***/ }), /***/ 14952: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(66390), exports); /***/ }), /***/ 66390: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LogoutRequestFilterSensitiveLog = exports.ListAccountsRequestFilterSensitiveLog = exports.ListAccountRolesRequestFilterSensitiveLog = exports.GetRoleCredentialsResponseFilterSensitiveLog = exports.RoleCredentialsFilterSensitiveLog = exports.GetRoleCredentialsRequestFilterSensitiveLog = exports.UnauthorizedException = exports.TooManyRequestsException = exports.ResourceNotFoundException = exports.InvalidRequestException = void 0; const smithy_client_1 = __nccwpck_require__(63570); const SSOServiceException_1 = __nccwpck_require__(81517); class InvalidRequestException extends SSOServiceException_1.SSOServiceException { constructor(opts) { super({ name: "InvalidRequestException", $fault: "client", ...opts, }); this.name = "InvalidRequestException"; this.$fault = "client"; Object.setPrototypeOf(this, InvalidRequestException.prototype); } } exports.InvalidRequestException = InvalidRequestException; class ResourceNotFoundException extends SSOServiceException_1.SSOServiceException { constructor(opts) { super({ name: "ResourceNotFoundException", $fault: "client", ...opts, }); this.name = "ResourceNotFoundException"; this.$fault = "client"; Object.setPrototypeOf(this, ResourceNotFoundException.prototype); } } exports.ResourceNotFoundException = ResourceNotFoundException; class TooManyRequestsException extends SSOServiceException_1.SSOServiceException { constructor(opts) { super({ name: "TooManyRequestsException", $fault: "client", ...opts, }); this.name = "TooManyRequestsException"; this.$fault = "client"; Object.setPrototypeOf(this, TooManyRequestsException.prototype); } } exports.TooManyRequestsException = TooManyRequestsException; class UnauthorizedException extends SSOServiceException_1.SSOServiceException { constructor(opts) { super({ name: "UnauthorizedException", $fault: "client", ...opts, }); this.name = "UnauthorizedException"; this.$fault = "client"; Object.setPrototypeOf(this, UnauthorizedException.prototype); } } exports.UnauthorizedException = UnauthorizedException; const GetRoleCredentialsRequestFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.accessToken && { accessToken: smithy_client_1.SENSITIVE_STRING }), }); exports.GetRoleCredentialsRequestFilterSensitiveLog = GetRoleCredentialsRequestFilterSensitiveLog; const RoleCredentialsFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.secretAccessKey && { secretAccessKey: smithy_client_1.SENSITIVE_STRING }), ...(obj.sessionToken && { sessionToken: smithy_client_1.SENSITIVE_STRING }), }); exports.RoleCredentialsFilterSensitiveLog = RoleCredentialsFilterSensitiveLog; const GetRoleCredentialsResponseFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.roleCredentials && { roleCredentials: (0, exports.RoleCredentialsFilterSensitiveLog)(obj.roleCredentials) }), }); exports.GetRoleCredentialsResponseFilterSensitiveLog = GetRoleCredentialsResponseFilterSensitiveLog; const ListAccountRolesRequestFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.accessToken && { accessToken: smithy_client_1.SENSITIVE_STRING }), }); exports.ListAccountRolesRequestFilterSensitiveLog = ListAccountRolesRequestFilterSensitiveLog; const ListAccountsRequestFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.accessToken && { accessToken: smithy_client_1.SENSITIVE_STRING }), }); exports.ListAccountsRequestFilterSensitiveLog = ListAccountsRequestFilterSensitiveLog; const LogoutRequestFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.accessToken && { accessToken: smithy_client_1.SENSITIVE_STRING }), }); exports.LogoutRequestFilterSensitiveLog = LogoutRequestFilterSensitiveLog; /***/ }), /***/ 80849: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 88460: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.paginateListAccountRoles = void 0; const ListAccountRolesCommand_1 = __nccwpck_require__(1513); const SSOClient_1 = __nccwpck_require__(71057); const makePagedClientRequest = async (client, input, ...args) => { return await client.send(new ListAccountRolesCommand_1.ListAccountRolesCommand(input), ...args); }; async function* paginateListAccountRoles(config, input, ...additionalArguments) { let token = config.startingToken || undefined; let hasNext = true; let page; while (hasNext) { input.nextToken = token; input["maxResults"] = config.pageSize; if (config.client instanceof SSOClient_1.SSOClient) { page = await makePagedClientRequest(config.client, input, ...additionalArguments); } else { throw new Error("Invalid client, expected SSO | SSOClient"); } yield page; const prevToken = token; token = page.nextToken; hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); } return undefined; } exports.paginateListAccountRoles = paginateListAccountRoles; /***/ }), /***/ 50938: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.paginateListAccounts = void 0; const ListAccountsCommand_1 = __nccwpck_require__(64296); const SSOClient_1 = __nccwpck_require__(71057); const makePagedClientRequest = async (client, input, ...args) => { return await client.send(new ListAccountsCommand_1.ListAccountsCommand(input), ...args); }; async function* paginateListAccounts(config, input, ...additionalArguments) { let token = config.startingToken || undefined; let hasNext = true; let page; while (hasNext) { input.nextToken = token; input["maxResults"] = config.pageSize; if (config.client instanceof SSOClient_1.SSOClient) { page = await makePagedClientRequest(config.client, input, ...additionalArguments); } else { throw new Error("Invalid client, expected SSO | SSOClient"); } yield page; const prevToken = token; token = page.nextToken; hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); } return undefined; } exports.paginateListAccounts = paginateListAccounts; /***/ }), /***/ 36773: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(80849), exports); tslib_1.__exportStar(__nccwpck_require__(88460), exports); tslib_1.__exportStar(__nccwpck_require__(50938), exports); /***/ }), /***/ 98507: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.de_LogoutCommand = exports.de_ListAccountsCommand = exports.de_ListAccountRolesCommand = exports.de_GetRoleCredentialsCommand = exports.se_LogoutCommand = exports.se_ListAccountsCommand = exports.se_ListAccountRolesCommand = exports.se_GetRoleCredentialsCommand = void 0; const protocol_http_1 = __nccwpck_require__(64418); const smithy_client_1 = __nccwpck_require__(63570); const models_0_1 = __nccwpck_require__(66390); const SSOServiceException_1 = __nccwpck_require__(81517); const se_GetRoleCredentialsCommand = async (input, context) => { const { hostname, protocol = "https", port, path: basePath } = await context.endpoint(); const headers = (0, smithy_client_1.map)({}, isSerializableHeaderValue, { "x-amz-sso_bearer_token": input.accessToken, }); const resolvedPath = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + "/federation/credentials"; const query = (0, smithy_client_1.map)({ role_name: [, (0, smithy_client_1.expectNonNull)(input.roleName, `roleName`)], account_id: [, (0, smithy_client_1.expectNonNull)(input.accountId, `accountId`)], }); let body; return new protocol_http_1.HttpRequest({ protocol, hostname, port, method: "GET", headers, path: resolvedPath, query, body, }); }; exports.se_GetRoleCredentialsCommand = se_GetRoleCredentialsCommand; const se_ListAccountRolesCommand = async (input, context) => { const { hostname, protocol = "https", port, path: basePath } = await context.endpoint(); const headers = (0, smithy_client_1.map)({}, isSerializableHeaderValue, { "x-amz-sso_bearer_token": input.accessToken, }); const resolvedPath = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + "/assignment/roles"; const query = (0, smithy_client_1.map)({ next_token: [, input.nextToken], max_result: [() => input.maxResults !== void 0, () => input.maxResults.toString()], account_id: [, (0, smithy_client_1.expectNonNull)(input.accountId, `accountId`)], }); let body; return new protocol_http_1.HttpRequest({ protocol, hostname, port, method: "GET", headers, path: resolvedPath, query, body, }); }; exports.se_ListAccountRolesCommand = se_ListAccountRolesCommand; const se_ListAccountsCommand = async (input, context) => { const { hostname, protocol = "https", port, path: basePath } = await context.endpoint(); const headers = (0, smithy_client_1.map)({}, isSerializableHeaderValue, { "x-amz-sso_bearer_token": input.accessToken, }); const resolvedPath = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + "/assignment/accounts"; const query = (0, smithy_client_1.map)({ next_token: [, input.nextToken], max_result: [() => input.maxResults !== void 0, () => input.maxResults.toString()], }); let body; return new protocol_http_1.HttpRequest({ protocol, hostname, port, method: "GET", headers, path: resolvedPath, query, body, }); }; exports.se_ListAccountsCommand = se_ListAccountsCommand; const se_LogoutCommand = async (input, context) => { const { hostname, protocol = "https", port, path: basePath } = await context.endpoint(); const headers = (0, smithy_client_1.map)({}, isSerializableHeaderValue, { "x-amz-sso_bearer_token": input.accessToken, }); const resolvedPath = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + "/logout"; let body; return new protocol_http_1.HttpRequest({ protocol, hostname, port, method: "POST", headers, path: resolvedPath, body, }); }; exports.se_LogoutCommand = se_LogoutCommand; const de_GetRoleCredentialsCommand = async (output, context) => { if (output.statusCode !== 200 && output.statusCode >= 300) { return de_GetRoleCredentialsCommandError(output, context); } const contents = (0, smithy_client_1.map)({ $metadata: deserializeMetadata(output), }); const data = (0, smithy_client_1.expectNonNull)((0, smithy_client_1.expectObject)(await parseBody(output.body, context)), "body"); const doc = (0, smithy_client_1.take)(data, { roleCredentials: smithy_client_1._json, }); Object.assign(contents, doc); return contents; }; exports.de_GetRoleCredentialsCommand = de_GetRoleCredentialsCommand; const de_GetRoleCredentialsCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "InvalidRequestException": case "com.amazonaws.sso#InvalidRequestException": throw await de_InvalidRequestExceptionRes(parsedOutput, context); case "ResourceNotFoundException": case "com.amazonaws.sso#ResourceNotFoundException": throw await de_ResourceNotFoundExceptionRes(parsedOutput, context); case "TooManyRequestsException": case "com.amazonaws.sso#TooManyRequestsException": throw await de_TooManyRequestsExceptionRes(parsedOutput, context); case "UnauthorizedException": case "com.amazonaws.sso#UnauthorizedException": throw await de_UnauthorizedExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_ListAccountRolesCommand = async (output, context) => { if (output.statusCode !== 200 && output.statusCode >= 300) { return de_ListAccountRolesCommandError(output, context); } const contents = (0, smithy_client_1.map)({ $metadata: deserializeMetadata(output), }); const data = (0, smithy_client_1.expectNonNull)((0, smithy_client_1.expectObject)(await parseBody(output.body, context)), "body"); const doc = (0, smithy_client_1.take)(data, { nextToken: smithy_client_1.expectString, roleList: smithy_client_1._json, }); Object.assign(contents, doc); return contents; }; exports.de_ListAccountRolesCommand = de_ListAccountRolesCommand; const de_ListAccountRolesCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "InvalidRequestException": case "com.amazonaws.sso#InvalidRequestException": throw await de_InvalidRequestExceptionRes(parsedOutput, context); case "ResourceNotFoundException": case "com.amazonaws.sso#ResourceNotFoundException": throw await de_ResourceNotFoundExceptionRes(parsedOutput, context); case "TooManyRequestsException": case "com.amazonaws.sso#TooManyRequestsException": throw await de_TooManyRequestsExceptionRes(parsedOutput, context); case "UnauthorizedException": case "com.amazonaws.sso#UnauthorizedException": throw await de_UnauthorizedExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_ListAccountsCommand = async (output, context) => { if (output.statusCode !== 200 && output.statusCode >= 300) { return de_ListAccountsCommandError(output, context); } const contents = (0, smithy_client_1.map)({ $metadata: deserializeMetadata(output), }); const data = (0, smithy_client_1.expectNonNull)((0, smithy_client_1.expectObject)(await parseBody(output.body, context)), "body"); const doc = (0, smithy_client_1.take)(data, { accountList: smithy_client_1._json, nextToken: smithy_client_1.expectString, }); Object.assign(contents, doc); return contents; }; exports.de_ListAccountsCommand = de_ListAccountsCommand; const de_ListAccountsCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "InvalidRequestException": case "com.amazonaws.sso#InvalidRequestException": throw await de_InvalidRequestExceptionRes(parsedOutput, context); case "ResourceNotFoundException": case "com.amazonaws.sso#ResourceNotFoundException": throw await de_ResourceNotFoundExceptionRes(parsedOutput, context); case "TooManyRequestsException": case "com.amazonaws.sso#TooManyRequestsException": throw await de_TooManyRequestsExceptionRes(parsedOutput, context); case "UnauthorizedException": case "com.amazonaws.sso#UnauthorizedException": throw await de_UnauthorizedExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const de_LogoutCommand = async (output, context) => { if (output.statusCode !== 200 && output.statusCode >= 300) { return de_LogoutCommandError(output, context); } const contents = (0, smithy_client_1.map)({ $metadata: deserializeMetadata(output), }); await (0, smithy_client_1.collectBody)(output.body, context); return contents; }; exports.de_LogoutCommand = de_LogoutCommand; const de_LogoutCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "InvalidRequestException": case "com.amazonaws.sso#InvalidRequestException": throw await de_InvalidRequestExceptionRes(parsedOutput, context); case "TooManyRequestsException": case "com.amazonaws.sso#TooManyRequestsException": throw await de_TooManyRequestsExceptionRes(parsedOutput, context); case "UnauthorizedException": case "com.amazonaws.sso#UnauthorizedException": throw await de_UnauthorizedExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; const throwDefaultError = (0, smithy_client_1.withBaseException)(SSOServiceException_1.SSOServiceException); const de_InvalidRequestExceptionRes = async (parsedOutput, context) => { const contents = (0, smithy_client_1.map)({}); const data = parsedOutput.body; const doc = (0, smithy_client_1.take)(data, { message: smithy_client_1.expectString, }); Object.assign(contents, doc); const exception = new models_0_1.InvalidRequestException({ $metadata: deserializeMetadata(parsedOutput), ...contents, }); return (0, smithy_client_1.decorateServiceException)(exception, parsedOutput.body); }; const de_ResourceNotFoundExceptionRes = async (parsedOutput, context) => { const contents = (0, smithy_client_1.map)({}); const data = parsedOutput.body; const doc = (0, smithy_client_1.take)(data, { message: smithy_client_1.expectString, }); Object.assign(contents, doc); const exception = new models_0_1.ResourceNotFoundException({ $metadata: deserializeMetadata(parsedOutput), ...contents, }); return (0, smithy_client_1.decorateServiceException)(exception, parsedOutput.body); }; const de_TooManyRequestsExceptionRes = async (parsedOutput, context) => { const contents = (0, smithy_client_1.map)({}); const data = parsedOutput.body; const doc = (0, smithy_client_1.take)(data, { message: smithy_client_1.expectString, }); Object.assign(contents, doc); const exception = new models_0_1.TooManyRequestsException({ $metadata: deserializeMetadata(parsedOutput), ...contents, }); return (0, smithy_client_1.decorateServiceException)(exception, parsedOutput.body); }; const de_UnauthorizedExceptionRes = async (parsedOutput, context) => { const contents = (0, smithy_client_1.map)({}); const data = parsedOutput.body; const doc = (0, smithy_client_1.take)(data, { message: smithy_client_1.expectString, }); Object.assign(contents, doc); const exception = new models_0_1.UnauthorizedException({ $metadata: deserializeMetadata(parsedOutput), ...contents, }); return (0, smithy_client_1.decorateServiceException)(exception, parsedOutput.body); }; const deserializeMetadata = (output) => ({ httpStatusCode: output.statusCode, requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], extendedRequestId: output.headers["x-amz-id-2"], cfId: output.headers["x-amz-cf-id"], }); const collectBodyString = (streamBody, context) => (0, smithy_client_1.collectBody)(streamBody, context).then((body) => context.utf8Encoder(body)); const isSerializableHeaderValue = (value) => value !== undefined && value !== null && value !== "" && (!Object.getOwnPropertyNames(value).includes("length") || value.length != 0) && (!Object.getOwnPropertyNames(value).includes("size") || value.size != 0); const parseBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { if (encoded.length) { return JSON.parse(encoded); } return {}; }); const parseErrorBody = async (errorBody, context) => { const value = await parseBody(errorBody, context); value.message = value.message ?? value.Message; return value; }; const loadRestJsonErrorCode = (output, data) => { const findKey = (object, key) => Object.keys(object).find((k) => k.toLowerCase() === key.toLowerCase()); const sanitizeErrorCode = (rawValue) => { let cleanValue = rawValue; if (typeof cleanValue === "number") { cleanValue = cleanValue.toString(); } if (cleanValue.indexOf(",") >= 0) { cleanValue = cleanValue.split(",")[0]; } if (cleanValue.indexOf(":") >= 0) { cleanValue = cleanValue.split(":")[0]; } if (cleanValue.indexOf("#") >= 0) { cleanValue = cleanValue.split("#")[1]; } return cleanValue; }; const headerKey = findKey(output.headers, "x-amzn-errortype"); if (headerKey !== undefined) { return sanitizeErrorCode(output.headers[headerKey]); } if (data.code !== undefined) { return sanitizeErrorCode(data.code); } if (data["__type"] !== undefined) { return sanitizeErrorCode(data["__type"]); } }; /***/ }), /***/ 19756: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getRuntimeConfig = void 0; const tslib_1 = __nccwpck_require__(4351); const package_json_1 = tslib_1.__importDefault(__nccwpck_require__(91092)); const core_1 = __nccwpck_require__(59963); const util_user_agent_node_1 = __nccwpck_require__(98095); const config_resolver_1 = __nccwpck_require__(53098); const hash_node_1 = __nccwpck_require__(3081); const middleware_retry_1 = __nccwpck_require__(96039); const node_config_provider_1 = __nccwpck_require__(33461); const node_http_handler_1 = __nccwpck_require__(20258); const util_body_length_node_1 = __nccwpck_require__(68075); const util_retry_1 = __nccwpck_require__(84902); const runtimeConfig_shared_1 = __nccwpck_require__(44809); const smithy_client_1 = __nccwpck_require__(63570); const util_defaults_mode_node_1 = __nccwpck_require__(72429); const smithy_client_2 = __nccwpck_require__(63570); const getRuntimeConfig = (config) => { (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version); const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config); const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode); const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config); (0, core_1.emitWarningIfUnsupportedVersion)(process.version); return { ...clientSharedValues, ...config, runtime: "node", defaultsMode, bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, defaultUserAgentProvider: config?.defaultUserAgentProvider ?? (0, util_user_agent_node_1.defaultUserAgent)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS), region: config?.region ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS), requestHandler: config?.requestHandler ?? new node_http_handler_1.NodeHttpHandler(defaultConfigProvider), retryMode: config?.retryMode ?? (0, node_config_provider_1.loadConfig)({ ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS, default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE, }), sha256: config?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"), streamCollector: config?.streamCollector ?? node_http_handler_1.streamCollector, useDualstackEndpoint: config?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS), useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS), }; }; exports.getRuntimeConfig = getRuntimeConfig; /***/ }), /***/ 44809: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getRuntimeConfig = void 0; const smithy_client_1 = __nccwpck_require__(63570); const url_parser_1 = __nccwpck_require__(14681); const util_base64_1 = __nccwpck_require__(75600); const util_utf8_1 = __nccwpck_require__(41895); const endpointResolver_1 = __nccwpck_require__(30898); const getRuntimeConfig = (config) => { return { apiVersion: "2019-06-10", base64Decoder: config?.base64Decoder ?? util_base64_1.fromBase64, base64Encoder: config?.base64Encoder ?? util_base64_1.toBase64, disableHostPrefix: config?.disableHostPrefix ?? false, endpointProvider: config?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver, extensions: config?.extensions ?? [], logger: config?.logger ?? new smithy_client_1.NoOpLogger(), serviceId: config?.serviceId ?? "SSO", urlParser: config?.urlParser ?? url_parser_1.parseUrl, utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, }; }; exports.getRuntimeConfig = getRuntimeConfig; /***/ }), /***/ 63398: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveRuntimeExtensions = void 0; const region_config_resolver_1 = __nccwpck_require__(18156); const protocol_http_1 = __nccwpck_require__(64418); const smithy_client_1 = __nccwpck_require__(63570); const asPartial = (t) => t; const resolveRuntimeExtensions = (runtimeConfig, extensions) => { const extensionConfiguration = { ...asPartial((0, region_config_resolver_1.getAwsRegionExtensionConfiguration)(runtimeConfig)), ...asPartial((0, smithy_client_1.getDefaultExtensionConfiguration)(runtimeConfig)), ...asPartial((0, protocol_http_1.getHttpHandlerExtensionConfiguration)(runtimeConfig)), }; extensions.forEach((extension) => extension.configure(extensionConfiguration)); return { ...runtimeConfig, ...(0, region_config_resolver_1.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), ...(0, smithy_client_1.resolveDefaultRuntimeConfig)(extensionConfiguration), ...(0, protocol_http_1.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), }; }; exports.resolveRuntimeExtensions = resolveRuntimeExtensions; /***/ }), /***/ 32605: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.STS = void 0; const smithy_client_1 = __nccwpck_require__(63570); const AssumeRoleCommand_1 = __nccwpck_require__(59802); const AssumeRoleWithSAMLCommand_1 = __nccwpck_require__(72865); const AssumeRoleWithWebIdentityCommand_1 = __nccwpck_require__(37451); const DecodeAuthorizationMessageCommand_1 = __nccwpck_require__(74150); const GetAccessKeyInfoCommand_1 = __nccwpck_require__(49804); const GetCallerIdentityCommand_1 = __nccwpck_require__(24278); const GetFederationTokenCommand_1 = __nccwpck_require__(57552); const GetSessionTokenCommand_1 = __nccwpck_require__(43285); const STSClient_1 = __nccwpck_require__(64195); const commands = { AssumeRoleCommand: AssumeRoleCommand_1.AssumeRoleCommand, AssumeRoleWithSAMLCommand: AssumeRoleWithSAMLCommand_1.AssumeRoleWithSAMLCommand, AssumeRoleWithWebIdentityCommand: AssumeRoleWithWebIdentityCommand_1.AssumeRoleWithWebIdentityCommand, DecodeAuthorizationMessageCommand: DecodeAuthorizationMessageCommand_1.DecodeAuthorizationMessageCommand, GetAccessKeyInfoCommand: GetAccessKeyInfoCommand_1.GetAccessKeyInfoCommand, GetCallerIdentityCommand: GetCallerIdentityCommand_1.GetCallerIdentityCommand, GetFederationTokenCommand: GetFederationTokenCommand_1.GetFederationTokenCommand, GetSessionTokenCommand: GetSessionTokenCommand_1.GetSessionTokenCommand, }; class STS extends STSClient_1.STSClient { } exports.STS = STS; (0, smithy_client_1.createAggregatedClient)(commands, STS); /***/ }), /***/ 64195: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.STSClient = exports.__Client = void 0; const middleware_host_header_1 = __nccwpck_require__(22545); const middleware_logger_1 = __nccwpck_require__(20014); const middleware_recursion_detection_1 = __nccwpck_require__(85525); const middleware_sdk_sts_1 = __nccwpck_require__(55959); const middleware_user_agent_1 = __nccwpck_require__(64688); const config_resolver_1 = __nccwpck_require__(53098); const middleware_content_length_1 = __nccwpck_require__(82800); const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_retry_1 = __nccwpck_require__(96039); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "__Client", ({ enumerable: true, get: function () { return smithy_client_1.Client; } })); const EndpointParameters_1 = __nccwpck_require__(20510); const runtimeConfig_1 = __nccwpck_require__(83405); const runtimeExtensions_1 = __nccwpck_require__(32053); class STSClient extends smithy_client_1.Client { constructor(...[configuration]) { const _config_0 = (0, runtimeConfig_1.getRuntimeConfig)(configuration || {}); const _config_1 = (0, EndpointParameters_1.resolveClientEndpointParameters)(_config_0); const _config_2 = (0, config_resolver_1.resolveRegionConfig)(_config_1); const _config_3 = (0, middleware_endpoint_1.resolveEndpointConfig)(_config_2); const _config_4 = (0, middleware_retry_1.resolveRetryConfig)(_config_3); const _config_5 = (0, middleware_host_header_1.resolveHostHeaderConfig)(_config_4); const _config_6 = (0, middleware_sdk_sts_1.resolveStsAuthConfig)(_config_5, { stsClientCtor: STSClient }); const _config_7 = (0, middleware_user_agent_1.resolveUserAgentConfig)(_config_6); const _config_8 = (0, runtimeExtensions_1.resolveRuntimeExtensions)(_config_7, configuration?.extensions || []); super(_config_8); this.config = _config_8; this.middlewareStack.use((0, middleware_retry_1.getRetryPlugin)(this.config)); this.middlewareStack.use((0, middleware_content_length_1.getContentLengthPlugin)(this.config)); this.middlewareStack.use((0, middleware_host_header_1.getHostHeaderPlugin)(this.config)); this.middlewareStack.use((0, middleware_logger_1.getLoggerPlugin)(this.config)); this.middlewareStack.use((0, middleware_recursion_detection_1.getRecursionDetectionPlugin)(this.config)); this.middlewareStack.use((0, middleware_user_agent_1.getUserAgentPlugin)(this.config)); } destroy() { super.destroy(); } } exports.STSClient = STSClient; /***/ }), /***/ 59802: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AssumeRoleCommand = exports.$Command = void 0; const middleware_signing_1 = __nccwpck_require__(14935); const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const models_0_1 = __nccwpck_require__(21780); const Aws_query_1 = __nccwpck_require__(10740); class AssumeRoleCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" }, UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, AssumeRoleCommand.getEndpointParameterInstructions())); this.middlewareStack.use((0, middleware_signing_1.getAwsAuthPlugin)(configuration)); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "STSClient"; const commandName = "AssumeRoleCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: models_0_1.AssumeRoleResponseFilterSensitiveLog, [types_1.SMITHY_CONTEXT_KEY]: { service: "AWSSecurityTokenServiceV20110615", operation: "AssumeRole", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_query_1.se_AssumeRoleCommand)(input, context); } deserialize(output, context) { return (0, Aws_query_1.de_AssumeRoleCommand)(output, context); } } exports.AssumeRoleCommand = AssumeRoleCommand; /***/ }), /***/ 72865: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AssumeRoleWithSAMLCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const models_0_1 = __nccwpck_require__(21780); const Aws_query_1 = __nccwpck_require__(10740); class AssumeRoleWithSAMLCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" }, UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, AssumeRoleWithSAMLCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "STSClient"; const commandName = "AssumeRoleWithSAMLCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: models_0_1.AssumeRoleWithSAMLRequestFilterSensitiveLog, outputFilterSensitiveLog: models_0_1.AssumeRoleWithSAMLResponseFilterSensitiveLog, [types_1.SMITHY_CONTEXT_KEY]: { service: "AWSSecurityTokenServiceV20110615", operation: "AssumeRoleWithSAML", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_query_1.se_AssumeRoleWithSAMLCommand)(input, context); } deserialize(output, context) { return (0, Aws_query_1.de_AssumeRoleWithSAMLCommand)(output, context); } } exports.AssumeRoleWithSAMLCommand = AssumeRoleWithSAMLCommand; /***/ }), /***/ 37451: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AssumeRoleWithWebIdentityCommand = exports.$Command = void 0; const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const models_0_1 = __nccwpck_require__(21780); const Aws_query_1 = __nccwpck_require__(10740); class AssumeRoleWithWebIdentityCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" }, UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, AssumeRoleWithWebIdentityCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "STSClient"; const commandName = "AssumeRoleWithWebIdentityCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: models_0_1.AssumeRoleWithWebIdentityRequestFilterSensitiveLog, outputFilterSensitiveLog: models_0_1.AssumeRoleWithWebIdentityResponseFilterSensitiveLog, [types_1.SMITHY_CONTEXT_KEY]: { service: "AWSSecurityTokenServiceV20110615", operation: "AssumeRoleWithWebIdentity", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_query_1.se_AssumeRoleWithWebIdentityCommand)(input, context); } deserialize(output, context) { return (0, Aws_query_1.de_AssumeRoleWithWebIdentityCommand)(output, context); } } exports.AssumeRoleWithWebIdentityCommand = AssumeRoleWithWebIdentityCommand; /***/ }), /***/ 74150: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DecodeAuthorizationMessageCommand = exports.$Command = void 0; const middleware_signing_1 = __nccwpck_require__(14935); const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_query_1 = __nccwpck_require__(10740); class DecodeAuthorizationMessageCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" }, UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, DecodeAuthorizationMessageCommand.getEndpointParameterInstructions())); this.middlewareStack.use((0, middleware_signing_1.getAwsAuthPlugin)(configuration)); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "STSClient"; const commandName = "DecodeAuthorizationMessageCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "AWSSecurityTokenServiceV20110615", operation: "DecodeAuthorizationMessage", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_query_1.se_DecodeAuthorizationMessageCommand)(input, context); } deserialize(output, context) { return (0, Aws_query_1.de_DecodeAuthorizationMessageCommand)(output, context); } } exports.DecodeAuthorizationMessageCommand = DecodeAuthorizationMessageCommand; /***/ }), /***/ 49804: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GetAccessKeyInfoCommand = exports.$Command = void 0; const middleware_signing_1 = __nccwpck_require__(14935); const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_query_1 = __nccwpck_require__(10740); class GetAccessKeyInfoCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" }, UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, GetAccessKeyInfoCommand.getEndpointParameterInstructions())); this.middlewareStack.use((0, middleware_signing_1.getAwsAuthPlugin)(configuration)); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "STSClient"; const commandName = "GetAccessKeyInfoCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "AWSSecurityTokenServiceV20110615", operation: "GetAccessKeyInfo", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_query_1.se_GetAccessKeyInfoCommand)(input, context); } deserialize(output, context) { return (0, Aws_query_1.de_GetAccessKeyInfoCommand)(output, context); } } exports.GetAccessKeyInfoCommand = GetAccessKeyInfoCommand; /***/ }), /***/ 24278: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GetCallerIdentityCommand = exports.$Command = void 0; const middleware_signing_1 = __nccwpck_require__(14935); const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const Aws_query_1 = __nccwpck_require__(10740); class GetCallerIdentityCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" }, UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, GetCallerIdentityCommand.getEndpointParameterInstructions())); this.middlewareStack.use((0, middleware_signing_1.getAwsAuthPlugin)(configuration)); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "STSClient"; const commandName = "GetCallerIdentityCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "AWSSecurityTokenServiceV20110615", operation: "GetCallerIdentity", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_query_1.se_GetCallerIdentityCommand)(input, context); } deserialize(output, context) { return (0, Aws_query_1.de_GetCallerIdentityCommand)(output, context); } } exports.GetCallerIdentityCommand = GetCallerIdentityCommand; /***/ }), /***/ 57552: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GetFederationTokenCommand = exports.$Command = void 0; const middleware_signing_1 = __nccwpck_require__(14935); const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const models_0_1 = __nccwpck_require__(21780); const Aws_query_1 = __nccwpck_require__(10740); class GetFederationTokenCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" }, UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, GetFederationTokenCommand.getEndpointParameterInstructions())); this.middlewareStack.use((0, middleware_signing_1.getAwsAuthPlugin)(configuration)); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "STSClient"; const commandName = "GetFederationTokenCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: models_0_1.GetFederationTokenResponseFilterSensitiveLog, [types_1.SMITHY_CONTEXT_KEY]: { service: "AWSSecurityTokenServiceV20110615", operation: "GetFederationToken", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_query_1.se_GetFederationTokenCommand)(input, context); } deserialize(output, context) { return (0, Aws_query_1.de_GetFederationTokenCommand)(output, context); } } exports.GetFederationTokenCommand = GetFederationTokenCommand; /***/ }), /***/ 43285: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GetSessionTokenCommand = exports.$Command = void 0; const middleware_signing_1 = __nccwpck_require__(14935); const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "$Command", ({ enumerable: true, get: function () { return smithy_client_1.Command; } })); const types_1 = __nccwpck_require__(55756); const models_0_1 = __nccwpck_require__(21780); const Aws_query_1 = __nccwpck_require__(10740); class GetSessionTokenCommand extends smithy_client_1.Command { static getEndpointParameterInstructions() { return { UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" }, UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } constructor(input) { super(); this.input = input; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_1.getEndpointPlugin)(configuration, GetSessionTokenCommand.getEndpointParameterInstructions())); this.middlewareStack.use((0, middleware_signing_1.getAwsAuthPlugin)(configuration)); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "STSClient"; const commandName = "GetSessionTokenCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: models_0_1.GetSessionTokenResponseFilterSensitiveLog, [types_1.SMITHY_CONTEXT_KEY]: { service: "AWSSecurityTokenServiceV20110615", operation: "GetSessionToken", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return (0, Aws_query_1.se_GetSessionTokenCommand)(input, context); } deserialize(output, context) { return (0, Aws_query_1.de_GetSessionTokenCommand)(output, context); } } exports.GetSessionTokenCommand = GetSessionTokenCommand; /***/ }), /***/ 55716: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(59802), exports); tslib_1.__exportStar(__nccwpck_require__(72865), exports); tslib_1.__exportStar(__nccwpck_require__(37451), exports); tslib_1.__exportStar(__nccwpck_require__(74150), exports); tslib_1.__exportStar(__nccwpck_require__(49804), exports); tslib_1.__exportStar(__nccwpck_require__(24278), exports); tslib_1.__exportStar(__nccwpck_require__(57552), exports); tslib_1.__exportStar(__nccwpck_require__(43285), exports); /***/ }), /***/ 88028: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.decorateDefaultCredentialProvider = exports.getDefaultRoleAssumerWithWebIdentity = exports.getDefaultRoleAssumer = void 0; const defaultStsRoleAssumers_1 = __nccwpck_require__(90048); const STSClient_1 = __nccwpck_require__(64195); const getCustomizableStsClientCtor = (baseCtor, customizations) => { if (!customizations) return baseCtor; else return class CustomizableSTSClient extends baseCtor { constructor(config) { super(config); for (const customization of customizations) { this.middlewareStack.use(customization); } } }; }; const getDefaultRoleAssumer = (stsOptions = {}, stsPlugins) => (0, defaultStsRoleAssumers_1.getDefaultRoleAssumer)(stsOptions, getCustomizableStsClientCtor(STSClient_1.STSClient, stsPlugins)); exports.getDefaultRoleAssumer = getDefaultRoleAssumer; const getDefaultRoleAssumerWithWebIdentity = (stsOptions = {}, stsPlugins) => (0, defaultStsRoleAssumers_1.getDefaultRoleAssumerWithWebIdentity)(stsOptions, getCustomizableStsClientCtor(STSClient_1.STSClient, stsPlugins)); exports.getDefaultRoleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity; const decorateDefaultCredentialProvider = (provider) => (input) => provider({ roleAssumer: (0, exports.getDefaultRoleAssumer)(input), roleAssumerWithWebIdentity: (0, exports.getDefaultRoleAssumerWithWebIdentity)(input), ...input, }); exports.decorateDefaultCredentialProvider = decorateDefaultCredentialProvider; /***/ }), /***/ 90048: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.decorateDefaultCredentialProvider = exports.getDefaultRoleAssumerWithWebIdentity = exports.getDefaultRoleAssumer = void 0; const AssumeRoleCommand_1 = __nccwpck_require__(59802); const AssumeRoleWithWebIdentityCommand_1 = __nccwpck_require__(37451); const ASSUME_ROLE_DEFAULT_REGION = "us-east-1"; const decorateDefaultRegion = (region) => { if (typeof region !== "function") { return region === undefined ? ASSUME_ROLE_DEFAULT_REGION : region; } return async () => { try { return await region(); } catch (e) { return ASSUME_ROLE_DEFAULT_REGION; } }; }; const getDefaultRoleAssumer = (stsOptions, stsClientCtor) => { let stsClient; let closureSourceCreds; return async (sourceCreds, params) => { closureSourceCreds = sourceCreds; if (!stsClient) { const { logger, region, requestHandler } = stsOptions; stsClient = new stsClientCtor({ logger, credentialDefaultProvider: () => async () => closureSourceCreds, region: decorateDefaultRegion(region || stsOptions.region), ...(requestHandler ? { requestHandler } : {}), }); } const { Credentials } = await stsClient.send(new AssumeRoleCommand_1.AssumeRoleCommand(params)); if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) { throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`); } return { accessKeyId: Credentials.AccessKeyId, secretAccessKey: Credentials.SecretAccessKey, sessionToken: Credentials.SessionToken, expiration: Credentials.Expiration, }; }; }; exports.getDefaultRoleAssumer = getDefaultRoleAssumer; const getDefaultRoleAssumerWithWebIdentity = (stsOptions, stsClientCtor) => { let stsClient; return async (params) => { if (!stsClient) { const { logger, region, requestHandler } = stsOptions; stsClient = new stsClientCtor({ logger, region: decorateDefaultRegion(region || stsOptions.region), ...(requestHandler ? { requestHandler } : {}), }); } const { Credentials } = await stsClient.send(new AssumeRoleWithWebIdentityCommand_1.AssumeRoleWithWebIdentityCommand(params)); if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) { throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`); } return { accessKeyId: Credentials.AccessKeyId, secretAccessKey: Credentials.SecretAccessKey, sessionToken: Credentials.SessionToken, expiration: Credentials.Expiration, }; }; }; exports.getDefaultRoleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity; const decorateDefaultCredentialProvider = (provider) => (input) => provider({ roleAssumer: (0, exports.getDefaultRoleAssumer)(input, input.stsClientCtor), roleAssumerWithWebIdentity: (0, exports.getDefaultRoleAssumerWithWebIdentity)(input, input.stsClientCtor), ...input, }); exports.decorateDefaultCredentialProvider = decorateDefaultCredentialProvider; /***/ }), /***/ 20510: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveClientEndpointParameters = void 0; const resolveClientEndpointParameters = (options) => { return { ...options, useDualstackEndpoint: options.useDualstackEndpoint ?? false, useFipsEndpoint: options.useFipsEndpoint ?? false, useGlobalEndpoint: options.useGlobalEndpoint ?? false, defaultSigningName: "sts", }; }; exports.resolveClientEndpointParameters = resolveClientEndpointParameters; /***/ }), /***/ 41203: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.defaultEndpointResolver = void 0; const util_endpoints_1 = __nccwpck_require__(45473); const ruleset_1 = __nccwpck_require__(86882); const defaultEndpointResolver = (endpointParams, context = {}) => { return (0, util_endpoints_1.resolveEndpoint)(ruleset_1.ruleSet, { endpointParams: endpointParams, logger: context.logger, }); }; exports.defaultEndpointResolver = defaultEndpointResolver; /***/ }), /***/ 86882: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ruleSet = void 0; const F = "required", G = "type", H = "fn", I = "argv", J = "ref"; const a = false, b = true, c = "booleanEquals", d = "stringEquals", e = "sigv4", f = "sts", g = "us-east-1", h = "endpoint", i = "https://sts.{Region}.{PartitionResult#dnsSuffix}", j = "tree", k = "error", l = "getAttr", m = { [F]: false, [G]: "String" }, n = { [F]: true, "default": false, [G]: "Boolean" }, o = { [J]: "Endpoint" }, p = { [H]: "isSet", [I]: [{ [J]: "Region" }] }, q = { [J]: "Region" }, r = { [H]: "aws.partition", [I]: [q], "assign": "PartitionResult" }, s = { [J]: "UseFIPS" }, t = { [J]: "UseDualStack" }, u = { "url": "https://sts.amazonaws.com", "properties": { "authSchemes": [{ "name": e, "signingName": f, "signingRegion": g }] }, "headers": {} }, v = {}, w = { "conditions": [{ [H]: d, [I]: [q, "aws-global"] }], [h]: u, [G]: h }, x = { [H]: c, [I]: [s, true] }, y = { [H]: c, [I]: [t, true] }, z = { [H]: l, [I]: [{ [J]: "PartitionResult" }, "supportsFIPS"] }, A = { [J]: "PartitionResult" }, B = { [H]: c, [I]: [true, { [H]: l, [I]: [A, "supportsDualStack"] }] }, C = [{ [H]: "isSet", [I]: [o] }], D = [x], E = [y]; const _data = { version: "1.0", parameters: { Region: m, UseDualStack: n, UseFIPS: n, Endpoint: m, UseGlobalEndpoint: n }, rules: [{ conditions: [{ [H]: c, [I]: [{ [J]: "UseGlobalEndpoint" }, b] }, { [H]: "not", [I]: C }, p, r, { [H]: c, [I]: [s, a] }, { [H]: c, [I]: [t, a] }], rules: [{ conditions: [{ [H]: d, [I]: [q, "ap-northeast-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "ap-south-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "ap-southeast-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "ap-southeast-2"] }], endpoint: u, [G]: h }, w, { conditions: [{ [H]: d, [I]: [q, "ca-central-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-central-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-north-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-west-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-west-2"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-west-3"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "sa-east-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, g] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "us-east-2"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "us-west-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "us-west-2"] }], endpoint: u, [G]: h }, { endpoint: { url: i, properties: { authSchemes: [{ name: e, signingName: f, signingRegion: "{Region}" }] }, headers: v }, [G]: h }], [G]: j }, { conditions: C, rules: [{ conditions: D, error: "Invalid Configuration: FIPS and custom endpoint are not supported", [G]: k }, { conditions: E, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", [G]: k }, { endpoint: { url: o, properties: v, headers: v }, [G]: h }], [G]: j }, { conditions: [p], rules: [{ conditions: [r], rules: [{ conditions: [x, y], rules: [{ conditions: [{ [H]: c, [I]: [b, z] }, B], rules: [{ endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v, headers: v }, [G]: h }], [G]: j }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", [G]: k }], [G]: j }, { conditions: D, rules: [{ conditions: [{ [H]: c, [I]: [z, b] }], rules: [{ conditions: [{ [H]: d, [I]: [{ [H]: l, [I]: [A, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://sts.{Region}.amazonaws.com", properties: v, headers: v }, [G]: h }, { endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dnsSuffix}", properties: v, headers: v }, [G]: h }], [G]: j }, { error: "FIPS is enabled but this partition does not support FIPS", [G]: k }], [G]: j }, { conditions: E, rules: [{ conditions: [B], rules: [{ endpoint: { url: "https://sts.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v, headers: v }, [G]: h }], [G]: j }, { error: "DualStack is enabled but this partition does not support DualStack", [G]: k }], [G]: j }, w, { endpoint: { url: i, properties: v, headers: v }, [G]: h }], [G]: j }], [G]: j }, { error: "Invalid Configuration: Missing Region", [G]: k }] }; exports.ruleSet = _data; /***/ }), /***/ 52209: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.STSServiceException = void 0; const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(64195), exports); tslib_1.__exportStar(__nccwpck_require__(32605), exports); tslib_1.__exportStar(__nccwpck_require__(55716), exports); tslib_1.__exportStar(__nccwpck_require__(20106), exports); tslib_1.__exportStar(__nccwpck_require__(88028), exports); __nccwpck_require__(13350); var STSServiceException_1 = __nccwpck_require__(26450); Object.defineProperty(exports, "STSServiceException", ({ enumerable: true, get: function () { return STSServiceException_1.STSServiceException; } })); /***/ }), /***/ 26450: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.STSServiceException = exports.__ServiceException = void 0; const smithy_client_1 = __nccwpck_require__(63570); Object.defineProperty(exports, "__ServiceException", ({ enumerable: true, get: function () { return smithy_client_1.ServiceException; } })); class STSServiceException extends smithy_client_1.ServiceException { constructor(options) { super(options); Object.setPrototypeOf(this, STSServiceException.prototype); } } exports.STSServiceException = STSServiceException; /***/ }), /***/ 20106: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(21780), exports); /***/ }), /***/ 21780: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GetSessionTokenResponseFilterSensitiveLog = exports.GetFederationTokenResponseFilterSensitiveLog = exports.AssumeRoleWithWebIdentityResponseFilterSensitiveLog = exports.AssumeRoleWithWebIdentityRequestFilterSensitiveLog = exports.AssumeRoleWithSAMLResponseFilterSensitiveLog = exports.AssumeRoleWithSAMLRequestFilterSensitiveLog = exports.AssumeRoleResponseFilterSensitiveLog = exports.CredentialsFilterSensitiveLog = exports.InvalidAuthorizationMessageException = exports.IDPCommunicationErrorException = exports.InvalidIdentityTokenException = exports.IDPRejectedClaimException = exports.RegionDisabledException = exports.PackedPolicyTooLargeException = exports.MalformedPolicyDocumentException = exports.ExpiredTokenException = void 0; const smithy_client_1 = __nccwpck_require__(63570); const STSServiceException_1 = __nccwpck_require__(26450); class ExpiredTokenException extends STSServiceException_1.STSServiceException { constructor(opts) { super({ name: "ExpiredTokenException", $fault: "client", ...opts, }); this.name = "ExpiredTokenException"; this.$fault = "client"; Object.setPrototypeOf(this, ExpiredTokenException.prototype); } } exports.ExpiredTokenException = ExpiredTokenException; class MalformedPolicyDocumentException extends STSServiceException_1.STSServiceException { constructor(opts) { super({ name: "MalformedPolicyDocumentException", $fault: "client", ...opts, }); this.name = "MalformedPolicyDocumentException"; this.$fault = "client"; Object.setPrototypeOf(this, MalformedPolicyDocumentException.prototype); } } exports.MalformedPolicyDocumentException = MalformedPolicyDocumentException; class PackedPolicyTooLargeException extends STSServiceException_1.STSServiceException { constructor(opts) { super({ name: "PackedPolicyTooLargeException", $fault: "client", ...opts, }); this.name = "PackedPolicyTooLargeException"; this.$fault = "client"; Object.setPrototypeOf(this, PackedPolicyTooLargeException.prototype); } } exports.PackedPolicyTooLargeException = PackedPolicyTooLargeException; class RegionDisabledException extends STSServiceException_1.STSServiceException { constructor(opts) { super({ name: "RegionDisabledException", $fault: "client", ...opts, }); this.name = "RegionDisabledException"; this.$fault = "client"; Object.setPrototypeOf(this, RegionDisabledException.prototype); } } exports.RegionDisabledException = RegionDisabledException; class IDPRejectedClaimException extends STSServiceException_1.STSServiceException { constructor(opts) { super({ name: "IDPRejectedClaimException", $fault: "client", ...opts, }); this.name = "IDPRejectedClaimException"; this.$fault = "client"; Object.setPrototypeOf(this, IDPRejectedClaimException.prototype); } } exports.IDPRejectedClaimException = IDPRejectedClaimException; class InvalidIdentityTokenException extends STSServiceException_1.STSServiceException { constructor(opts) { super({ name: "InvalidIdentityTokenException", $fault: "client", ...opts, }); this.name = "InvalidIdentityTokenException"; this.$fault = "client"; Object.setPrototypeOf(this, InvalidIdentityTokenException.prototype); } } exports.InvalidIdentityTokenException = InvalidIdentityTokenException; class IDPCommunicationErrorException extends STSServiceException_1.STSServiceException { constructor(opts) { super({ name: "IDPCommunicationErrorException", $fault: "client", ...opts, }); this.name = "IDPCommunicationErrorException"; this.$fault = "client"; Object.setPrototypeOf(this, IDPCommunicationErrorException.prototype); } } exports.IDPCommunicationErrorException = IDPCommunicationErrorException; class InvalidAuthorizationMessageException extends STSServiceException_1.STSServiceException { constructor(opts) { super({ name: "InvalidAuthorizationMessageException", $fault: "client", ...opts, }); this.name = "InvalidAuthorizationMessageException"; this.$fault = "client"; Object.setPrototypeOf(this, InvalidAuthorizationMessageException.prototype); } } exports.InvalidAuthorizationMessageException = InvalidAuthorizationMessageException; const CredentialsFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.SecretAccessKey && { SecretAccessKey: smithy_client_1.SENSITIVE_STRING }), }); exports.CredentialsFilterSensitiveLog = CredentialsFilterSensitiveLog; const AssumeRoleResponseFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.Credentials && { Credentials: (0, exports.CredentialsFilterSensitiveLog)(obj.Credentials) }), }); exports.AssumeRoleResponseFilterSensitiveLog = AssumeRoleResponseFilterSensitiveLog; const AssumeRoleWithSAMLRequestFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.SAMLAssertion && { SAMLAssertion: smithy_client_1.SENSITIVE_STRING }), }); exports.AssumeRoleWithSAMLRequestFilterSensitiveLog = AssumeRoleWithSAMLRequestFilterSensitiveLog; const AssumeRoleWithSAMLResponseFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.Credentials && { Credentials: (0, exports.CredentialsFilterSensitiveLog)(obj.Credentials) }), }); exports.AssumeRoleWithSAMLResponseFilterSensitiveLog = AssumeRoleWithSAMLResponseFilterSensitiveLog; const AssumeRoleWithWebIdentityRequestFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.WebIdentityToken && { WebIdentityToken: smithy_client_1.SENSITIVE_STRING }), }); exports.AssumeRoleWithWebIdentityRequestFilterSensitiveLog = AssumeRoleWithWebIdentityRequestFilterSensitiveLog; const AssumeRoleWithWebIdentityResponseFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.Credentials && { Credentials: (0, exports.CredentialsFilterSensitiveLog)(obj.Credentials) }), }); exports.AssumeRoleWithWebIdentityResponseFilterSensitiveLog = AssumeRoleWithWebIdentityResponseFilterSensitiveLog; const GetFederationTokenResponseFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.Credentials && { Credentials: (0, exports.CredentialsFilterSensitiveLog)(obj.Credentials) }), }); exports.GetFederationTokenResponseFilterSensitiveLog = GetFederationTokenResponseFilterSensitiveLog; const GetSessionTokenResponseFilterSensitiveLog = (obj) => ({ ...obj, ...(obj.Credentials && { Credentials: (0, exports.CredentialsFilterSensitiveLog)(obj.Credentials) }), }); exports.GetSessionTokenResponseFilterSensitiveLog = GetSessionTokenResponseFilterSensitiveLog; /***/ }), /***/ 10740: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.de_GetSessionTokenCommand = exports.de_GetFederationTokenCommand = exports.de_GetCallerIdentityCommand = exports.de_GetAccessKeyInfoCommand = exports.de_DecodeAuthorizationMessageCommand = exports.de_AssumeRoleWithWebIdentityCommand = exports.de_AssumeRoleWithSAMLCommand = exports.de_AssumeRoleCommand = exports.se_GetSessionTokenCommand = exports.se_GetFederationTokenCommand = exports.se_GetCallerIdentityCommand = exports.se_GetAccessKeyInfoCommand = exports.se_DecodeAuthorizationMessageCommand = exports.se_AssumeRoleWithWebIdentityCommand = exports.se_AssumeRoleWithSAMLCommand = exports.se_AssumeRoleCommand = void 0; const protocol_http_1 = __nccwpck_require__(64418); const smithy_client_1 = __nccwpck_require__(63570); const fast_xml_parser_1 = __nccwpck_require__(12603); const models_0_1 = __nccwpck_require__(21780); const STSServiceException_1 = __nccwpck_require__(26450); const se_AssumeRoleCommand = async (input, context) => { const headers = SHARED_HEADERS; let body; body = buildFormUrlencodedString({ ...se_AssumeRoleRequest(input, context), Action: "AssumeRole", Version: "2011-06-15", }); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_AssumeRoleCommand = se_AssumeRoleCommand; const se_AssumeRoleWithSAMLCommand = async (input, context) => { const headers = SHARED_HEADERS; let body; body = buildFormUrlencodedString({ ...se_AssumeRoleWithSAMLRequest(input, context), Action: "AssumeRoleWithSAML", Version: "2011-06-15", }); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_AssumeRoleWithSAMLCommand = se_AssumeRoleWithSAMLCommand; const se_AssumeRoleWithWebIdentityCommand = async (input, context) => { const headers = SHARED_HEADERS; let body; body = buildFormUrlencodedString({ ...se_AssumeRoleWithWebIdentityRequest(input, context), Action: "AssumeRoleWithWebIdentity", Version: "2011-06-15", }); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_AssumeRoleWithWebIdentityCommand = se_AssumeRoleWithWebIdentityCommand; const se_DecodeAuthorizationMessageCommand = async (input, context) => { const headers = SHARED_HEADERS; let body; body = buildFormUrlencodedString({ ...se_DecodeAuthorizationMessageRequest(input, context), Action: "DecodeAuthorizationMessage", Version: "2011-06-15", }); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_DecodeAuthorizationMessageCommand = se_DecodeAuthorizationMessageCommand; const se_GetAccessKeyInfoCommand = async (input, context) => { const headers = SHARED_HEADERS; let body; body = buildFormUrlencodedString({ ...se_GetAccessKeyInfoRequest(input, context), Action: "GetAccessKeyInfo", Version: "2011-06-15", }); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_GetAccessKeyInfoCommand = se_GetAccessKeyInfoCommand; const se_GetCallerIdentityCommand = async (input, context) => { const headers = SHARED_HEADERS; let body; body = buildFormUrlencodedString({ ...se_GetCallerIdentityRequest(input, context), Action: "GetCallerIdentity", Version: "2011-06-15", }); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_GetCallerIdentityCommand = se_GetCallerIdentityCommand; const se_GetFederationTokenCommand = async (input, context) => { const headers = SHARED_HEADERS; let body; body = buildFormUrlencodedString({ ...se_GetFederationTokenRequest(input, context), Action: "GetFederationToken", Version: "2011-06-15", }); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_GetFederationTokenCommand = se_GetFederationTokenCommand; const se_GetSessionTokenCommand = async (input, context) => { const headers = SHARED_HEADERS; let body; body = buildFormUrlencodedString({ ...se_GetSessionTokenRequest(input, context), Action: "GetSessionToken", Version: "2011-06-15", }); return buildHttpRpcRequest(context, headers, "/", undefined, body); }; exports.se_GetSessionTokenCommand = se_GetSessionTokenCommand; const de_AssumeRoleCommand = async (output, context) => { if (output.statusCode >= 300) { return de_AssumeRoleCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_AssumeRoleResponse(data.AssumeRoleResult, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_AssumeRoleCommand = de_AssumeRoleCommand; const de_AssumeRoleCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadQueryErrorCode(output, parsedOutput.body); switch (errorCode) { case "ExpiredTokenException": case "com.amazonaws.sts#ExpiredTokenException": throw await de_ExpiredTokenExceptionRes(parsedOutput, context); case "MalformedPolicyDocument": case "com.amazonaws.sts#MalformedPolicyDocumentException": throw await de_MalformedPolicyDocumentExceptionRes(parsedOutput, context); case "PackedPolicyTooLarge": case "com.amazonaws.sts#PackedPolicyTooLargeException": throw await de_PackedPolicyTooLargeExceptionRes(parsedOutput, context); case "RegionDisabledException": case "com.amazonaws.sts#RegionDisabledException": throw await de_RegionDisabledExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody: parsedBody.Error, errorCode, }); } }; const de_AssumeRoleWithSAMLCommand = async (output, context) => { if (output.statusCode >= 300) { return de_AssumeRoleWithSAMLCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_AssumeRoleWithSAMLResponse(data.AssumeRoleWithSAMLResult, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_AssumeRoleWithSAMLCommand = de_AssumeRoleWithSAMLCommand; const de_AssumeRoleWithSAMLCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadQueryErrorCode(output, parsedOutput.body); switch (errorCode) { case "ExpiredTokenException": case "com.amazonaws.sts#ExpiredTokenException": throw await de_ExpiredTokenExceptionRes(parsedOutput, context); case "IDPRejectedClaim": case "com.amazonaws.sts#IDPRejectedClaimException": throw await de_IDPRejectedClaimExceptionRes(parsedOutput, context); case "InvalidIdentityToken": case "com.amazonaws.sts#InvalidIdentityTokenException": throw await de_InvalidIdentityTokenExceptionRes(parsedOutput, context); case "MalformedPolicyDocument": case "com.amazonaws.sts#MalformedPolicyDocumentException": throw await de_MalformedPolicyDocumentExceptionRes(parsedOutput, context); case "PackedPolicyTooLarge": case "com.amazonaws.sts#PackedPolicyTooLargeException": throw await de_PackedPolicyTooLargeExceptionRes(parsedOutput, context); case "RegionDisabledException": case "com.amazonaws.sts#RegionDisabledException": throw await de_RegionDisabledExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody: parsedBody.Error, errorCode, }); } }; const de_AssumeRoleWithWebIdentityCommand = async (output, context) => { if (output.statusCode >= 300) { return de_AssumeRoleWithWebIdentityCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_AssumeRoleWithWebIdentityResponse(data.AssumeRoleWithWebIdentityResult, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_AssumeRoleWithWebIdentityCommand = de_AssumeRoleWithWebIdentityCommand; const de_AssumeRoleWithWebIdentityCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadQueryErrorCode(output, parsedOutput.body); switch (errorCode) { case "ExpiredTokenException": case "com.amazonaws.sts#ExpiredTokenException": throw await de_ExpiredTokenExceptionRes(parsedOutput, context); case "IDPCommunicationError": case "com.amazonaws.sts#IDPCommunicationErrorException": throw await de_IDPCommunicationErrorExceptionRes(parsedOutput, context); case "IDPRejectedClaim": case "com.amazonaws.sts#IDPRejectedClaimException": throw await de_IDPRejectedClaimExceptionRes(parsedOutput, context); case "InvalidIdentityToken": case "com.amazonaws.sts#InvalidIdentityTokenException": throw await de_InvalidIdentityTokenExceptionRes(parsedOutput, context); case "MalformedPolicyDocument": case "com.amazonaws.sts#MalformedPolicyDocumentException": throw await de_MalformedPolicyDocumentExceptionRes(parsedOutput, context); case "PackedPolicyTooLarge": case "com.amazonaws.sts#PackedPolicyTooLargeException": throw await de_PackedPolicyTooLargeExceptionRes(parsedOutput, context); case "RegionDisabledException": case "com.amazonaws.sts#RegionDisabledException": throw await de_RegionDisabledExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody: parsedBody.Error, errorCode, }); } }; const de_DecodeAuthorizationMessageCommand = async (output, context) => { if (output.statusCode >= 300) { return de_DecodeAuthorizationMessageCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_DecodeAuthorizationMessageResponse(data.DecodeAuthorizationMessageResult, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_DecodeAuthorizationMessageCommand = de_DecodeAuthorizationMessageCommand; const de_DecodeAuthorizationMessageCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadQueryErrorCode(output, parsedOutput.body); switch (errorCode) { case "InvalidAuthorizationMessageException": case "com.amazonaws.sts#InvalidAuthorizationMessageException": throw await de_InvalidAuthorizationMessageExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody: parsedBody.Error, errorCode, }); } }; const de_GetAccessKeyInfoCommand = async (output, context) => { if (output.statusCode >= 300) { return de_GetAccessKeyInfoCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_GetAccessKeyInfoResponse(data.GetAccessKeyInfoResult, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_GetAccessKeyInfoCommand = de_GetAccessKeyInfoCommand; const de_GetAccessKeyInfoCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadQueryErrorCode(output, parsedOutput.body); const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody: parsedBody.Error, errorCode, }); }; const de_GetCallerIdentityCommand = async (output, context) => { if (output.statusCode >= 300) { return de_GetCallerIdentityCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_GetCallerIdentityResponse(data.GetCallerIdentityResult, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_GetCallerIdentityCommand = de_GetCallerIdentityCommand; const de_GetCallerIdentityCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadQueryErrorCode(output, parsedOutput.body); const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody: parsedBody.Error, errorCode, }); }; const de_GetFederationTokenCommand = async (output, context) => { if (output.statusCode >= 300) { return de_GetFederationTokenCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_GetFederationTokenResponse(data.GetFederationTokenResult, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_GetFederationTokenCommand = de_GetFederationTokenCommand; const de_GetFederationTokenCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadQueryErrorCode(output, parsedOutput.body); switch (errorCode) { case "MalformedPolicyDocument": case "com.amazonaws.sts#MalformedPolicyDocumentException": throw await de_MalformedPolicyDocumentExceptionRes(parsedOutput, context); case "PackedPolicyTooLarge": case "com.amazonaws.sts#PackedPolicyTooLargeException": throw await de_PackedPolicyTooLargeExceptionRes(parsedOutput, context); case "RegionDisabledException": case "com.amazonaws.sts#RegionDisabledException": throw await de_RegionDisabledExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody: parsedBody.Error, errorCode, }); } }; const de_GetSessionTokenCommand = async (output, context) => { if (output.statusCode >= 300) { return de_GetSessionTokenCommandError(output, context); } const data = await parseBody(output.body, context); let contents = {}; contents = de_GetSessionTokenResponse(data.GetSessionTokenResult, context); const response = { $metadata: deserializeMetadata(output), ...contents, }; return response; }; exports.de_GetSessionTokenCommand = de_GetSessionTokenCommand; const de_GetSessionTokenCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadQueryErrorCode(output, parsedOutput.body); switch (errorCode) { case "RegionDisabledException": case "com.amazonaws.sts#RegionDisabledException": throw await de_RegionDisabledExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody: parsedBody.Error, errorCode, }); } }; const de_ExpiredTokenExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = de_ExpiredTokenException(body.Error, context); const exception = new models_0_1.ExpiredTokenException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_IDPCommunicationErrorExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = de_IDPCommunicationErrorException(body.Error, context); const exception = new models_0_1.IDPCommunicationErrorException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_IDPRejectedClaimExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = de_IDPRejectedClaimException(body.Error, context); const exception = new models_0_1.IDPRejectedClaimException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_InvalidAuthorizationMessageExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = de_InvalidAuthorizationMessageException(body.Error, context); const exception = new models_0_1.InvalidAuthorizationMessageException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_InvalidIdentityTokenExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = de_InvalidIdentityTokenException(body.Error, context); const exception = new models_0_1.InvalidIdentityTokenException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_MalformedPolicyDocumentExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = de_MalformedPolicyDocumentException(body.Error, context); const exception = new models_0_1.MalformedPolicyDocumentException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_PackedPolicyTooLargeExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = de_PackedPolicyTooLargeException(body.Error, context); const exception = new models_0_1.PackedPolicyTooLargeException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const de_RegionDisabledExceptionRes = async (parsedOutput, context) => { const body = parsedOutput.body; const deserialized = de_RegionDisabledException(body.Error, context); const exception = new models_0_1.RegionDisabledException({ $metadata: deserializeMetadata(parsedOutput), ...deserialized, }); return (0, smithy_client_1.decorateServiceException)(exception, body); }; const se_AssumeRoleRequest = (input, context) => { const entries = {}; if (input.RoleArn != null) { entries["RoleArn"] = input.RoleArn; } if (input.RoleSessionName != null) { entries["RoleSessionName"] = input.RoleSessionName; } if (input.PolicyArns != null) { const memberEntries = se_policyDescriptorListType(input.PolicyArns, context); if (input.PolicyArns?.length === 0) { entries.PolicyArns = []; } Object.entries(memberEntries).forEach(([key, value]) => { const loc = `PolicyArns.${key}`; entries[loc] = value; }); } if (input.Policy != null) { entries["Policy"] = input.Policy; } if (input.DurationSeconds != null) { entries["DurationSeconds"] = input.DurationSeconds; } if (input.Tags != null) { const memberEntries = se_tagListType(input.Tags, context); if (input.Tags?.length === 0) { entries.Tags = []; } Object.entries(memberEntries).forEach(([key, value]) => { const loc = `Tags.${key}`; entries[loc] = value; }); } if (input.TransitiveTagKeys != null) { const memberEntries = se_tagKeyListType(input.TransitiveTagKeys, context); if (input.TransitiveTagKeys?.length === 0) { entries.TransitiveTagKeys = []; } Object.entries(memberEntries).forEach(([key, value]) => { const loc = `TransitiveTagKeys.${key}`; entries[loc] = value; }); } if (input.ExternalId != null) { entries["ExternalId"] = input.ExternalId; } if (input.SerialNumber != null) { entries["SerialNumber"] = input.SerialNumber; } if (input.TokenCode != null) { entries["TokenCode"] = input.TokenCode; } if (input.SourceIdentity != null) { entries["SourceIdentity"] = input.SourceIdentity; } if (input.ProvidedContexts != null) { const memberEntries = se_ProvidedContextsListType(input.ProvidedContexts, context); if (input.ProvidedContexts?.length === 0) { entries.ProvidedContexts = []; } Object.entries(memberEntries).forEach(([key, value]) => { const loc = `ProvidedContexts.${key}`; entries[loc] = value; }); } return entries; }; const se_AssumeRoleWithSAMLRequest = (input, context) => { const entries = {}; if (input.RoleArn != null) { entries["RoleArn"] = input.RoleArn; } if (input.PrincipalArn != null) { entries["PrincipalArn"] = input.PrincipalArn; } if (input.SAMLAssertion != null) { entries["SAMLAssertion"] = input.SAMLAssertion; } if (input.PolicyArns != null) { const memberEntries = se_policyDescriptorListType(input.PolicyArns, context); if (input.PolicyArns?.length === 0) { entries.PolicyArns = []; } Object.entries(memberEntries).forEach(([key, value]) => { const loc = `PolicyArns.${key}`; entries[loc] = value; }); } if (input.Policy != null) { entries["Policy"] = input.Policy; } if (input.DurationSeconds != null) { entries["DurationSeconds"] = input.DurationSeconds; } return entries; }; const se_AssumeRoleWithWebIdentityRequest = (input, context) => { const entries = {}; if (input.RoleArn != null) { entries["RoleArn"] = input.RoleArn; } if (input.RoleSessionName != null) { entries["RoleSessionName"] = input.RoleSessionName; } if (input.WebIdentityToken != null) { entries["WebIdentityToken"] = input.WebIdentityToken; } if (input.ProviderId != null) { entries["ProviderId"] = input.ProviderId; } if (input.PolicyArns != null) { const memberEntries = se_policyDescriptorListType(input.PolicyArns, context); if (input.PolicyArns?.length === 0) { entries.PolicyArns = []; } Object.entries(memberEntries).forEach(([key, value]) => { const loc = `PolicyArns.${key}`; entries[loc] = value; }); } if (input.Policy != null) { entries["Policy"] = input.Policy; } if (input.DurationSeconds != null) { entries["DurationSeconds"] = input.DurationSeconds; } return entries; }; const se_DecodeAuthorizationMessageRequest = (input, context) => { const entries = {}; if (input.EncodedMessage != null) { entries["EncodedMessage"] = input.EncodedMessage; } return entries; }; const se_GetAccessKeyInfoRequest = (input, context) => { const entries = {}; if (input.AccessKeyId != null) { entries["AccessKeyId"] = input.AccessKeyId; } return entries; }; const se_GetCallerIdentityRequest = (input, context) => { const entries = {}; return entries; }; const se_GetFederationTokenRequest = (input, context) => { const entries = {}; if (input.Name != null) { entries["Name"] = input.Name; } if (input.Policy != null) { entries["Policy"] = input.Policy; } if (input.PolicyArns != null) { const memberEntries = se_policyDescriptorListType(input.PolicyArns, context); if (input.PolicyArns?.length === 0) { entries.PolicyArns = []; } Object.entries(memberEntries).forEach(([key, value]) => { const loc = `PolicyArns.${key}`; entries[loc] = value; }); } if (input.DurationSeconds != null) { entries["DurationSeconds"] = input.DurationSeconds; } if (input.Tags != null) { const memberEntries = se_tagListType(input.Tags, context); if (input.Tags?.length === 0) { entries.Tags = []; } Object.entries(memberEntries).forEach(([key, value]) => { const loc = `Tags.${key}`; entries[loc] = value; }); } return entries; }; const se_GetSessionTokenRequest = (input, context) => { const entries = {}; if (input.DurationSeconds != null) { entries["DurationSeconds"] = input.DurationSeconds; } if (input.SerialNumber != null) { entries["SerialNumber"] = input.SerialNumber; } if (input.TokenCode != null) { entries["TokenCode"] = input.TokenCode; } return entries; }; const se_policyDescriptorListType = (input, context) => { const entries = {}; let counter = 1; for (const entry of input) { if (entry === null) { continue; } const memberEntries = se_PolicyDescriptorType(entry, context); Object.entries(memberEntries).forEach(([key, value]) => { entries[`member.${counter}.${key}`] = value; }); counter++; } return entries; }; const se_PolicyDescriptorType = (input, context) => { const entries = {}; if (input.arn != null) { entries["arn"] = input.arn; } return entries; }; const se_ProvidedContext = (input, context) => { const entries = {}; if (input.ProviderArn != null) { entries["ProviderArn"] = input.ProviderArn; } if (input.ContextAssertion != null) { entries["ContextAssertion"] = input.ContextAssertion; } return entries; }; const se_ProvidedContextsListType = (input, context) => { const entries = {}; let counter = 1; for (const entry of input) { if (entry === null) { continue; } const memberEntries = se_ProvidedContext(entry, context); Object.entries(memberEntries).forEach(([key, value]) => { entries[`member.${counter}.${key}`] = value; }); counter++; } return entries; }; const se_Tag = (input, context) => { const entries = {}; if (input.Key != null) { entries["Key"] = input.Key; } if (input.Value != null) { entries["Value"] = input.Value; } return entries; }; const se_tagKeyListType = (input, context) => { const entries = {}; let counter = 1; for (const entry of input) { if (entry === null) { continue; } entries[`member.${counter}`] = entry; counter++; } return entries; }; const se_tagListType = (input, context) => { const entries = {}; let counter = 1; for (const entry of input) { if (entry === null) { continue; } const memberEntries = se_Tag(entry, context); Object.entries(memberEntries).forEach(([key, value]) => { entries[`member.${counter}.${key}`] = value; }); counter++; } return entries; }; const de_AssumedRoleUser = (output, context) => { const contents = {}; if (output["AssumedRoleId"] !== undefined) { contents.AssumedRoleId = (0, smithy_client_1.expectString)(output["AssumedRoleId"]); } if (output["Arn"] !== undefined) { contents.Arn = (0, smithy_client_1.expectString)(output["Arn"]); } return contents; }; const de_AssumeRoleResponse = (output, context) => { const contents = {}; if (output["Credentials"] !== undefined) { contents.Credentials = de_Credentials(output["Credentials"], context); } if (output["AssumedRoleUser"] !== undefined) { contents.AssumedRoleUser = de_AssumedRoleUser(output["AssumedRoleUser"], context); } if (output["PackedPolicySize"] !== undefined) { contents.PackedPolicySize = (0, smithy_client_1.strictParseInt32)(output["PackedPolicySize"]); } if (output["SourceIdentity"] !== undefined) { contents.SourceIdentity = (0, smithy_client_1.expectString)(output["SourceIdentity"]); } return contents; }; const de_AssumeRoleWithSAMLResponse = (output, context) => { const contents = {}; if (output["Credentials"] !== undefined) { contents.Credentials = de_Credentials(output["Credentials"], context); } if (output["AssumedRoleUser"] !== undefined) { contents.AssumedRoleUser = de_AssumedRoleUser(output["AssumedRoleUser"], context); } if (output["PackedPolicySize"] !== undefined) { contents.PackedPolicySize = (0, smithy_client_1.strictParseInt32)(output["PackedPolicySize"]); } if (output["Subject"] !== undefined) { contents.Subject = (0, smithy_client_1.expectString)(output["Subject"]); } if (output["SubjectType"] !== undefined) { contents.SubjectType = (0, smithy_client_1.expectString)(output["SubjectType"]); } if (output["Issuer"] !== undefined) { contents.Issuer = (0, smithy_client_1.expectString)(output["Issuer"]); } if (output["Audience"] !== undefined) { contents.Audience = (0, smithy_client_1.expectString)(output["Audience"]); } if (output["NameQualifier"] !== undefined) { contents.NameQualifier = (0, smithy_client_1.expectString)(output["NameQualifier"]); } if (output["SourceIdentity"] !== undefined) { contents.SourceIdentity = (0, smithy_client_1.expectString)(output["SourceIdentity"]); } return contents; }; const de_AssumeRoleWithWebIdentityResponse = (output, context) => { const contents = {}; if (output["Credentials"] !== undefined) { contents.Credentials = de_Credentials(output["Credentials"], context); } if (output["SubjectFromWebIdentityToken"] !== undefined) { contents.SubjectFromWebIdentityToken = (0, smithy_client_1.expectString)(output["SubjectFromWebIdentityToken"]); } if (output["AssumedRoleUser"] !== undefined) { contents.AssumedRoleUser = de_AssumedRoleUser(output["AssumedRoleUser"], context); } if (output["PackedPolicySize"] !== undefined) { contents.PackedPolicySize = (0, smithy_client_1.strictParseInt32)(output["PackedPolicySize"]); } if (output["Provider"] !== undefined) { contents.Provider = (0, smithy_client_1.expectString)(output["Provider"]); } if (output["Audience"] !== undefined) { contents.Audience = (0, smithy_client_1.expectString)(output["Audience"]); } if (output["SourceIdentity"] !== undefined) { contents.SourceIdentity = (0, smithy_client_1.expectString)(output["SourceIdentity"]); } return contents; }; const de_Credentials = (output, context) => { const contents = {}; if (output["AccessKeyId"] !== undefined) { contents.AccessKeyId = (0, smithy_client_1.expectString)(output["AccessKeyId"]); } if (output["SecretAccessKey"] !== undefined) { contents.SecretAccessKey = (0, smithy_client_1.expectString)(output["SecretAccessKey"]); } if (output["SessionToken"] !== undefined) { contents.SessionToken = (0, smithy_client_1.expectString)(output["SessionToken"]); } if (output["Expiration"] !== undefined) { contents.Expiration = (0, smithy_client_1.expectNonNull)((0, smithy_client_1.parseRfc3339DateTimeWithOffset)(output["Expiration"])); } return contents; }; const de_DecodeAuthorizationMessageResponse = (output, context) => { const contents = {}; if (output["DecodedMessage"] !== undefined) { contents.DecodedMessage = (0, smithy_client_1.expectString)(output["DecodedMessage"]); } return contents; }; const de_ExpiredTokenException = (output, context) => { const contents = {}; if (output["message"] !== undefined) { contents.message = (0, smithy_client_1.expectString)(output["message"]); } return contents; }; const de_FederatedUser = (output, context) => { const contents = {}; if (output["FederatedUserId"] !== undefined) { contents.FederatedUserId = (0, smithy_client_1.expectString)(output["FederatedUserId"]); } if (output["Arn"] !== undefined) { contents.Arn = (0, smithy_client_1.expectString)(output["Arn"]); } return contents; }; const de_GetAccessKeyInfoResponse = (output, context) => { const contents = {}; if (output["Account"] !== undefined) { contents.Account = (0, smithy_client_1.expectString)(output["Account"]); } return contents; }; const de_GetCallerIdentityResponse = (output, context) => { const contents = {}; if (output["UserId"] !== undefined) { contents.UserId = (0, smithy_client_1.expectString)(output["UserId"]); } if (output["Account"] !== undefined) { contents.Account = (0, smithy_client_1.expectString)(output["Account"]); } if (output["Arn"] !== undefined) { contents.Arn = (0, smithy_client_1.expectString)(output["Arn"]); } return contents; }; const de_GetFederationTokenResponse = (output, context) => { const contents = {}; if (output["Credentials"] !== undefined) { contents.Credentials = de_Credentials(output["Credentials"], context); } if (output["FederatedUser"] !== undefined) { contents.FederatedUser = de_FederatedUser(output["FederatedUser"], context); } if (output["PackedPolicySize"] !== undefined) { contents.PackedPolicySize = (0, smithy_client_1.strictParseInt32)(output["PackedPolicySize"]); } return contents; }; const de_GetSessionTokenResponse = (output, context) => { const contents = {}; if (output["Credentials"] !== undefined) { contents.Credentials = de_Credentials(output["Credentials"], context); } return contents; }; const de_IDPCommunicationErrorException = (output, context) => { const contents = {}; if (output["message"] !== undefined) { contents.message = (0, smithy_client_1.expectString)(output["message"]); } return contents; }; const de_IDPRejectedClaimException = (output, context) => { const contents = {}; if (output["message"] !== undefined) { contents.message = (0, smithy_client_1.expectString)(output["message"]); } return contents; }; const de_InvalidAuthorizationMessageException = (output, context) => { const contents = {}; if (output["message"] !== undefined) { contents.message = (0, smithy_client_1.expectString)(output["message"]); } return contents; }; const de_InvalidIdentityTokenException = (output, context) => { const contents = {}; if (output["message"] !== undefined) { contents.message = (0, smithy_client_1.expectString)(output["message"]); } return contents; }; const de_MalformedPolicyDocumentException = (output, context) => { const contents = {}; if (output["message"] !== undefined) { contents.message = (0, smithy_client_1.expectString)(output["message"]); } return contents; }; const de_PackedPolicyTooLargeException = (output, context) => { const contents = {}; if (output["message"] !== undefined) { contents.message = (0, smithy_client_1.expectString)(output["message"]); } return contents; }; const de_RegionDisabledException = (output, context) => { const contents = {}; if (output["message"] !== undefined) { contents.message = (0, smithy_client_1.expectString)(output["message"]); } return contents; }; const deserializeMetadata = (output) => ({ httpStatusCode: output.statusCode, requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], extendedRequestId: output.headers["x-amz-id-2"], cfId: output.headers["x-amz-cf-id"], }); const collectBodyString = (streamBody, context) => (0, smithy_client_1.collectBody)(streamBody, context).then((body) => context.utf8Encoder(body)); const throwDefaultError = (0, smithy_client_1.withBaseException)(STSServiceException_1.STSServiceException); const buildHttpRpcRequest = async (context, headers, path, resolvedHostname, body) => { const { hostname, protocol = "https", port, path: basePath } = await context.endpoint(); const contents = { protocol, hostname, port, method: "POST", path: basePath.endsWith("/") ? basePath.slice(0, -1) + path : basePath + path, headers, }; if (resolvedHostname !== undefined) { contents.hostname = resolvedHostname; } if (body !== undefined) { contents.body = body; } return new protocol_http_1.HttpRequest(contents); }; const SHARED_HEADERS = { "content-type": "application/x-www-form-urlencoded", }; const parseBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { if (encoded.length) { const parser = new fast_xml_parser_1.XMLParser({ attributeNamePrefix: "", htmlEntities: true, ignoreAttributes: false, ignoreDeclaration: true, parseTagValue: false, trimValues: false, tagValueProcessor: (_, val) => (val.trim() === "" && val.includes("\n") ? "" : undefined), }); parser.addEntity("#xD", "\r"); parser.addEntity("#10", "\n"); const parsedObj = parser.parse(encoded); const textNodeName = "#text"; const key = Object.keys(parsedObj)[0]; const parsedObjToReturn = parsedObj[key]; if (parsedObjToReturn[textNodeName]) { parsedObjToReturn[key] = parsedObjToReturn[textNodeName]; delete parsedObjToReturn[textNodeName]; } return (0, smithy_client_1.getValueFromTextNode)(parsedObjToReturn); } return {}; }); const parseErrorBody = async (errorBody, context) => { const value = await parseBody(errorBody, context); if (value.Error) { value.Error.message = value.Error.message ?? value.Error.Message; } return value; }; const buildFormUrlencodedString = (formEntries) => Object.entries(formEntries) .map(([key, value]) => (0, smithy_client_1.extendedEncodeURIComponent)(key) + "=" + (0, smithy_client_1.extendedEncodeURIComponent)(value)) .join("&"); const loadQueryErrorCode = (output, data) => { if (data.Error?.Code !== undefined) { return data.Error.Code; } if (output.statusCode == 404) { return "NotFound"; } }; /***/ }), /***/ 83405: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getRuntimeConfig = void 0; const tslib_1 = __nccwpck_require__(4351); const package_json_1 = tslib_1.__importDefault(__nccwpck_require__(7947)); const defaultStsRoleAssumers_1 = __nccwpck_require__(90048); const core_1 = __nccwpck_require__(59963); const credential_provider_node_1 = __nccwpck_require__(75531); const util_user_agent_node_1 = __nccwpck_require__(98095); const config_resolver_1 = __nccwpck_require__(53098); const hash_node_1 = __nccwpck_require__(3081); const middleware_retry_1 = __nccwpck_require__(96039); const node_config_provider_1 = __nccwpck_require__(33461); const node_http_handler_1 = __nccwpck_require__(20258); const util_body_length_node_1 = __nccwpck_require__(68075); const util_retry_1 = __nccwpck_require__(84902); const runtimeConfig_shared_1 = __nccwpck_require__(52642); const smithy_client_1 = __nccwpck_require__(63570); const util_defaults_mode_node_1 = __nccwpck_require__(72429); const smithy_client_2 = __nccwpck_require__(63570); const getRuntimeConfig = (config) => { (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version); const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config); const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode); const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config); (0, core_1.emitWarningIfUnsupportedVersion)(process.version); return { ...clientSharedValues, ...config, runtime: "node", defaultsMode, bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, credentialDefaultProvider: config?.credentialDefaultProvider ?? (0, defaultStsRoleAssumers_1.decorateDefaultCredentialProvider)(credential_provider_node_1.defaultProvider), defaultUserAgentProvider: config?.defaultUserAgentProvider ?? (0, util_user_agent_node_1.defaultUserAgent)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS), region: config?.region ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS), requestHandler: config?.requestHandler ?? new node_http_handler_1.NodeHttpHandler(defaultConfigProvider), retryMode: config?.retryMode ?? (0, node_config_provider_1.loadConfig)({ ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS, default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE, }), sha256: config?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"), streamCollector: config?.streamCollector ?? node_http_handler_1.streamCollector, useDualstackEndpoint: config?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS), useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS), }; }; exports.getRuntimeConfig = getRuntimeConfig; /***/ }), /***/ 52642: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getRuntimeConfig = void 0; const smithy_client_1 = __nccwpck_require__(63570); const url_parser_1 = __nccwpck_require__(14681); const util_base64_1 = __nccwpck_require__(75600); const util_utf8_1 = __nccwpck_require__(41895); const endpointResolver_1 = __nccwpck_require__(41203); const getRuntimeConfig = (config) => { return { apiVersion: "2011-06-15", base64Decoder: config?.base64Decoder ?? util_base64_1.fromBase64, base64Encoder: config?.base64Encoder ?? util_base64_1.toBase64, disableHostPrefix: config?.disableHostPrefix ?? false, endpointProvider: config?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver, extensions: config?.extensions ?? [], logger: config?.logger ?? new smithy_client_1.NoOpLogger(), serviceId: config?.serviceId ?? "STS", urlParser: config?.urlParser ?? url_parser_1.parseUrl, utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, }; }; exports.getRuntimeConfig = getRuntimeConfig; /***/ }), /***/ 32053: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveRuntimeExtensions = void 0; const region_config_resolver_1 = __nccwpck_require__(18156); const protocol_http_1 = __nccwpck_require__(64418); const smithy_client_1 = __nccwpck_require__(63570); const asPartial = (t) => t; const resolveRuntimeExtensions = (runtimeConfig, extensions) => { const extensionConfiguration = { ...asPartial((0, region_config_resolver_1.getAwsRegionExtensionConfiguration)(runtimeConfig)), ...asPartial((0, smithy_client_1.getDefaultExtensionConfiguration)(runtimeConfig)), ...asPartial((0, protocol_http_1.getHttpHandlerExtensionConfiguration)(runtimeConfig)), }; extensions.forEach((extension) => extension.configure(extensionConfiguration)); return { ...runtimeConfig, ...(0, region_config_resolver_1.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), ...(0, smithy_client_1.resolveDefaultRuntimeConfig)(extensionConfiguration), ...(0, protocol_http_1.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), }; }; exports.resolveRuntimeExtensions = resolveRuntimeExtensions; /***/ }), /***/ 14154: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.emitWarningIfUnsupportedVersion = void 0; let warningEmitted = false; const emitWarningIfUnsupportedVersion = (version) => { if (version && !warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 16) { warningEmitted = true; process.emitWarning(`NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will no longer support Node.js 14.x on May 1, 2024. To continue receiving updates to AWS services, bug fixes, and security updates please upgrade to an active Node.js LTS version. More information can be found at: https://a.co/dzr2AJd`); } }; exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion; /***/ }), /***/ 7249: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(14154), exports); /***/ }), /***/ 59963: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(7249), exports); tslib_1.__exportStar(__nccwpck_require__(53069), exports); /***/ }), /***/ 26133: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports._toNum = exports._toBool = exports._toStr = void 0; const _toStr = (val) => { if (val == null) { return val; } if (typeof val === "number" || typeof val === "bigint") { const warning = new Error(`Received number ${val} where a string was expected.`); warning.name = "Warning"; console.warn(warning); return String(val); } if (typeof val === "boolean") { const warning = new Error(`Received boolean ${val} where a string was expected.`); warning.name = "Warning"; console.warn(warning); return String(val); } return val; }; exports._toStr = _toStr; const _toBool = (val) => { if (val == null) { return val; } if (typeof val === "number") { } if (typeof val === "string") { const lowercase = val.toLowerCase(); if (val !== "" && lowercase !== "false" && lowercase !== "true") { const warning = new Error(`Received string "${val}" where a boolean was expected.`); warning.name = "Warning"; console.warn(warning); } return val !== "" && lowercase !== "false"; } return val; }; exports._toBool = _toBool; const _toNum = (val) => { if (val == null) { return val; } if (typeof val === "boolean") { } if (typeof val === "string") { const num = Number(val); if (num.toString() !== val) { const warning = new Error(`Received string "${val}" where a number was expected.`); warning.name = "Warning"; console.warn(warning); return val; } return num; } return val; }; exports._toNum = _toNum; /***/ }), /***/ 53069: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(26133), exports); tslib_1.__exportStar(__nccwpck_require__(11823), exports); /***/ }), /***/ 11823: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.awsExpectUnion = void 0; const smithy_client_1 = __nccwpck_require__(63570); const awsExpectUnion = (value) => { if (value == null) { return undefined; } if (typeof value === "object" && "__type" in value) { delete value.__type; } return (0, smithy_client_1.expectUnion)(value); }; exports.awsExpectUnion = awsExpectUnion; /***/ }), /***/ 80255: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fromEnv = exports.ENV_EXPIRATION = exports.ENV_SESSION = exports.ENV_SECRET = exports.ENV_KEY = void 0; const property_provider_1 = __nccwpck_require__(79721); exports.ENV_KEY = "AWS_ACCESS_KEY_ID"; exports.ENV_SECRET = "AWS_SECRET_ACCESS_KEY"; exports.ENV_SESSION = "AWS_SESSION_TOKEN"; exports.ENV_EXPIRATION = "AWS_CREDENTIAL_EXPIRATION"; const fromEnv = () => async () => { const accessKeyId = process.env[exports.ENV_KEY]; const secretAccessKey = process.env[exports.ENV_SECRET]; const sessionToken = process.env[exports.ENV_SESSION]; const expiry = process.env[exports.ENV_EXPIRATION]; if (accessKeyId && secretAccessKey) { return { accessKeyId, secretAccessKey, ...(sessionToken && { sessionToken }), ...(expiry && { expiration: new Date(expiry) }), }; } throw new property_provider_1.CredentialsProviderError("Unable to find environment variable credentials."); }; exports.fromEnv = fromEnv; /***/ }), /***/ 15972: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(80255), exports); /***/ }), /***/ 55442: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fromIni = void 0; const shared_ini_file_loader_1 = __nccwpck_require__(43507); const resolveProfileData_1 = __nccwpck_require__(95653); const fromIni = (init = {}) => async () => { const profiles = await (0, shared_ini_file_loader_1.parseKnownFiles)(init); return (0, resolveProfileData_1.resolveProfileData)((0, shared_ini_file_loader_1.getProfileName)(init), profiles, init); }; exports.fromIni = fromIni; /***/ }), /***/ 74203: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(55442), exports); /***/ }), /***/ 60853: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveAssumeRoleCredentials = exports.isAssumeRoleProfile = void 0; const property_provider_1 = __nccwpck_require__(79721); const shared_ini_file_loader_1 = __nccwpck_require__(43507); const resolveCredentialSource_1 = __nccwpck_require__(82458); const resolveProfileData_1 = __nccwpck_require__(95653); const isAssumeRoleProfile = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.role_arn === "string" && ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1 && ["undefined", "string"].indexOf(typeof arg.external_id) > -1 && ["undefined", "string"].indexOf(typeof arg.mfa_serial) > -1 && (isAssumeRoleWithSourceProfile(arg) || isAssumeRoleWithProviderProfile(arg)); exports.isAssumeRoleProfile = isAssumeRoleProfile; const isAssumeRoleWithSourceProfile = (arg) => typeof arg.source_profile === "string" && typeof arg.credential_source === "undefined"; const isAssumeRoleWithProviderProfile = (arg) => typeof arg.credential_source === "string" && typeof arg.source_profile === "undefined"; const resolveAssumeRoleCredentials = async (profileName, profiles, options, visitedProfiles = {}) => { const data = profiles[profileName]; if (!options.roleAssumer) { throw new property_provider_1.CredentialsProviderError(`Profile ${profileName} requires a role to be assumed, but no role assumption callback was provided.`, false); } const { source_profile } = data; if (source_profile && source_profile in visitedProfiles) { throw new property_provider_1.CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile` + ` ${(0, shared_ini_file_loader_1.getProfileName)(options)}. Profiles visited: ` + Object.keys(visitedProfiles).join(", "), false); } const sourceCredsProvider = source_profile ? (0, resolveProfileData_1.resolveProfileData)(source_profile, profiles, options, { ...visitedProfiles, [source_profile]: true, }) : (0, resolveCredentialSource_1.resolveCredentialSource)(data.credential_source, profileName)(); const params = { RoleArn: data.role_arn, RoleSessionName: data.role_session_name || `aws-sdk-js-${Date.now()}`, ExternalId: data.external_id, DurationSeconds: parseInt(data.duration_seconds || "3600", 10), }; const { mfa_serial } = data; if (mfa_serial) { if (!options.mfaCodeProvider) { throw new property_provider_1.CredentialsProviderError(`Profile ${profileName} requires multi-factor authentication, but no MFA code callback was provided.`, false); } params.SerialNumber = mfa_serial; params.TokenCode = await options.mfaCodeProvider(mfa_serial); } const sourceCreds = await sourceCredsProvider; return options.roleAssumer(sourceCreds, params); }; exports.resolveAssumeRoleCredentials = resolveAssumeRoleCredentials; /***/ }), /***/ 82458: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveCredentialSource = void 0; const credential_provider_env_1 = __nccwpck_require__(15972); const credential_provider_imds_1 = __nccwpck_require__(7477); const property_provider_1 = __nccwpck_require__(79721); const resolveCredentialSource = (credentialSource, profileName) => { const sourceProvidersMap = { EcsContainer: credential_provider_imds_1.fromContainerMetadata, Ec2InstanceMetadata: credential_provider_imds_1.fromInstanceMetadata, Environment: credential_provider_env_1.fromEnv, }; if (credentialSource in sourceProvidersMap) { return sourceProvidersMap[credentialSource](); } else { throw new property_provider_1.CredentialsProviderError(`Unsupported credential source in profile ${profileName}. Got ${credentialSource}, ` + `expected EcsContainer or Ec2InstanceMetadata or Environment.`); } }; exports.resolveCredentialSource = resolveCredentialSource; /***/ }), /***/ 69993: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveProcessCredentials = exports.isProcessProfile = void 0; const credential_provider_process_1 = __nccwpck_require__(89969); const isProcessProfile = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.credential_process === "string"; exports.isProcessProfile = isProcessProfile; const resolveProcessCredentials = async (options, profile) => (0, credential_provider_process_1.fromProcess)({ ...options, profile, })(); exports.resolveProcessCredentials = resolveProcessCredentials; /***/ }), /***/ 95653: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveProfileData = void 0; const property_provider_1 = __nccwpck_require__(79721); const resolveAssumeRoleCredentials_1 = __nccwpck_require__(60853); const resolveProcessCredentials_1 = __nccwpck_require__(69993); const resolveSsoCredentials_1 = __nccwpck_require__(59867); const resolveStaticCredentials_1 = __nccwpck_require__(33071); const resolveWebIdentityCredentials_1 = __nccwpck_require__(58342); const resolveProfileData = async (profileName, profiles, options, visitedProfiles = {}) => { const data = profiles[profileName]; if (Object.keys(visitedProfiles).length > 0 && (0, resolveStaticCredentials_1.isStaticCredsProfile)(data)) { return (0, resolveStaticCredentials_1.resolveStaticCredentials)(data); } if ((0, resolveAssumeRoleCredentials_1.isAssumeRoleProfile)(data)) { return (0, resolveAssumeRoleCredentials_1.resolveAssumeRoleCredentials)(profileName, profiles, options, visitedProfiles); } if ((0, resolveStaticCredentials_1.isStaticCredsProfile)(data)) { return (0, resolveStaticCredentials_1.resolveStaticCredentials)(data); } if ((0, resolveWebIdentityCredentials_1.isWebIdentityProfile)(data)) { return (0, resolveWebIdentityCredentials_1.resolveWebIdentityCredentials)(data, options); } if ((0, resolveProcessCredentials_1.isProcessProfile)(data)) { return (0, resolveProcessCredentials_1.resolveProcessCredentials)(options, profileName); } if ((0, resolveSsoCredentials_1.isSsoProfile)(data)) { return (0, resolveSsoCredentials_1.resolveSsoCredentials)(data); } throw new property_provider_1.CredentialsProviderError(`Profile ${profileName} could not be found or parsed in shared credentials file.`); }; exports.resolveProfileData = resolveProfileData; /***/ }), /***/ 59867: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveSsoCredentials = exports.isSsoProfile = void 0; const credential_provider_sso_1 = __nccwpck_require__(26414); var credential_provider_sso_2 = __nccwpck_require__(26414); Object.defineProperty(exports, "isSsoProfile", ({ enumerable: true, get: function () { return credential_provider_sso_2.isSsoProfile; } })); const resolveSsoCredentials = (data) => { const { sso_start_url, sso_account_id, sso_session, sso_region, sso_role_name } = (0, credential_provider_sso_1.validateSsoProfile)(data); return (0, credential_provider_sso_1.fromSSO)({ ssoStartUrl: sso_start_url, ssoAccountId: sso_account_id, ssoSession: sso_session, ssoRegion: sso_region, ssoRoleName: sso_role_name, })(); }; exports.resolveSsoCredentials = resolveSsoCredentials; /***/ }), /***/ 33071: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveStaticCredentials = exports.isStaticCredsProfile = void 0; const isStaticCredsProfile = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.aws_access_key_id === "string" && typeof arg.aws_secret_access_key === "string" && ["undefined", "string"].indexOf(typeof arg.aws_session_token) > -1; exports.isStaticCredsProfile = isStaticCredsProfile; const resolveStaticCredentials = (profile) => Promise.resolve({ accessKeyId: profile.aws_access_key_id, secretAccessKey: profile.aws_secret_access_key, sessionToken: profile.aws_session_token, }); exports.resolveStaticCredentials = resolveStaticCredentials; /***/ }), /***/ 58342: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveWebIdentityCredentials = exports.isWebIdentityProfile = void 0; const credential_provider_web_identity_1 = __nccwpck_require__(15646); const isWebIdentityProfile = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.web_identity_token_file === "string" && typeof arg.role_arn === "string" && ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1; exports.isWebIdentityProfile = isWebIdentityProfile; const resolveWebIdentityCredentials = async (profile, options) => (0, credential_provider_web_identity_1.fromTokenFile)({ webIdentityTokenFile: profile.web_identity_token_file, roleArn: profile.role_arn, roleSessionName: profile.role_session_name, roleAssumerWithWebIdentity: options.roleAssumerWithWebIdentity, })(); exports.resolveWebIdentityCredentials = resolveWebIdentityCredentials; /***/ }), /***/ 15560: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.defaultProvider = void 0; const credential_provider_env_1 = __nccwpck_require__(15972); const credential_provider_ini_1 = __nccwpck_require__(74203); const credential_provider_process_1 = __nccwpck_require__(89969); const credential_provider_sso_1 = __nccwpck_require__(26414); const credential_provider_web_identity_1 = __nccwpck_require__(15646); const property_provider_1 = __nccwpck_require__(79721); const shared_ini_file_loader_1 = __nccwpck_require__(43507); const remoteProvider_1 = __nccwpck_require__(50626); const defaultProvider = (init = {}) => (0, property_provider_1.memoize)((0, property_provider_1.chain)(...(init.profile || process.env[shared_ini_file_loader_1.ENV_PROFILE] ? [] : [(0, credential_provider_env_1.fromEnv)()]), (0, credential_provider_sso_1.fromSSO)(init), (0, credential_provider_ini_1.fromIni)(init), (0, credential_provider_process_1.fromProcess)(init), (0, credential_provider_web_identity_1.fromTokenFile)(init), (0, remoteProvider_1.remoteProvider)(init), async () => { throw new property_provider_1.CredentialsProviderError("Could not load credentials from any providers", false); }), (credentials) => credentials.expiration !== undefined && credentials.expiration.getTime() - Date.now() < 300000, (credentials) => credentials.expiration !== undefined); exports.defaultProvider = defaultProvider; /***/ }), /***/ 75531: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(15560), exports); /***/ }), /***/ 50626: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.remoteProvider = exports.ENV_IMDS_DISABLED = void 0; const credential_provider_imds_1 = __nccwpck_require__(7477); const property_provider_1 = __nccwpck_require__(79721); exports.ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; const remoteProvider = (init) => { if (process.env[credential_provider_imds_1.ENV_CMDS_RELATIVE_URI] || process.env[credential_provider_imds_1.ENV_CMDS_FULL_URI]) { return (0, credential_provider_imds_1.fromContainerMetadata)(init); } if (process.env[exports.ENV_IMDS_DISABLED]) { return async () => { throw new property_provider_1.CredentialsProviderError("EC2 Instance Metadata Service access disabled"); }; } return (0, credential_provider_imds_1.fromInstanceMetadata)(init); }; exports.remoteProvider = remoteProvider; /***/ }), /***/ 72650: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fromProcess = void 0; const shared_ini_file_loader_1 = __nccwpck_require__(43507); const resolveProcessCredentials_1 = __nccwpck_require__(74926); const fromProcess = (init = {}) => async () => { const profiles = await (0, shared_ini_file_loader_1.parseKnownFiles)(init); return (0, resolveProcessCredentials_1.resolveProcessCredentials)((0, shared_ini_file_loader_1.getProfileName)(init), profiles); }; exports.fromProcess = fromProcess; /***/ }), /***/ 41104: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getValidatedProcessCredentials = void 0; const getValidatedProcessCredentials = (profileName, data) => { if (data.Version !== 1) { throw Error(`Profile ${profileName} credential_process did not return Version 1.`); } if (data.AccessKeyId === undefined || data.SecretAccessKey === undefined) { throw Error(`Profile ${profileName} credential_process returned invalid credentials.`); } if (data.Expiration) { const currentTime = new Date(); const expireTime = new Date(data.Expiration); if (expireTime < currentTime) { throw Error(`Profile ${profileName} credential_process returned expired credentials.`); } } return { accessKeyId: data.AccessKeyId, secretAccessKey: data.SecretAccessKey, ...(data.SessionToken && { sessionToken: data.SessionToken }), ...(data.Expiration && { expiration: new Date(data.Expiration) }), }; }; exports.getValidatedProcessCredentials = getValidatedProcessCredentials; /***/ }), /***/ 89969: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(72650), exports); /***/ }), /***/ 74926: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveProcessCredentials = void 0; const property_provider_1 = __nccwpck_require__(79721); const child_process_1 = __nccwpck_require__(32081); const util_1 = __nccwpck_require__(73837); const getValidatedProcessCredentials_1 = __nccwpck_require__(41104); const resolveProcessCredentials = async (profileName, profiles) => { const profile = profiles[profileName]; if (profiles[profileName]) { const credentialProcess = profile["credential_process"]; if (credentialProcess !== undefined) { const execPromise = (0, util_1.promisify)(child_process_1.exec); try { const { stdout } = await execPromise(credentialProcess); let data; try { data = JSON.parse(stdout.trim()); } catch (_a) { throw Error(`Profile ${profileName} credential_process returned invalid JSON.`); } return (0, getValidatedProcessCredentials_1.getValidatedProcessCredentials)(profileName, data); } catch (error) { throw new property_provider_1.CredentialsProviderError(error.message); } } else { throw new property_provider_1.CredentialsProviderError(`Profile ${profileName} did not contain credential_process.`); } } else { throw new property_provider_1.CredentialsProviderError(`Profile ${profileName} could not be found in shared credentials file.`); } }; exports.resolveProcessCredentials = resolveProcessCredentials; /***/ }), /***/ 35959: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fromSSO = void 0; const property_provider_1 = __nccwpck_require__(79721); const shared_ini_file_loader_1 = __nccwpck_require__(43507); const isSsoProfile_1 = __nccwpck_require__(32572); const resolveSSOCredentials_1 = __nccwpck_require__(94729); const validateSsoProfile_1 = __nccwpck_require__(48098); const fromSSO = (init = {}) => async () => { const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoClient, ssoSession } = init; const profileName = (0, shared_ini_file_loader_1.getProfileName)(init); if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { const profiles = await (0, shared_ini_file_loader_1.parseKnownFiles)(init); const profile = profiles[profileName]; if (!profile) { throw new property_provider_1.CredentialsProviderError(`Profile ${profileName} was not found.`); } if (!(0, isSsoProfile_1.isSsoProfile)(profile)) { throw new property_provider_1.CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`); } if (profile === null || profile === void 0 ? void 0 : profile.sso_session) { const ssoSessions = await (0, shared_ini_file_loader_1.loadSsoSessionData)(init); const session = ssoSessions[profile.sso_session]; const conflictMsg = ` configurations in profile ${profileName} and sso-session ${profile.sso_session}`; if (ssoRegion && ssoRegion !== session.sso_region) { throw new property_provider_1.CredentialsProviderError(`Conflicting SSO region` + conflictMsg, false); } if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) { throw new property_provider_1.CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, false); } profile.sso_region = session.sso_region; profile.sso_start_url = session.sso_start_url; } const { sso_start_url, sso_account_id, sso_region, sso_role_name, sso_session } = (0, validateSsoProfile_1.validateSsoProfile)(profile); return (0, resolveSSOCredentials_1.resolveSSOCredentials)({ ssoStartUrl: sso_start_url, ssoSession: sso_session, ssoAccountId: sso_account_id, ssoRegion: sso_region, ssoRoleName: sso_role_name, ssoClient: ssoClient, profile: profileName, }); } else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) { throw new property_provider_1.CredentialsProviderError("Incomplete configuration. The fromSSO() argument hash must include " + '"ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"'); } else { return (0, resolveSSOCredentials_1.resolveSSOCredentials)({ ssoStartUrl, ssoSession, ssoAccountId, ssoRegion, ssoRoleName, ssoClient, profile: profileName, }); } }; exports.fromSSO = fromSSO; /***/ }), /***/ 26414: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(35959), exports); tslib_1.__exportStar(__nccwpck_require__(32572), exports); tslib_1.__exportStar(__nccwpck_require__(86623), exports); tslib_1.__exportStar(__nccwpck_require__(48098), exports); /***/ }), /***/ 32572: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isSsoProfile = void 0; const isSsoProfile = (arg) => arg && (typeof arg.sso_start_url === "string" || typeof arg.sso_account_id === "string" || typeof arg.sso_session === "string" || typeof arg.sso_region === "string" || typeof arg.sso_role_name === "string"); exports.isSsoProfile = isSsoProfile; /***/ }), /***/ 94729: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveSSOCredentials = void 0; const client_sso_1 = __nccwpck_require__(82666); const token_providers_1 = __nccwpck_require__(52843); const property_provider_1 = __nccwpck_require__(79721); const shared_ini_file_loader_1 = __nccwpck_require__(43507); const SHOULD_FAIL_CREDENTIAL_CHAIN = false; const resolveSSOCredentials = async ({ ssoStartUrl, ssoSession, ssoAccountId, ssoRegion, ssoRoleName, ssoClient, profile, }) => { let token; const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`; if (ssoSession) { try { const _token = await (0, token_providers_1.fromSso)({ profile })(); token = { accessToken: _token.token, expiresAt: new Date(_token.expiration).toISOString(), }; } catch (e) { throw new property_provider_1.CredentialsProviderError(e.message, SHOULD_FAIL_CREDENTIAL_CHAIN); } } else { try { token = await (0, shared_ini_file_loader_1.getSSOTokenFromFile)(ssoStartUrl); } catch (e) { throw new property_provider_1.CredentialsProviderError(`The SSO session associated with this profile is invalid. ${refreshMessage}`, SHOULD_FAIL_CREDENTIAL_CHAIN); } } if (new Date(token.expiresAt).getTime() - Date.now() <= 0) { throw new property_provider_1.CredentialsProviderError(`The SSO session associated with this profile has expired. ${refreshMessage}`, SHOULD_FAIL_CREDENTIAL_CHAIN); } const { accessToken } = token; const sso = ssoClient || new client_sso_1.SSOClient({ region: ssoRegion }); let ssoResp; try { ssoResp = await sso.send(new client_sso_1.GetRoleCredentialsCommand({ accountId: ssoAccountId, roleName: ssoRoleName, accessToken, })); } catch (e) { throw property_provider_1.CredentialsProviderError.from(e, SHOULD_FAIL_CREDENTIAL_CHAIN); } const { roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration } = {} } = ssoResp; if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) { throw new property_provider_1.CredentialsProviderError("SSO returns an invalid temporary credential.", SHOULD_FAIL_CREDENTIAL_CHAIN); } return { accessKeyId, secretAccessKey, sessionToken, expiration: new Date(expiration) }; }; exports.resolveSSOCredentials = resolveSSOCredentials; /***/ }), /***/ 86623: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 48098: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.validateSsoProfile = void 0; const property_provider_1 = __nccwpck_require__(79721); const validateSsoProfile = (profile) => { const { sso_start_url, sso_account_id, sso_region, sso_role_name } = profile; if (!sso_start_url || !sso_account_id || !sso_region || !sso_role_name) { throw new property_provider_1.CredentialsProviderError(`Profile is configured with invalid SSO credentials. Required parameters "sso_account_id", ` + `"sso_region", "sso_role_name", "sso_start_url". Got ${Object.keys(profile).join(", ")}\nReference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, false); } return profile; }; exports.validateSsoProfile = validateSsoProfile; /***/ }), /***/ 35614: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fromTokenFile = void 0; const property_provider_1 = __nccwpck_require__(79721); const fs_1 = __nccwpck_require__(57147); const fromWebToken_1 = __nccwpck_require__(47905); const ENV_TOKEN_FILE = "AWS_WEB_IDENTITY_TOKEN_FILE"; const ENV_ROLE_ARN = "AWS_ROLE_ARN"; const ENV_ROLE_SESSION_NAME = "AWS_ROLE_SESSION_NAME"; const fromTokenFile = (init = {}) => async () => { var _a, _b, _c; const webIdentityTokenFile = (_a = init === null || init === void 0 ? void 0 : init.webIdentityTokenFile) !== null && _a !== void 0 ? _a : process.env[ENV_TOKEN_FILE]; const roleArn = (_b = init === null || init === void 0 ? void 0 : init.roleArn) !== null && _b !== void 0 ? _b : process.env[ENV_ROLE_ARN]; const roleSessionName = (_c = init === null || init === void 0 ? void 0 : init.roleSessionName) !== null && _c !== void 0 ? _c : process.env[ENV_ROLE_SESSION_NAME]; if (!webIdentityTokenFile || !roleArn) { throw new property_provider_1.CredentialsProviderError("Web identity configuration not specified"); } return (0, fromWebToken_1.fromWebToken)({ ...init, webIdentityToken: (0, fs_1.readFileSync)(webIdentityTokenFile, { encoding: "ascii" }), roleArn, roleSessionName, })(); }; exports.fromTokenFile = fromTokenFile; /***/ }), /***/ 47905: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fromWebToken = void 0; const property_provider_1 = __nccwpck_require__(79721); const fromWebToken = (init) => () => { const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy, durationSeconds, roleAssumerWithWebIdentity, } = init; if (!roleAssumerWithWebIdentity) { throw new property_provider_1.CredentialsProviderError(`Role Arn '${roleArn}' needs to be assumed with web identity,` + ` but no role assumption callback was provided.`, false); } return roleAssumerWithWebIdentity({ RoleArn: roleArn, RoleSessionName: roleSessionName !== null && roleSessionName !== void 0 ? roleSessionName : `aws-sdk-js-session-${Date.now()}`, WebIdentityToken: webIdentityToken, ProviderId: providerId, PolicyArns: policyArns, Policy: policy, DurationSeconds: durationSeconds, }); }; exports.fromWebToken = fromWebToken; /***/ }), /***/ 15646: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(35614), exports); tslib_1.__exportStar(__nccwpck_require__(47905), exports); /***/ }), /***/ 22545: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getHostHeaderPlugin = exports.hostHeaderMiddlewareOptions = exports.hostHeaderMiddleware = exports.resolveHostHeaderConfig = void 0; const protocol_http_1 = __nccwpck_require__(64418); function resolveHostHeaderConfig(input) { return input; } exports.resolveHostHeaderConfig = resolveHostHeaderConfig; const hostHeaderMiddleware = (options) => (next) => async (args) => { if (!protocol_http_1.HttpRequest.isInstance(args.request)) return next(args); const { request } = args; const { handlerProtocol = "" } = options.requestHandler.metadata || {}; if (handlerProtocol.indexOf("h2") >= 0 && !request.headers[":authority"]) { delete request.headers["host"]; request.headers[":authority"] = request.hostname + (request.port ? ":" + request.port : ""); } else if (!request.headers["host"]) { let host = request.hostname; if (request.port != null) host += `:${request.port}`; request.headers["host"] = host; } return next(args); }; exports.hostHeaderMiddleware = hostHeaderMiddleware; exports.hostHeaderMiddlewareOptions = { name: "hostHeaderMiddleware", step: "build", priority: "low", tags: ["HOST"], override: true, }; const getHostHeaderPlugin = (options) => ({ applyToStack: (clientStack) => { clientStack.add((0, exports.hostHeaderMiddleware)(options), exports.hostHeaderMiddlewareOptions); }, }); exports.getHostHeaderPlugin = getHostHeaderPlugin; /***/ }), /***/ 20014: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(9754), exports); /***/ }), /***/ 9754: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getLoggerPlugin = exports.loggerMiddlewareOptions = exports.loggerMiddleware = void 0; const loggerMiddleware = () => (next, context) => async (args) => { var _a, _b; try { const response = await next(args); const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context; const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions; const inputFilterSensitiveLog = overrideInputFilterSensitiveLog !== null && overrideInputFilterSensitiveLog !== void 0 ? overrideInputFilterSensitiveLog : context.inputFilterSensitiveLog; const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog !== null && overrideOutputFilterSensitiveLog !== void 0 ? overrideOutputFilterSensitiveLog : context.outputFilterSensitiveLog; const { $metadata, ...outputWithoutMetadata } = response.output; (_a = logger === null || logger === void 0 ? void 0 : logger.info) === null || _a === void 0 ? void 0 : _a.call(logger, { clientName, commandName, input: inputFilterSensitiveLog(args.input), output: outputFilterSensitiveLog(outputWithoutMetadata), metadata: $metadata, }); return response; } catch (error) { const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context; const { overrideInputFilterSensitiveLog } = dynamoDbDocumentClientOptions; const inputFilterSensitiveLog = overrideInputFilterSensitiveLog !== null && overrideInputFilterSensitiveLog !== void 0 ? overrideInputFilterSensitiveLog : context.inputFilterSensitiveLog; (_b = logger === null || logger === void 0 ? void 0 : logger.error) === null || _b === void 0 ? void 0 : _b.call(logger, { clientName, commandName, input: inputFilterSensitiveLog(args.input), error, metadata: error.$metadata, }); throw error; } }; exports.loggerMiddleware = loggerMiddleware; exports.loggerMiddlewareOptions = { name: "loggerMiddleware", tags: ["LOGGER"], step: "initialize", override: true, }; const getLoggerPlugin = (options) => ({ applyToStack: (clientStack) => { clientStack.add((0, exports.loggerMiddleware)(), exports.loggerMiddlewareOptions); }, }); exports.getLoggerPlugin = getLoggerPlugin; /***/ }), /***/ 85525: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getRecursionDetectionPlugin = exports.addRecursionDetectionMiddlewareOptions = exports.recursionDetectionMiddleware = void 0; const protocol_http_1 = __nccwpck_require__(64418); const TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id"; const ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME"; const ENV_TRACE_ID = "_X_AMZN_TRACE_ID"; const recursionDetectionMiddleware = (options) => (next) => async (args) => { const { request } = args; if (!protocol_http_1.HttpRequest.isInstance(request) || options.runtime !== "node" || request.headers.hasOwnProperty(TRACE_ID_HEADER_NAME)) { return next(args); } const functionName = process.env[ENV_LAMBDA_FUNCTION_NAME]; const traceId = process.env[ENV_TRACE_ID]; const nonEmptyString = (str) => typeof str === "string" && str.length > 0; if (nonEmptyString(functionName) && nonEmptyString(traceId)) { request.headers[TRACE_ID_HEADER_NAME] = traceId; } return next({ ...args, request, }); }; exports.recursionDetectionMiddleware = recursionDetectionMiddleware; exports.addRecursionDetectionMiddlewareOptions = { step: "build", tags: ["RECURSION_DETECTION"], name: "recursionDetectionMiddleware", override: true, priority: "low", }; const getRecursionDetectionPlugin = (options) => ({ applyToStack: (clientStack) => { clientStack.add((0, exports.recursionDetectionMiddleware)(options), exports.addRecursionDetectionMiddlewareOptions); }, }); exports.getRecursionDetectionPlugin = getRecursionDetectionPlugin; /***/ }), /***/ 55959: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveStsAuthConfig = void 0; const middleware_signing_1 = __nccwpck_require__(14935); const resolveStsAuthConfig = (input, { stsClientCtor }) => (0, middleware_signing_1.resolveAwsAuthConfig)({ ...input, stsClientCtor, }); exports.resolveStsAuthConfig = resolveStsAuthConfig; /***/ }), /***/ 84193: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveSigV4AuthConfig = exports.resolveAwsAuthConfig = void 0; const property_provider_1 = __nccwpck_require__(79721); const signature_v4_1 = __nccwpck_require__(11528); const util_middleware_1 = __nccwpck_require__(2390); const CREDENTIAL_EXPIRE_WINDOW = 300000; const resolveAwsAuthConfig = (input) => { const normalizedCreds = input.credentials ? normalizeCredentialProvider(input.credentials) : input.credentialDefaultProvider(input); const { signingEscapePath = true, systemClockOffset = input.systemClockOffset || 0, sha256 } = input; let signer; if (input.signer) { signer = (0, util_middleware_1.normalizeProvider)(input.signer); } else if (input.regionInfoProvider) { signer = () => (0, util_middleware_1.normalizeProvider)(input.region)() .then(async (region) => [ (await input.regionInfoProvider(region, { useFipsEndpoint: await input.useFipsEndpoint(), useDualstackEndpoint: await input.useDualstackEndpoint(), })) || {}, region, ]) .then(([regionInfo, region]) => { const { signingRegion, signingService } = regionInfo; input.signingRegion = input.signingRegion || signingRegion || region; input.signingName = input.signingName || signingService || input.serviceId; const params = { ...input, credentials: normalizedCreds, region: input.signingRegion, service: input.signingName, sha256, uriEscapePath: signingEscapePath, }; const SignerCtor = input.signerConstructor || signature_v4_1.SignatureV4; return new SignerCtor(params); }); } else { signer = async (authScheme) => { authScheme = Object.assign({}, { name: "sigv4", signingName: input.signingName || input.defaultSigningName, signingRegion: await (0, util_middleware_1.normalizeProvider)(input.region)(), properties: {}, }, authScheme); const signingRegion = authScheme.signingRegion; const signingService = authScheme.signingName; input.signingRegion = input.signingRegion || signingRegion; input.signingName = input.signingName || signingService || input.serviceId; const params = { ...input, credentials: normalizedCreds, region: input.signingRegion, service: input.signingName, sha256, uriEscapePath: signingEscapePath, }; const SignerCtor = input.signerConstructor || signature_v4_1.SignatureV4; return new SignerCtor(params); }; } return { ...input, systemClockOffset, signingEscapePath, credentials: normalizedCreds, signer, }; }; exports.resolveAwsAuthConfig = resolveAwsAuthConfig; const resolveSigV4AuthConfig = (input) => { const normalizedCreds = input.credentials ? normalizeCredentialProvider(input.credentials) : input.credentialDefaultProvider(input); const { signingEscapePath = true, systemClockOffset = input.systemClockOffset || 0, sha256 } = input; let signer; if (input.signer) { signer = (0, util_middleware_1.normalizeProvider)(input.signer); } else { signer = (0, util_middleware_1.normalizeProvider)(new signature_v4_1.SignatureV4({ credentials: normalizedCreds, region: input.region, service: input.signingName, sha256, uriEscapePath: signingEscapePath, })); } return { ...input, systemClockOffset, signingEscapePath, credentials: normalizedCreds, signer, }; }; exports.resolveSigV4AuthConfig = resolveSigV4AuthConfig; const normalizeCredentialProvider = (credentials) => { if (typeof credentials === "function") { return (0, property_provider_1.memoize)(credentials, (credentials) => credentials.expiration !== undefined && credentials.expiration.getTime() - Date.now() < CREDENTIAL_EXPIRE_WINDOW, (credentials) => credentials.expiration !== undefined); } return (0, util_middleware_1.normalizeProvider)(credentials); }; /***/ }), /***/ 88053: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getSigV4AuthPlugin = exports.getAwsAuthPlugin = exports.awsAuthMiddlewareOptions = exports.awsAuthMiddleware = void 0; const protocol_http_1 = __nccwpck_require__(64418); const getSkewCorrectedDate_1 = __nccwpck_require__(68253); const getUpdatedSystemClockOffset_1 = __nccwpck_require__(35863); const awsAuthMiddleware = (options) => (next, context) => async function (args) { var _a, _b, _c, _d; if (!protocol_http_1.HttpRequest.isInstance(args.request)) return next(args); const authScheme = (_c = (_b = (_a = context.endpointV2) === null || _a === void 0 ? void 0 : _a.properties) === null || _b === void 0 ? void 0 : _b.authSchemes) === null || _c === void 0 ? void 0 : _c[0]; const multiRegionOverride = (authScheme === null || authScheme === void 0 ? void 0 : authScheme.name) === "sigv4a" ? (_d = authScheme === null || authScheme === void 0 ? void 0 : authScheme.signingRegionSet) === null || _d === void 0 ? void 0 : _d.join(",") : undefined; const signer = await options.signer(authScheme); const output = await next({ ...args, request: await signer.sign(args.request, { signingDate: (0, getSkewCorrectedDate_1.getSkewCorrectedDate)(options.systemClockOffset), signingRegion: multiRegionOverride || context["signing_region"], signingService: context["signing_service"], }), }).catch((error) => { var _a; const serverTime = (_a = error.ServerTime) !== null && _a !== void 0 ? _a : getDateHeader(error.$response); if (serverTime) { options.systemClockOffset = (0, getUpdatedSystemClockOffset_1.getUpdatedSystemClockOffset)(serverTime, options.systemClockOffset); } throw error; }); const dateHeader = getDateHeader(output.response); if (dateHeader) { options.systemClockOffset = (0, getUpdatedSystemClockOffset_1.getUpdatedSystemClockOffset)(dateHeader, options.systemClockOffset); } return output; }; exports.awsAuthMiddleware = awsAuthMiddleware; const getDateHeader = (response) => { var _a, _b, _c; return protocol_http_1.HttpResponse.isInstance(response) ? (_b = (_a = response.headers) === null || _a === void 0 ? void 0 : _a.date) !== null && _b !== void 0 ? _b : (_c = response.headers) === null || _c === void 0 ? void 0 : _c.Date : undefined; }; exports.awsAuthMiddlewareOptions = { name: "awsAuthMiddleware", tags: ["SIGNATURE", "AWSAUTH"], relation: "after", toMiddleware: "retryMiddleware", override: true, }; const getAwsAuthPlugin = (options) => ({ applyToStack: (clientStack) => { clientStack.addRelativeTo((0, exports.awsAuthMiddleware)(options), exports.awsAuthMiddlewareOptions); }, }); exports.getAwsAuthPlugin = getAwsAuthPlugin; exports.getSigV4AuthPlugin = exports.getAwsAuthPlugin; /***/ }), /***/ 14935: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(84193), exports); tslib_1.__exportStar(__nccwpck_require__(88053), exports); /***/ }), /***/ 68253: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getSkewCorrectedDate = void 0; const getSkewCorrectedDate = (systemClockOffset) => new Date(Date.now() + systemClockOffset); exports.getSkewCorrectedDate = getSkewCorrectedDate; /***/ }), /***/ 35863: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getUpdatedSystemClockOffset = void 0; const isClockSkewed_1 = __nccwpck_require__(85301); const getUpdatedSystemClockOffset = (clockTime, currentSystemClockOffset) => { const clockTimeInMs = Date.parse(clockTime); if ((0, isClockSkewed_1.isClockSkewed)(clockTimeInMs, currentSystemClockOffset)) { return clockTimeInMs - Date.now(); } return currentSystemClockOffset; }; exports.getUpdatedSystemClockOffset = getUpdatedSystemClockOffset; /***/ }), /***/ 85301: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isClockSkewed = void 0; const getSkewCorrectedDate_1 = __nccwpck_require__(68253); const isClockSkewed = (clockTime, systemClockOffset) => Math.abs((0, getSkewCorrectedDate_1.getSkewCorrectedDate)(systemClockOffset).getTime() - clockTime) >= 300000; exports.isClockSkewed = isClockSkewed; /***/ }), /***/ 36546: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveUserAgentConfig = void 0; function resolveUserAgentConfig(input) { return { ...input, customUserAgent: typeof input.customUserAgent === "string" ? [[input.customUserAgent]] : input.customUserAgent, }; } exports.resolveUserAgentConfig = resolveUserAgentConfig; /***/ }), /***/ 28025: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UA_ESCAPE_CHAR = exports.UA_VALUE_ESCAPE_REGEX = exports.UA_NAME_ESCAPE_REGEX = exports.UA_NAME_SEPARATOR = exports.SPACE = exports.X_AMZ_USER_AGENT = exports.USER_AGENT = void 0; exports.USER_AGENT = "user-agent"; exports.X_AMZ_USER_AGENT = "x-amz-user-agent"; exports.SPACE = " "; exports.UA_NAME_SEPARATOR = "/"; exports.UA_NAME_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g; exports.UA_VALUE_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g; exports.UA_ESCAPE_CHAR = "-"; /***/ }), /***/ 64688: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(36546), exports); tslib_1.__exportStar(__nccwpck_require__(76236), exports); /***/ }), /***/ 76236: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getUserAgentPlugin = exports.getUserAgentMiddlewareOptions = exports.userAgentMiddleware = void 0; const util_endpoints_1 = __nccwpck_require__(13350); const protocol_http_1 = __nccwpck_require__(64418); const constants_1 = __nccwpck_require__(28025); const userAgentMiddleware = (options) => (next, context) => async (args) => { var _a, _b; const { request } = args; if (!protocol_http_1.HttpRequest.isInstance(request)) return next(args); const { headers } = request; const userAgent = ((_a = context === null || context === void 0 ? void 0 : context.userAgent) === null || _a === void 0 ? void 0 : _a.map(escapeUserAgent)) || []; const defaultUserAgent = (await options.defaultUserAgentProvider()).map(escapeUserAgent); const customUserAgent = ((_b = options === null || options === void 0 ? void 0 : options.customUserAgent) === null || _b === void 0 ? void 0 : _b.map(escapeUserAgent)) || []; const prefix = (0, util_endpoints_1.getUserAgentPrefix)(); const sdkUserAgentValue = (prefix ? [prefix] : []) .concat([...defaultUserAgent, ...userAgent, ...customUserAgent]) .join(constants_1.SPACE); const normalUAValue = [ ...defaultUserAgent.filter((section) => section.startsWith("aws-sdk-")), ...customUserAgent, ].join(constants_1.SPACE); if (options.runtime !== "browser") { if (normalUAValue) { headers[constants_1.X_AMZ_USER_AGENT] = headers[constants_1.X_AMZ_USER_AGENT] ? `${headers[constants_1.USER_AGENT]} ${normalUAValue}` : normalUAValue; } headers[constants_1.USER_AGENT] = sdkUserAgentValue; } else { headers[constants_1.X_AMZ_USER_AGENT] = sdkUserAgentValue; } return next({ ...args, request, }); }; exports.userAgentMiddleware = userAgentMiddleware; const escapeUserAgent = (userAgentPair) => { var _a; const name = userAgentPair[0] .split(constants_1.UA_NAME_SEPARATOR) .map((part) => part.replace(constants_1.UA_NAME_ESCAPE_REGEX, constants_1.UA_ESCAPE_CHAR)) .join(constants_1.UA_NAME_SEPARATOR); const version = (_a = userAgentPair[1]) === null || _a === void 0 ? void 0 : _a.replace(constants_1.UA_VALUE_ESCAPE_REGEX, constants_1.UA_ESCAPE_CHAR); const prefixSeparatorIndex = name.indexOf(constants_1.UA_NAME_SEPARATOR); const prefix = name.substring(0, prefixSeparatorIndex); let uaName = name.substring(prefixSeparatorIndex + 1); if (prefix === "api") { uaName = uaName.toLowerCase(); } return [prefix, uaName, version] .filter((item) => item && item.length > 0) .reduce((acc, item, index) => { switch (index) { case 0: return item; case 1: return `${acc}/${item}`; default: return `${acc}#${item}`; } }, ""); }; exports.getUserAgentMiddlewareOptions = { name: "getUserAgentMiddleware", step: "build", priority: "low", tags: ["SET_USER_AGENT", "USER_AGENT"], override: true, }; const getUserAgentPlugin = (config) => ({ applyToStack: (clientStack) => { clientStack.add((0, exports.userAgentMiddleware)(config), exports.getUserAgentMiddlewareOptions); }, }); exports.getUserAgentPlugin = getUserAgentPlugin; /***/ }), /***/ 60079: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveAwsRegionExtensionConfiguration = exports.getAwsRegionExtensionConfiguration = void 0; const getAwsRegionExtensionConfiguration = (runtimeConfig) => { let runtimeConfigRegion = async () => { if (runtimeConfig.region === undefined) { throw new Error("Region is missing from runtimeConfig"); } const region = runtimeConfig.region; if (typeof region === "string") { return region; } return region(); }; return { setRegion(region) { runtimeConfigRegion = region; }, region() { return runtimeConfigRegion; }, }; }; exports.getAwsRegionExtensionConfiguration = getAwsRegionExtensionConfiguration; const resolveAwsRegionExtensionConfiguration = (awsRegionExtensionConfiguration) => { return { region: awsRegionExtensionConfiguration.region(), }; }; exports.resolveAwsRegionExtensionConfiguration = resolveAwsRegionExtensionConfiguration; /***/ }), /***/ 18156: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(60079), exports); tslib_1.__exportStar(__nccwpck_require__(17177), exports); /***/ }), /***/ 60123: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NODE_REGION_CONFIG_FILE_OPTIONS = exports.NODE_REGION_CONFIG_OPTIONS = exports.REGION_INI_NAME = exports.REGION_ENV_NAME = void 0; exports.REGION_ENV_NAME = "AWS_REGION"; exports.REGION_INI_NAME = "region"; exports.NODE_REGION_CONFIG_OPTIONS = { environmentVariableSelector: (env) => env[exports.REGION_ENV_NAME], configFileSelector: (profile) => profile[exports.REGION_INI_NAME], default: () => { throw new Error("Region is missing"); }, }; exports.NODE_REGION_CONFIG_FILE_OPTIONS = { preferredFile: "credentials", }; /***/ }), /***/ 30048: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getRealRegion = void 0; const isFipsRegion_1 = __nccwpck_require__(37257); const getRealRegion = (region) => (0, isFipsRegion_1.isFipsRegion)(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region; exports.getRealRegion = getRealRegion; /***/ }), /***/ 17177: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(60123), exports); tslib_1.__exportStar(__nccwpck_require__(46187), exports); /***/ }), /***/ 37257: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isFipsRegion = void 0; const isFipsRegion = (region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")); exports.isFipsRegion = isFipsRegion; /***/ }), /***/ 46187: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveRegionConfig = void 0; const getRealRegion_1 = __nccwpck_require__(30048); const isFipsRegion_1 = __nccwpck_require__(37257); const resolveRegionConfig = (input) => { const { region, useFipsEndpoint } = input; if (!region) { throw new Error("Region is missing"); } return { ...input, region: async () => { if (typeof region === "string") { return (0, getRealRegion_1.getRealRegion)(region); } const providedRegion = await region(); return (0, getRealRegion_1.getRealRegion)(providedRegion); }, useFipsEndpoint: async () => { const providedRegion = typeof region === "string" ? region : await region(); if ((0, isFipsRegion_1.isFipsRegion)(providedRegion)) { return true; } return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint(); }, }; }; exports.resolveRegionConfig = resolveRegionConfig; /***/ }), /***/ 52664: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UnsupportedGrantTypeException = exports.UnauthorizedClientException = exports.SlowDownException = exports.SSOOIDCClient = exports.InvalidScopeException = exports.InvalidRequestException = exports.InvalidClientException = exports.InternalServerException = exports.ExpiredTokenException = exports.CreateTokenCommand = exports.AuthorizationPendingException = exports.AccessDeniedException = void 0; const middleware_host_header_1 = __nccwpck_require__(22545); const middleware_logger_1 = __nccwpck_require__(20014); const middleware_recursion_detection_1 = __nccwpck_require__(85525); const middleware_user_agent_1 = __nccwpck_require__(64688); const config_resolver_1 = __nccwpck_require__(53098); const middleware_content_length_1 = __nccwpck_require__(82800); const middleware_endpoint_1 = __nccwpck_require__(82918); const middleware_retry_1 = __nccwpck_require__(96039); const smithy_client_1 = __nccwpck_require__(63570); var resolveClientEndpointParameters = (options) => { var _a, _b; return { ...options, useDualstackEndpoint: (_a = options.useDualstackEndpoint) !== null && _a !== void 0 ? _a : false, useFipsEndpoint: (_b = options.useFipsEndpoint) !== null && _b !== void 0 ? _b : false, defaultSigningName: "awsssooidc", }; }; var package_default = { version: "3.429.0" }; const util_user_agent_node_1 = __nccwpck_require__(98095); const config_resolver_2 = __nccwpck_require__(53098); const hash_node_1 = __nccwpck_require__(3081); const middleware_retry_2 = __nccwpck_require__(96039); const node_config_provider_1 = __nccwpck_require__(33461); const node_http_handler_1 = __nccwpck_require__(20258); const util_body_length_node_1 = __nccwpck_require__(68075); const util_retry_1 = __nccwpck_require__(84902); const smithy_client_2 = __nccwpck_require__(63570); const url_parser_1 = __nccwpck_require__(14681); const util_base64_1 = __nccwpck_require__(75600); const util_utf8_1 = __nccwpck_require__(41895); const util_endpoints_1 = __nccwpck_require__(45473); var s = "required"; var t = "fn"; var u = "argv"; var v = "ref"; var a = "isSet"; var b = "tree"; var c = "error"; var d = "endpoint"; var e = "PartitionResult"; var f = "getAttr"; var g = { [s]: false, type: "String" }; var h = { [s]: true, default: false, type: "Boolean" }; var i = { [v]: "Endpoint" }; var j = { [t]: "booleanEquals", [u]: [{ [v]: "UseFIPS" }, true] }; var k = { [t]: "booleanEquals", [u]: [{ [v]: "UseDualStack" }, true] }; var l = {}; var m = { [t]: "booleanEquals", [u]: [true, { [t]: f, [u]: [{ [v]: e }, "supportsFIPS"] }] }; var n = { [v]: e }; var o = { [t]: "booleanEquals", [u]: [true, { [t]: f, [u]: [n, "supportsDualStack"] }] }; var p = [j]; var q = [k]; var r = [{ [v]: "Region" }]; var _data = { version: "1.0", parameters: { Region: g, UseDualStack: h, UseFIPS: h, Endpoint: g }, rules: [ { conditions: [{ [t]: a, [u]: [i] }], type: b, rules: [ { conditions: p, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: c }, { conditions: q, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: c }, { endpoint: { url: i, properties: l, headers: l }, type: d }, ], }, { conditions: [{ [t]: a, [u]: r }], type: b, rules: [ { conditions: [{ [t]: "aws.partition", [u]: r, assign: e }], type: b, rules: [ { conditions: [j, k], type: b, rules: [ { conditions: [m, o], type: b, rules: [ { endpoint: { url: "https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: l, headers: l, }, type: d, }, ], }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: c }, ], }, { conditions: p, type: b, rules: [ { conditions: [m], type: b, rules: [ { conditions: [{ [t]: "stringEquals", [u]: ["aws-us-gov", { [t]: f, [u]: [n, "name"] }] }], endpoint: { url: "https://oidc.{Region}.amazonaws.com", properties: l, headers: l }, type: d, }, { endpoint: { url: "https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}", properties: l, headers: l, }, type: d, }, ], }, { error: "FIPS is enabled but this partition does not support FIPS", type: c }, ], }, { conditions: q, type: b, rules: [ { conditions: [o], type: b, rules: [ { endpoint: { url: "https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: l, headers: l, }, type: d, }, ], }, { error: "DualStack is enabled but this partition does not support DualStack", type: c }, ], }, { endpoint: { url: "https://oidc.{Region}.{PartitionResult#dnsSuffix}", properties: l, headers: l }, type: d, }, ], }, ], }, { error: "Invalid Configuration: Missing Region", type: c }, ], }; var ruleSet = _data; var defaultEndpointResolver = (endpointParams, context = {}) => { return (0, util_endpoints_1.resolveEndpoint)(ruleSet, { endpointParams, logger: context.logger, }); }; var getRuntimeConfig = (config) => { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; return ({ apiVersion: "2019-06-10", base64Decoder: (_a = config === null || config === void 0 ? void 0 : config.base64Decoder) !== null && _a !== void 0 ? _a : util_base64_1.fromBase64, base64Encoder: (_b = config === null || config === void 0 ? void 0 : config.base64Encoder) !== null && _b !== void 0 ? _b : util_base64_1.toBase64, disableHostPrefix: (_c = config === null || config === void 0 ? void 0 : config.disableHostPrefix) !== null && _c !== void 0 ? _c : false, endpointProvider: (_d = config === null || config === void 0 ? void 0 : config.endpointProvider) !== null && _d !== void 0 ? _d : defaultEndpointResolver, extensions: (_e = config === null || config === void 0 ? void 0 : config.extensions) !== null && _e !== void 0 ? _e : [], logger: (_f = config === null || config === void 0 ? void 0 : config.logger) !== null && _f !== void 0 ? _f : new smithy_client_2.NoOpLogger(), serviceId: (_g = config === null || config === void 0 ? void 0 : config.serviceId) !== null && _g !== void 0 ? _g : "SSO OIDC", urlParser: (_h = config === null || config === void 0 ? void 0 : config.urlParser) !== null && _h !== void 0 ? _h : url_parser_1.parseUrl, utf8Decoder: (_j = config === null || config === void 0 ? void 0 : config.utf8Decoder) !== null && _j !== void 0 ? _j : util_utf8_1.fromUtf8, utf8Encoder: (_k = config === null || config === void 0 ? void 0 : config.utf8Encoder) !== null && _k !== void 0 ? _k : util_utf8_1.toUtf8, }); }; const smithy_client_3 = __nccwpck_require__(63570); const util_defaults_mode_node_1 = __nccwpck_require__(72429); const smithy_client_4 = __nccwpck_require__(63570); var getRuntimeConfig2 = (config) => { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; (0, smithy_client_4.emitWarningIfUnsupportedVersion)(process.version); const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config); const defaultConfigProvider = () => defaultsMode().then(smithy_client_3.loadConfigsForDefaultMode); const clientSharedValues = getRuntimeConfig(config); return { ...clientSharedValues, ...config, runtime: "node", defaultsMode, bodyLengthChecker: (_a = config === null || config === void 0 ? void 0 : config.bodyLengthChecker) !== null && _a !== void 0 ? _a : util_body_length_node_1.calculateBodyLength, defaultUserAgentProvider: (_b = config === null || config === void 0 ? void 0 : config.defaultUserAgentProvider) !== null && _b !== void 0 ? _b : (0, util_user_agent_node_1.defaultUserAgent)({ serviceId: clientSharedValues.serviceId, clientVersion: package_default.version }), maxAttempts: (_c = config === null || config === void 0 ? void 0 : config.maxAttempts) !== null && _c !== void 0 ? _c : (0, node_config_provider_1.loadConfig)(middleware_retry_2.NODE_MAX_ATTEMPT_CONFIG_OPTIONS), region: (_d = config === null || config === void 0 ? void 0 : config.region) !== null && _d !== void 0 ? _d : (0, node_config_provider_1.loadConfig)(config_resolver_2.NODE_REGION_CONFIG_OPTIONS, config_resolver_2.NODE_REGION_CONFIG_FILE_OPTIONS), requestHandler: (_e = config === null || config === void 0 ? void 0 : config.requestHandler) !== null && _e !== void 0 ? _e : new node_http_handler_1.NodeHttpHandler(defaultConfigProvider), retryMode: (_f = config === null || config === void 0 ? void 0 : config.retryMode) !== null && _f !== void 0 ? _f : (0, node_config_provider_1.loadConfig)({ ...middleware_retry_2.NODE_RETRY_MODE_CONFIG_OPTIONS, default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE, }), sha256: (_g = config === null || config === void 0 ? void 0 : config.sha256) !== null && _g !== void 0 ? _g : hash_node_1.Hash.bind(null, "sha256"), streamCollector: (_h = config === null || config === void 0 ? void 0 : config.streamCollector) !== null && _h !== void 0 ? _h : node_http_handler_1.streamCollector, useDualstackEndpoint: (_j = config === null || config === void 0 ? void 0 : config.useDualstackEndpoint) !== null && _j !== void 0 ? _j : (0, node_config_provider_1.loadConfig)(config_resolver_2.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS), useFipsEndpoint: (_k = config === null || config === void 0 ? void 0 : config.useFipsEndpoint) !== null && _k !== void 0 ? _k : (0, node_config_provider_1.loadConfig)(config_resolver_2.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS), }; }; const region_config_resolver_1 = __nccwpck_require__(18156); const protocol_http_1 = __nccwpck_require__(64418); const smithy_client_5 = __nccwpck_require__(63570); var asPartial = (t2) => t2; var resolveRuntimeExtensions = (runtimeConfig, extensions) => { const extensionConfiguration = { ...asPartial((0, region_config_resolver_1.getAwsRegionExtensionConfiguration)(runtimeConfig)), ...asPartial((0, smithy_client_5.getDefaultExtensionConfiguration)(runtimeConfig)), ...asPartial((0, protocol_http_1.getHttpHandlerExtensionConfiguration)(runtimeConfig)), }; extensions.forEach((extension) => extension.configure(extensionConfiguration)); return { ...runtimeConfig, ...(0, region_config_resolver_1.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), ...(0, smithy_client_5.resolveDefaultRuntimeConfig)(extensionConfiguration), ...(0, protocol_http_1.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), }; }; var SSOOIDCClient = class extends smithy_client_1.Client { constructor(...[configuration]) { const _config_0 = getRuntimeConfig2(configuration || {}); const _config_1 = resolveClientEndpointParameters(_config_0); const _config_2 = (0, config_resolver_1.resolveRegionConfig)(_config_1); const _config_3 = (0, middleware_endpoint_1.resolveEndpointConfig)(_config_2); const _config_4 = (0, middleware_retry_1.resolveRetryConfig)(_config_3); const _config_5 = (0, middleware_host_header_1.resolveHostHeaderConfig)(_config_4); const _config_6 = (0, middleware_user_agent_1.resolveUserAgentConfig)(_config_5); const _config_7 = resolveRuntimeExtensions(_config_6, (configuration === null || configuration === void 0 ? void 0 : configuration.extensions) || []); super(_config_7); this.config = _config_7; this.middlewareStack.use((0, middleware_retry_1.getRetryPlugin)(this.config)); this.middlewareStack.use((0, middleware_content_length_1.getContentLengthPlugin)(this.config)); this.middlewareStack.use((0, middleware_host_header_1.getHostHeaderPlugin)(this.config)); this.middlewareStack.use((0, middleware_logger_1.getLoggerPlugin)(this.config)); this.middlewareStack.use((0, middleware_recursion_detection_1.getRecursionDetectionPlugin)(this.config)); this.middlewareStack.use((0, middleware_user_agent_1.getUserAgentPlugin)(this.config)); } destroy() { super.destroy(); } }; exports.SSOOIDCClient = SSOOIDCClient; const smithy_client_6 = __nccwpck_require__(63570); const middleware_endpoint_2 = __nccwpck_require__(82918); const middleware_serde_1 = __nccwpck_require__(81238); const smithy_client_7 = __nccwpck_require__(63570); const types_1 = __nccwpck_require__(55756); const protocol_http_2 = __nccwpck_require__(64418); const smithy_client_8 = __nccwpck_require__(63570); const smithy_client_9 = __nccwpck_require__(63570); var SSOOIDCServiceException = class _SSOOIDCServiceException extends smithy_client_9.ServiceException { constructor(options) { super(options); Object.setPrototypeOf(this, _SSOOIDCServiceException.prototype); } }; var AccessDeniedException = class _AccessDeniedException extends SSOOIDCServiceException { constructor(opts) { super({ name: "AccessDeniedException", $fault: "client", ...opts, }); this.name = "AccessDeniedException"; this.$fault = "client"; Object.setPrototypeOf(this, _AccessDeniedException.prototype); this.error = opts.error; this.error_description = opts.error_description; } }; exports.AccessDeniedException = AccessDeniedException; var AuthorizationPendingException = class _AuthorizationPendingException extends SSOOIDCServiceException { constructor(opts) { super({ name: "AuthorizationPendingException", $fault: "client", ...opts, }); this.name = "AuthorizationPendingException"; this.$fault = "client"; Object.setPrototypeOf(this, _AuthorizationPendingException.prototype); this.error = opts.error; this.error_description = opts.error_description; } }; exports.AuthorizationPendingException = AuthorizationPendingException; var ExpiredTokenException = class _ExpiredTokenException extends SSOOIDCServiceException { constructor(opts) { super({ name: "ExpiredTokenException", $fault: "client", ...opts, }); this.name = "ExpiredTokenException"; this.$fault = "client"; Object.setPrototypeOf(this, _ExpiredTokenException.prototype); this.error = opts.error; this.error_description = opts.error_description; } }; exports.ExpiredTokenException = ExpiredTokenException; var InternalServerException = class _InternalServerException extends SSOOIDCServiceException { constructor(opts) { super({ name: "InternalServerException", $fault: "server", ...opts, }); this.name = "InternalServerException"; this.$fault = "server"; Object.setPrototypeOf(this, _InternalServerException.prototype); this.error = opts.error; this.error_description = opts.error_description; } }; exports.InternalServerException = InternalServerException; var InvalidClientException = class _InvalidClientException extends SSOOIDCServiceException { constructor(opts) { super({ name: "InvalidClientException", $fault: "client", ...opts, }); this.name = "InvalidClientException"; this.$fault = "client"; Object.setPrototypeOf(this, _InvalidClientException.prototype); this.error = opts.error; this.error_description = opts.error_description; } }; exports.InvalidClientException = InvalidClientException; var InvalidGrantException = class _InvalidGrantException extends SSOOIDCServiceException { constructor(opts) { super({ name: "InvalidGrantException", $fault: "client", ...opts, }); this.name = "InvalidGrantException"; this.$fault = "client"; Object.setPrototypeOf(this, _InvalidGrantException.prototype); this.error = opts.error; this.error_description = opts.error_description; } }; var InvalidRequestException = class _InvalidRequestException extends SSOOIDCServiceException { constructor(opts) { super({ name: "InvalidRequestException", $fault: "client", ...opts, }); this.name = "InvalidRequestException"; this.$fault = "client"; Object.setPrototypeOf(this, _InvalidRequestException.prototype); this.error = opts.error; this.error_description = opts.error_description; } }; exports.InvalidRequestException = InvalidRequestException; var InvalidScopeException = class _InvalidScopeException extends SSOOIDCServiceException { constructor(opts) { super({ name: "InvalidScopeException", $fault: "client", ...opts, }); this.name = "InvalidScopeException"; this.$fault = "client"; Object.setPrototypeOf(this, _InvalidScopeException.prototype); this.error = opts.error; this.error_description = opts.error_description; } }; exports.InvalidScopeException = InvalidScopeException; var SlowDownException = class _SlowDownException extends SSOOIDCServiceException { constructor(opts) { super({ name: "SlowDownException", $fault: "client", ...opts, }); this.name = "SlowDownException"; this.$fault = "client"; Object.setPrototypeOf(this, _SlowDownException.prototype); this.error = opts.error; this.error_description = opts.error_description; } }; exports.SlowDownException = SlowDownException; var UnauthorizedClientException = class _UnauthorizedClientException extends SSOOIDCServiceException { constructor(opts) { super({ name: "UnauthorizedClientException", $fault: "client", ...opts, }); this.name = "UnauthorizedClientException"; this.$fault = "client"; Object.setPrototypeOf(this, _UnauthorizedClientException.prototype); this.error = opts.error; this.error_description = opts.error_description; } }; exports.UnauthorizedClientException = UnauthorizedClientException; var UnsupportedGrantTypeException = class _UnsupportedGrantTypeException extends SSOOIDCServiceException { constructor(opts) { super({ name: "UnsupportedGrantTypeException", $fault: "client", ...opts, }); this.name = "UnsupportedGrantTypeException"; this.$fault = "client"; Object.setPrototypeOf(this, _UnsupportedGrantTypeException.prototype); this.error = opts.error; this.error_description = opts.error_description; } }; exports.UnsupportedGrantTypeException = UnsupportedGrantTypeException; var InvalidClientMetadataException = class _InvalidClientMetadataException extends SSOOIDCServiceException { constructor(opts) { super({ name: "InvalidClientMetadataException", $fault: "client", ...opts, }); this.name = "InvalidClientMetadataException"; this.$fault = "client"; Object.setPrototypeOf(this, _InvalidClientMetadataException.prototype); this.error = opts.error; this.error_description = opts.error_description; } }; var se_CreateTokenCommand = async (input, context) => { const { hostname, protocol = "https", port, path: basePath } = await context.endpoint(); const headers = { "content-type": "application/json", }; const resolvedPath = `${(basePath === null || basePath === void 0 ? void 0 : basePath.endsWith("/")) ? basePath.slice(0, -1) : basePath || ""}/token`; let body; body = JSON.stringify((0, smithy_client_8.take)(input, { clientId: [], clientSecret: [], code: [], deviceCode: [], grantType: [], redirectUri: [], refreshToken: [], scope: (_) => (0, smithy_client_8._json)(_), })); return new protocol_http_2.HttpRequest({ protocol, hostname, port, method: "POST", headers, path: resolvedPath, body, }); }; var se_RegisterClientCommand = async (input, context) => { const { hostname, protocol = "https", port, path: basePath } = await context.endpoint(); const headers = { "content-type": "application/json", }; const resolvedPath = `${(basePath === null || basePath === void 0 ? void 0 : basePath.endsWith("/")) ? basePath.slice(0, -1) : basePath || ""}/client/register`; let body; body = JSON.stringify((0, smithy_client_8.take)(input, { clientName: [], clientType: [], scopes: (_) => (0, smithy_client_8._json)(_), })); return new protocol_http_2.HttpRequest({ protocol, hostname, port, method: "POST", headers, path: resolvedPath, body, }); }; var se_StartDeviceAuthorizationCommand = async (input, context) => { const { hostname, protocol = "https", port, path: basePath } = await context.endpoint(); const headers = { "content-type": "application/json", }; const resolvedPath = `${(basePath === null || basePath === void 0 ? void 0 : basePath.endsWith("/")) ? basePath.slice(0, -1) : basePath || ""}/device_authorization`; let body; body = JSON.stringify((0, smithy_client_8.take)(input, { clientId: [], clientSecret: [], startUrl: [], })); return new protocol_http_2.HttpRequest({ protocol, hostname, port, method: "POST", headers, path: resolvedPath, body, }); }; var de_CreateTokenCommand = async (output, context) => { if (output.statusCode !== 200 && output.statusCode >= 300) { return de_CreateTokenCommandError(output, context); } const contents = (0, smithy_client_8.map)({ $metadata: deserializeMetadata(output), }); const data = (0, smithy_client_8.expectNonNull)((0, smithy_client_8.expectObject)(await parseBody(output.body, context)), "body"); const doc = (0, smithy_client_8.take)(data, { accessToken: smithy_client_8.expectString, expiresIn: smithy_client_8.expectInt32, idToken: smithy_client_8.expectString, refreshToken: smithy_client_8.expectString, tokenType: smithy_client_8.expectString, }); Object.assign(contents, doc); return contents; }; var de_CreateTokenCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "AccessDeniedException": case "com.amazonaws.ssooidc#AccessDeniedException": throw await de_AccessDeniedExceptionRes(parsedOutput, context); case "AuthorizationPendingException": case "com.amazonaws.ssooidc#AuthorizationPendingException": throw await de_AuthorizationPendingExceptionRes(parsedOutput, context); case "ExpiredTokenException": case "com.amazonaws.ssooidc#ExpiredTokenException": throw await de_ExpiredTokenExceptionRes(parsedOutput, context); case "InternalServerException": case "com.amazonaws.ssooidc#InternalServerException": throw await de_InternalServerExceptionRes(parsedOutput, context); case "InvalidClientException": case "com.amazonaws.ssooidc#InvalidClientException": throw await de_InvalidClientExceptionRes(parsedOutput, context); case "InvalidGrantException": case "com.amazonaws.ssooidc#InvalidGrantException": throw await de_InvalidGrantExceptionRes(parsedOutput, context); case "InvalidRequestException": case "com.amazonaws.ssooidc#InvalidRequestException": throw await de_InvalidRequestExceptionRes(parsedOutput, context); case "InvalidScopeException": case "com.amazonaws.ssooidc#InvalidScopeException": throw await de_InvalidScopeExceptionRes(parsedOutput, context); case "SlowDownException": case "com.amazonaws.ssooidc#SlowDownException": throw await de_SlowDownExceptionRes(parsedOutput, context); case "UnauthorizedClientException": case "com.amazonaws.ssooidc#UnauthorizedClientException": throw await de_UnauthorizedClientExceptionRes(parsedOutput, context); case "UnsupportedGrantTypeException": case "com.amazonaws.ssooidc#UnsupportedGrantTypeException": throw await de_UnsupportedGrantTypeExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; var de_RegisterClientCommand = async (output, context) => { if (output.statusCode !== 200 && output.statusCode >= 300) { return de_RegisterClientCommandError(output, context); } const contents = (0, smithy_client_8.map)({ $metadata: deserializeMetadata(output), }); const data = (0, smithy_client_8.expectNonNull)((0, smithy_client_8.expectObject)(await parseBody(output.body, context)), "body"); const doc = (0, smithy_client_8.take)(data, { authorizationEndpoint: smithy_client_8.expectString, clientId: smithy_client_8.expectString, clientIdIssuedAt: smithy_client_8.expectLong, clientSecret: smithy_client_8.expectString, clientSecretExpiresAt: smithy_client_8.expectLong, tokenEndpoint: smithy_client_8.expectString, }); Object.assign(contents, doc); return contents; }; var de_RegisterClientCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "InternalServerException": case "com.amazonaws.ssooidc#InternalServerException": throw await de_InternalServerExceptionRes(parsedOutput, context); case "InvalidClientMetadataException": case "com.amazonaws.ssooidc#InvalidClientMetadataException": throw await de_InvalidClientMetadataExceptionRes(parsedOutput, context); case "InvalidRequestException": case "com.amazonaws.ssooidc#InvalidRequestException": throw await de_InvalidRequestExceptionRes(parsedOutput, context); case "InvalidScopeException": case "com.amazonaws.ssooidc#InvalidScopeException": throw await de_InvalidScopeExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; var de_StartDeviceAuthorizationCommand = async (output, context) => { if (output.statusCode !== 200 && output.statusCode >= 300) { return de_StartDeviceAuthorizationCommandError(output, context); } const contents = (0, smithy_client_8.map)({ $metadata: deserializeMetadata(output), }); const data = (0, smithy_client_8.expectNonNull)((0, smithy_client_8.expectObject)(await parseBody(output.body, context)), "body"); const doc = (0, smithy_client_8.take)(data, { deviceCode: smithy_client_8.expectString, expiresIn: smithy_client_8.expectInt32, interval: smithy_client_8.expectInt32, userCode: smithy_client_8.expectString, verificationUri: smithy_client_8.expectString, verificationUriComplete: smithy_client_8.expectString, }); Object.assign(contents, doc); return contents; }; var de_StartDeviceAuthorizationCommandError = async (output, context) => { const parsedOutput = { ...output, body: await parseErrorBody(output.body, context), }; const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); switch (errorCode) { case "InternalServerException": case "com.amazonaws.ssooidc#InternalServerException": throw await de_InternalServerExceptionRes(parsedOutput, context); case "InvalidClientException": case "com.amazonaws.ssooidc#InvalidClientException": throw await de_InvalidClientExceptionRes(parsedOutput, context); case "InvalidRequestException": case "com.amazonaws.ssooidc#InvalidRequestException": throw await de_InvalidRequestExceptionRes(parsedOutput, context); case "SlowDownException": case "com.amazonaws.ssooidc#SlowDownException": throw await de_SlowDownExceptionRes(parsedOutput, context); case "UnauthorizedClientException": case "com.amazonaws.ssooidc#UnauthorizedClientException": throw await de_UnauthorizedClientExceptionRes(parsedOutput, context); default: const parsedBody = parsedOutput.body; return throwDefaultError({ output, parsedBody, errorCode, }); } }; var throwDefaultError = (0, smithy_client_8.withBaseException)(SSOOIDCServiceException); var de_AccessDeniedExceptionRes = async (parsedOutput, context) => { const contents = (0, smithy_client_8.map)({}); const data = parsedOutput.body; const doc = (0, smithy_client_8.take)(data, { error: smithy_client_8.expectString, error_description: smithy_client_8.expectString, }); Object.assign(contents, doc); const exception = new AccessDeniedException({ $metadata: deserializeMetadata(parsedOutput), ...contents, }); return (0, smithy_client_8.decorateServiceException)(exception, parsedOutput.body); }; var de_AuthorizationPendingExceptionRes = async (parsedOutput, context) => { const contents = (0, smithy_client_8.map)({}); const data = parsedOutput.body; const doc = (0, smithy_client_8.take)(data, { error: smithy_client_8.expectString, error_description: smithy_client_8.expectString, }); Object.assign(contents, doc); const exception = new AuthorizationPendingException({ $metadata: deserializeMetadata(parsedOutput), ...contents, }); return (0, smithy_client_8.decorateServiceException)(exception, parsedOutput.body); }; var de_ExpiredTokenExceptionRes = async (parsedOutput, context) => { const contents = (0, smithy_client_8.map)({}); const data = parsedOutput.body; const doc = (0, smithy_client_8.take)(data, { error: smithy_client_8.expectString, error_description: smithy_client_8.expectString, }); Object.assign(contents, doc); const exception = new ExpiredTokenException({ $metadata: deserializeMetadata(parsedOutput), ...contents, }); return (0, smithy_client_8.decorateServiceException)(exception, parsedOutput.body); }; var de_InternalServerExceptionRes = async (parsedOutput, context) => { const contents = (0, smithy_client_8.map)({}); const data = parsedOutput.body; const doc = (0, smithy_client_8.take)(data, { error: smithy_client_8.expectString, error_description: smithy_client_8.expectString, }); Object.assign(contents, doc); const exception = new InternalServerException({ $metadata: deserializeMetadata(parsedOutput), ...contents, }); return (0, smithy_client_8.decorateServiceException)(exception, parsedOutput.body); }; var de_InvalidClientExceptionRes = async (parsedOutput, context) => { const contents = (0, smithy_client_8.map)({}); const data = parsedOutput.body; const doc = (0, smithy_client_8.take)(data, { error: smithy_client_8.expectString, error_description: smithy_client_8.expectString, }); Object.assign(contents, doc); const exception = new InvalidClientException({ $metadata: deserializeMetadata(parsedOutput), ...contents, }); return (0, smithy_client_8.decorateServiceException)(exception, parsedOutput.body); }; var de_InvalidClientMetadataExceptionRes = async (parsedOutput, context) => { const contents = (0, smithy_client_8.map)({}); const data = parsedOutput.body; const doc = (0, smithy_client_8.take)(data, { error: smithy_client_8.expectString, error_description: smithy_client_8.expectString, }); Object.assign(contents, doc); const exception = new InvalidClientMetadataException({ $metadata: deserializeMetadata(parsedOutput), ...contents, }); return (0, smithy_client_8.decorateServiceException)(exception, parsedOutput.body); }; var de_InvalidGrantExceptionRes = async (parsedOutput, context) => { const contents = (0, smithy_client_8.map)({}); const data = parsedOutput.body; const doc = (0, smithy_client_8.take)(data, { error: smithy_client_8.expectString, error_description: smithy_client_8.expectString, }); Object.assign(contents, doc); const exception = new InvalidGrantException({ $metadata: deserializeMetadata(parsedOutput), ...contents, }); return (0, smithy_client_8.decorateServiceException)(exception, parsedOutput.body); }; var de_InvalidRequestExceptionRes = async (parsedOutput, context) => { const contents = (0, smithy_client_8.map)({}); const data = parsedOutput.body; const doc = (0, smithy_client_8.take)(data, { error: smithy_client_8.expectString, error_description: smithy_client_8.expectString, }); Object.assign(contents, doc); const exception = new InvalidRequestException({ $metadata: deserializeMetadata(parsedOutput), ...contents, }); return (0, smithy_client_8.decorateServiceException)(exception, parsedOutput.body); }; var de_InvalidScopeExceptionRes = async (parsedOutput, context) => { const contents = (0, smithy_client_8.map)({}); const data = parsedOutput.body; const doc = (0, smithy_client_8.take)(data, { error: smithy_client_8.expectString, error_description: smithy_client_8.expectString, }); Object.assign(contents, doc); const exception = new InvalidScopeException({ $metadata: deserializeMetadata(parsedOutput), ...contents, }); return (0, smithy_client_8.decorateServiceException)(exception, parsedOutput.body); }; var de_SlowDownExceptionRes = async (parsedOutput, context) => { const contents = (0, smithy_client_8.map)({}); const data = parsedOutput.body; const doc = (0, smithy_client_8.take)(data, { error: smithy_client_8.expectString, error_description: smithy_client_8.expectString, }); Object.assign(contents, doc); const exception = new SlowDownException({ $metadata: deserializeMetadata(parsedOutput), ...contents, }); return (0, smithy_client_8.decorateServiceException)(exception, parsedOutput.body); }; var de_UnauthorizedClientExceptionRes = async (parsedOutput, context) => { const contents = (0, smithy_client_8.map)({}); const data = parsedOutput.body; const doc = (0, smithy_client_8.take)(data, { error: smithy_client_8.expectString, error_description: smithy_client_8.expectString, }); Object.assign(contents, doc); const exception = new UnauthorizedClientException({ $metadata: deserializeMetadata(parsedOutput), ...contents, }); return (0, smithy_client_8.decorateServiceException)(exception, parsedOutput.body); }; var de_UnsupportedGrantTypeExceptionRes = async (parsedOutput, context) => { const contents = (0, smithy_client_8.map)({}); const data = parsedOutput.body; const doc = (0, smithy_client_8.take)(data, { error: smithy_client_8.expectString, error_description: smithy_client_8.expectString, }); Object.assign(contents, doc); const exception = new UnsupportedGrantTypeException({ $metadata: deserializeMetadata(parsedOutput), ...contents, }); return (0, smithy_client_8.decorateServiceException)(exception, parsedOutput.body); }; var deserializeMetadata = (output) => { var _a, _b; return ({ httpStatusCode: output.statusCode, requestId: (_b = (_a = output.headers["x-amzn-requestid"]) !== null && _a !== void 0 ? _a : output.headers["x-amzn-request-id"]) !== null && _b !== void 0 ? _b : output.headers["x-amz-request-id"], extendedRequestId: output.headers["x-amz-id-2"], cfId: output.headers["x-amz-cf-id"], }); }; var collectBodyString = (streamBody, context) => (0, smithy_client_8.collectBody)(streamBody, context).then((body) => context.utf8Encoder(body)); var parseBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { if (encoded.length) { return JSON.parse(encoded); } return {}; }); var parseErrorBody = async (errorBody, context) => { var _a; const value = await parseBody(errorBody, context); value.message = (_a = value.message) !== null && _a !== void 0 ? _a : value.Message; return value; }; var loadRestJsonErrorCode = (output, data) => { const findKey = (object, key) => Object.keys(object).find((k2) => k2.toLowerCase() === key.toLowerCase()); const sanitizeErrorCode = (rawValue) => { let cleanValue = rawValue; if (typeof cleanValue === "number") { cleanValue = cleanValue.toString(); } if (cleanValue.indexOf(",") >= 0) { cleanValue = cleanValue.split(",")[0]; } if (cleanValue.indexOf(":") >= 0) { cleanValue = cleanValue.split(":")[0]; } if (cleanValue.indexOf("#") >= 0) { cleanValue = cleanValue.split("#")[1]; } return cleanValue; }; const headerKey = findKey(output.headers, "x-amzn-errortype"); if (headerKey !== void 0) { return sanitizeErrorCode(output.headers[headerKey]); } if (data.code !== void 0) { return sanitizeErrorCode(data.code); } if (data["__type"] !== void 0) { return sanitizeErrorCode(data["__type"]); } }; var CreateTokenCommand = class _CreateTokenCommand extends smithy_client_7.Command { constructor(input) { super(); this.input = input; } static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_1.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_2.getEndpointPlugin)(configuration, _CreateTokenCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "SSOOIDCClient"; const commandName = "CreateTokenCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_1.SMITHY_CONTEXT_KEY]: { service: "AWSSSOOIDCService", operation: "CreateToken", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return se_CreateTokenCommand(input, context); } deserialize(output, context) { return de_CreateTokenCommand(output, context); } }; exports.CreateTokenCommand = CreateTokenCommand; const middleware_endpoint_3 = __nccwpck_require__(82918); const middleware_serde_2 = __nccwpck_require__(81238); const smithy_client_10 = __nccwpck_require__(63570); const types_2 = __nccwpck_require__(55756); var RegisterClientCommand = class _RegisterClientCommand extends smithy_client_10.Command { constructor(input) { super(); this.input = input; } static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_2.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_3.getEndpointPlugin)(configuration, _RegisterClientCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "SSOOIDCClient"; const commandName = "RegisterClientCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_2.SMITHY_CONTEXT_KEY]: { service: "AWSSSOOIDCService", operation: "RegisterClient", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return se_RegisterClientCommand(input, context); } deserialize(output, context) { return de_RegisterClientCommand(output, context); } }; const middleware_endpoint_4 = __nccwpck_require__(82918); const middleware_serde_3 = __nccwpck_require__(81238); const smithy_client_11 = __nccwpck_require__(63570); const types_3 = __nccwpck_require__(55756); var StartDeviceAuthorizationCommand = class _StartDeviceAuthorizationCommand extends smithy_client_11.Command { constructor(input) { super(); this.input = input; } static getEndpointParameterInstructions() { return { UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, Endpoint: { type: "builtInParams", name: "endpoint" }, Region: { type: "builtInParams", name: "region" }, UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, }; } resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use((0, middleware_serde_3.getSerdePlugin)(configuration, this.serialize, this.deserialize)); this.middlewareStack.use((0, middleware_endpoint_4.getEndpointPlugin)(configuration, _StartDeviceAuthorizationCommand.getEndpointParameterInstructions())); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "SSOOIDCClient"; const commandName = "StartDeviceAuthorizationCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: (_) => _, outputFilterSensitiveLog: (_) => _, [types_3.SMITHY_CONTEXT_KEY]: { service: "AWSSSOOIDCService", operation: "StartDeviceAuthorization", }, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return se_StartDeviceAuthorizationCommand(input, context); } deserialize(output, context) { return de_StartDeviceAuthorizationCommand(output, context); } }; var commands = { CreateTokenCommand, RegisterClientCommand, StartDeviceAuthorizationCommand, }; var SSOOIDC = class extends SSOOIDCClient { }; (0, smithy_client_6.createAggregatedClient)(commands, SSOOIDC); /***/ }), /***/ 92242: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.REFRESH_MESSAGE = exports.EXPIRE_WINDOW_MS = void 0; exports.EXPIRE_WINDOW_MS = 5 * 60 * 1000; exports.REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`; /***/ }), /***/ 85125: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fromSso = void 0; const property_provider_1 = __nccwpck_require__(79721); const shared_ini_file_loader_1 = __nccwpck_require__(43507); const constants_1 = __nccwpck_require__(92242); const getNewSsoOidcToken_1 = __nccwpck_require__(93601); const validateTokenExpiry_1 = __nccwpck_require__(28418); const validateTokenKey_1 = __nccwpck_require__(2488); const writeSSOTokenToFile_1 = __nccwpck_require__(48552); const lastRefreshAttemptTime = new Date(0); const fromSso = (init = {}) => async () => { const profiles = await (0, shared_ini_file_loader_1.parseKnownFiles)(init); const profileName = (0, shared_ini_file_loader_1.getProfileName)(init); const profile = profiles[profileName]; if (!profile) { throw new property_provider_1.TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false); } else if (!profile["sso_session"]) { throw new property_provider_1.TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`); } const ssoSessionName = profile["sso_session"]; const ssoSessions = await (0, shared_ini_file_loader_1.loadSsoSessionData)(init); const ssoSession = ssoSessions[ssoSessionName]; if (!ssoSession) { throw new property_provider_1.TokenProviderError(`Sso session '${ssoSessionName}' could not be found in shared credentials file.`, false); } for (const ssoSessionRequiredKey of ["sso_start_url", "sso_region"]) { if (!ssoSession[ssoSessionRequiredKey]) { throw new property_provider_1.TokenProviderError(`Sso session '${ssoSessionName}' is missing required property '${ssoSessionRequiredKey}'.`, false); } } const ssoStartUrl = ssoSession["sso_start_url"]; const ssoRegion = ssoSession["sso_region"]; let ssoToken; try { ssoToken = await (0, shared_ini_file_loader_1.getSSOTokenFromFile)(ssoSessionName); } catch (e) { throw new property_provider_1.TokenProviderError(`The SSO session token associated with profile=${profileName} was not found or is invalid. ${constants_1.REFRESH_MESSAGE}`, false); } (0, validateTokenKey_1.validateTokenKey)("accessToken", ssoToken.accessToken); (0, validateTokenKey_1.validateTokenKey)("expiresAt", ssoToken.expiresAt); const { accessToken, expiresAt } = ssoToken; const existingToken = { token: accessToken, expiration: new Date(expiresAt) }; if (existingToken.expiration.getTime() - Date.now() > constants_1.EXPIRE_WINDOW_MS) { return existingToken; } if (Date.now() - lastRefreshAttemptTime.getTime() < 30 * 1000) { (0, validateTokenExpiry_1.validateTokenExpiry)(existingToken); return existingToken; } (0, validateTokenKey_1.validateTokenKey)("clientId", ssoToken.clientId, true); (0, validateTokenKey_1.validateTokenKey)("clientSecret", ssoToken.clientSecret, true); (0, validateTokenKey_1.validateTokenKey)("refreshToken", ssoToken.refreshToken, true); try { lastRefreshAttemptTime.setTime(Date.now()); const newSsoOidcToken = await (0, getNewSsoOidcToken_1.getNewSsoOidcToken)(ssoToken, ssoRegion); (0, validateTokenKey_1.validateTokenKey)("accessToken", newSsoOidcToken.accessToken); (0, validateTokenKey_1.validateTokenKey)("expiresIn", newSsoOidcToken.expiresIn); const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1000); try { await (0, writeSSOTokenToFile_1.writeSSOTokenToFile)(ssoSessionName, { ...ssoToken, accessToken: newSsoOidcToken.accessToken, expiresAt: newTokenExpiration.toISOString(), refreshToken: newSsoOidcToken.refreshToken, }); } catch (error) { } return { token: newSsoOidcToken.accessToken, expiration: newTokenExpiration, }; } catch (error) { (0, validateTokenExpiry_1.validateTokenExpiry)(existingToken); return existingToken; } }; exports.fromSso = fromSso; /***/ }), /***/ 63258: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fromStatic = void 0; const property_provider_1 = __nccwpck_require__(79721); const fromStatic = ({ token }) => async () => { if (!token || !token.token) { throw new property_provider_1.TokenProviderError(`Please pass a valid token to fromStatic`, false); } return token; }; exports.fromStatic = fromStatic; /***/ }), /***/ 93601: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getNewSsoOidcToken = void 0; const client_sso_oidc_node_1 = __nccwpck_require__(52664); const getSsoOidcClient_1 = __nccwpck_require__(99775); const getNewSsoOidcToken = (ssoToken, ssoRegion) => { const ssoOidcClient = (0, getSsoOidcClient_1.getSsoOidcClient)(ssoRegion); return ssoOidcClient.send(new client_sso_oidc_node_1.CreateTokenCommand({ clientId: ssoToken.clientId, clientSecret: ssoToken.clientSecret, refreshToken: ssoToken.refreshToken, grantType: "refresh_token", })); }; exports.getNewSsoOidcToken = getNewSsoOidcToken; /***/ }), /***/ 99775: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getSsoOidcClient = void 0; const client_sso_oidc_node_1 = __nccwpck_require__(52664); const ssoOidcClientsHash = {}; const getSsoOidcClient = (ssoRegion) => { if (ssoOidcClientsHash[ssoRegion]) { return ssoOidcClientsHash[ssoRegion]; } const ssoOidcClient = new client_sso_oidc_node_1.SSOOIDCClient({ region: ssoRegion }); ssoOidcClientsHash[ssoRegion] = ssoOidcClient; return ssoOidcClient; }; exports.getSsoOidcClient = getSsoOidcClient; /***/ }), /***/ 52843: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(52664), exports); tslib_1.__exportStar(__nccwpck_require__(85125), exports); tslib_1.__exportStar(__nccwpck_require__(63258), exports); tslib_1.__exportStar(__nccwpck_require__(70195), exports); /***/ }), /***/ 70195: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.nodeProvider = void 0; const property_provider_1 = __nccwpck_require__(79721); const fromSso_1 = __nccwpck_require__(85125); const nodeProvider = (init = {}) => (0, property_provider_1.memoize)((0, property_provider_1.chain)((0, fromSso_1.fromSso)(init), async () => { throw new property_provider_1.TokenProviderError("Could not load token from any providers", false); }), (token) => token.expiration !== undefined && token.expiration.getTime() - Date.now() < 300000, (token) => token.expiration !== undefined); exports.nodeProvider = nodeProvider; /***/ }), /***/ 28418: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.validateTokenExpiry = void 0; const property_provider_1 = __nccwpck_require__(79721); const constants_1 = __nccwpck_require__(92242); const validateTokenExpiry = (token) => { if (token.expiration && token.expiration.getTime() < Date.now()) { throw new property_provider_1.TokenProviderError(`Token is expired. ${constants_1.REFRESH_MESSAGE}`, false); } }; exports.validateTokenExpiry = validateTokenExpiry; /***/ }), /***/ 2488: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.validateTokenKey = void 0; const property_provider_1 = __nccwpck_require__(79721); const constants_1 = __nccwpck_require__(92242); const validateTokenKey = (key, value, forRefresh = false) => { if (typeof value === "undefined") { throw new property_provider_1.TokenProviderError(`Value not present for '${key}' in SSO Token${forRefresh ? ". Cannot refresh" : ""}. ${constants_1.REFRESH_MESSAGE}`, false); } }; exports.validateTokenKey = validateTokenKey; /***/ }), /***/ 48552: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.writeSSOTokenToFile = void 0; const shared_ini_file_loader_1 = __nccwpck_require__(43507); const fs_1 = __nccwpck_require__(57147); const { writeFile } = fs_1.promises; const writeSSOTokenToFile = (id, ssoToken) => { const tokenFilepath = (0, shared_ini_file_loader_1.getSSOTokenFilepath)(id); const tokenString = JSON.stringify(ssoToken, null, 2); return writeFile(tokenFilepath, tokenString); }; exports.writeSSOTokenToFile = writeSSOTokenToFile; /***/ }), /***/ 15011: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const util_endpoints_1 = __nccwpck_require__(45473); const isVirtualHostableS3Bucket_1 = __nccwpck_require__(48079); const parseArn_1 = __nccwpck_require__(34711); const partition_1 = __nccwpck_require__(37482); const awsEndpointFunctions = { isVirtualHostableS3Bucket: isVirtualHostableS3Bucket_1.isVirtualHostableS3Bucket, parseArn: parseArn_1.parseArn, partition: partition_1.partition, }; util_endpoints_1.customEndpointFunctions.aws = awsEndpointFunctions; /***/ }), /***/ 13350: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(15011), exports); tslib_1.__exportStar(__nccwpck_require__(37482), exports); tslib_1.__exportStar(__nccwpck_require__(73442), exports); tslib_1.__exportStar(__nccwpck_require__(36563), exports); tslib_1.__exportStar(__nccwpck_require__(57433), exports); /***/ }), /***/ 48079: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isVirtualHostableS3Bucket = void 0; const util_endpoints_1 = __nccwpck_require__(45473); const isIpAddress_1 = __nccwpck_require__(73442); const isVirtualHostableS3Bucket = (value, allowSubDomains = false) => { if (allowSubDomains) { for (const label of value.split(".")) { if (!(0, exports.isVirtualHostableS3Bucket)(label)) { return false; } } return true; } if (!(0, util_endpoints_1.isValidHostLabel)(value)) { return false; } if (value.length < 3 || value.length > 63) { return false; } if (value !== value.toLowerCase()) { return false; } if ((0, isIpAddress_1.isIpAddress)(value)) { return false; } return true; }; exports.isVirtualHostableS3Bucket = isVirtualHostableS3Bucket; /***/ }), /***/ 34711: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseArn = void 0; const parseArn = (value) => { const segments = value.split(":"); if (segments.length < 6) return null; const [arn, partition, service, region, accountId, ...resourceId] = segments; if (arn !== "arn" || partition === "" || service === "" || resourceId[0] === "") return null; return { partition, service, region, accountId, resourceId: resourceId[0].includes("/") ? resourceId[0].split("/") : resourceId, }; }; exports.parseArn = parseArn; /***/ }), /***/ 37482: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getUserAgentPrefix = exports.useDefaultPartitionInfo = exports.setPartitionInfo = exports.partition = void 0; const tslib_1 = __nccwpck_require__(4351); const partitions_json_1 = tslib_1.__importDefault(__nccwpck_require__(95367)); let selectedPartitionsInfo = partitions_json_1.default; let selectedUserAgentPrefix = ""; const partition = (value) => { const { partitions } = selectedPartitionsInfo; for (const partition of partitions) { const { regions, outputs } = partition; for (const [region, regionData] of Object.entries(regions)) { if (region === value) { return { ...outputs, ...regionData, }; } } } for (const partition of partitions) { const { regionRegex, outputs } = partition; if (new RegExp(regionRegex).test(value)) { return { ...outputs, }; } } const DEFAULT_PARTITION = partitions.find((partition) => partition.id === "aws"); if (!DEFAULT_PARTITION) { throw new Error("Provided region was not found in the partition array or regex," + " and default partition with id 'aws' doesn't exist."); } return { ...DEFAULT_PARTITION.outputs, }; }; exports.partition = partition; const setPartitionInfo = (partitionsInfo, userAgentPrefix = "") => { selectedPartitionsInfo = partitionsInfo; selectedUserAgentPrefix = userAgentPrefix; }; exports.setPartitionInfo = setPartitionInfo; const useDefaultPartitionInfo = () => { (0, exports.setPartitionInfo)(partitions_json_1.default, ""); }; exports.useDefaultPartitionInfo = useDefaultPartitionInfo; const getUserAgentPrefix = () => selectedUserAgentPrefix; exports.getUserAgentPrefix = getUserAgentPrefix; /***/ }), /***/ 73442: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isIpAddress = void 0; var util_endpoints_1 = __nccwpck_require__(45473); Object.defineProperty(exports, "isIpAddress", ({ enumerable: true, get: function () { return util_endpoints_1.isIpAddress; } })); /***/ }), /***/ 36563: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveEndpoint = void 0; var util_endpoints_1 = __nccwpck_require__(45473); Object.defineProperty(exports, "resolveEndpoint", ({ enumerable: true, get: function () { return util_endpoints_1.resolveEndpoint; } })); /***/ }), /***/ 82605: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.EndpointError = void 0; var util_endpoints_1 = __nccwpck_require__(45473); Object.defineProperty(exports, "EndpointError", ({ enumerable: true, get: function () { return util_endpoints_1.EndpointError; } })); /***/ }), /***/ 21261: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 20312: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 56083: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 21767: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 57433: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(82605), exports); tslib_1.__exportStar(__nccwpck_require__(21261), exports); tslib_1.__exportStar(__nccwpck_require__(20312), exports); tslib_1.__exportStar(__nccwpck_require__(56083), exports); tslib_1.__exportStar(__nccwpck_require__(21767), exports); tslib_1.__exportStar(__nccwpck_require__(41811), exports); /***/ }), /***/ 41811: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 5865: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.crtAvailability = void 0; exports.crtAvailability = { isCrtAvailable: false, }; /***/ }), /***/ 98095: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.defaultUserAgent = exports.UA_APP_ID_INI_NAME = exports.UA_APP_ID_ENV_NAME = exports.crtAvailability = void 0; const node_config_provider_1 = __nccwpck_require__(33461); const os_1 = __nccwpck_require__(22037); const process_1 = __nccwpck_require__(77282); const is_crt_available_1 = __nccwpck_require__(68390); var crt_availability_1 = __nccwpck_require__(5865); Object.defineProperty(exports, "crtAvailability", ({ enumerable: true, get: function () { return crt_availability_1.crtAvailability; } })); exports.UA_APP_ID_ENV_NAME = "AWS_SDK_UA_APP_ID"; exports.UA_APP_ID_INI_NAME = "sdk-ua-app-id"; const defaultUserAgent = ({ serviceId, clientVersion }) => { const sections = [ ["aws-sdk-js", clientVersion], ["ua", "2.0"], [`os/${(0, os_1.platform)()}`, (0, os_1.release)()], ["lang/js"], ["md/nodejs", `${process_1.versions.node}`], ]; const crtAvailable = (0, is_crt_available_1.isCrtAvailable)(); if (crtAvailable) { sections.push(crtAvailable); } if (serviceId) { sections.push([`api/${serviceId}`, clientVersion]); } if (process_1.env.AWS_EXECUTION_ENV) { sections.push([`exec-env/${process_1.env.AWS_EXECUTION_ENV}`]); } const appIdPromise = (0, node_config_provider_1.loadConfig)({ environmentVariableSelector: (env) => env[exports.UA_APP_ID_ENV_NAME], configFileSelector: (profile) => profile[exports.UA_APP_ID_INI_NAME], default: undefined, })(); let resolvedUserAgent = undefined; return async () => { if (!resolvedUserAgent) { const appId = await appIdPromise; resolvedUserAgent = appId ? [...sections, [`app/${appId}`]] : [...sections]; } return resolvedUserAgent; }; }; exports.defaultUserAgent = defaultUserAgent; /***/ }), /***/ 68390: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isCrtAvailable = void 0; const crt_availability_1 = __nccwpck_require__(5865); const isCrtAvailable = () => { if (crt_availability_1.crtAvailability.isCrtAvailable) { return ["md/crt-avail"]; } return null; }; exports.isCrtAvailable = isCrtAvailable; /***/ }), /***/ 28172: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toUtf8 = exports.fromUtf8 = void 0; const pureJs_1 = __nccwpck_require__(21590); const whatwgEncodingApi_1 = __nccwpck_require__(89215); const fromUtf8 = (input) => typeof TextEncoder === "function" ? (0, whatwgEncodingApi_1.fromUtf8)(input) : (0, pureJs_1.fromUtf8)(input); exports.fromUtf8 = fromUtf8; const toUtf8 = (input) => typeof TextDecoder === "function" ? (0, whatwgEncodingApi_1.toUtf8)(input) : (0, pureJs_1.toUtf8)(input); exports.toUtf8 = toUtf8; /***/ }), /***/ 21590: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toUtf8 = exports.fromUtf8 = void 0; const fromUtf8 = (input) => { const bytes = []; for (let i = 0, len = input.length; i < len; i++) { const value = input.charCodeAt(i); if (value < 0x80) { bytes.push(value); } else if (value < 0x800) { bytes.push((value >> 6) | 0b11000000, (value & 0b111111) | 0b10000000); } else if (i + 1 < input.length && (value & 0xfc00) === 0xd800 && (input.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { const surrogatePair = 0x10000 + ((value & 0b1111111111) << 10) + (input.charCodeAt(++i) & 0b1111111111); bytes.push((surrogatePair >> 18) | 0b11110000, ((surrogatePair >> 12) & 0b111111) | 0b10000000, ((surrogatePair >> 6) & 0b111111) | 0b10000000, (surrogatePair & 0b111111) | 0b10000000); } else { bytes.push((value >> 12) | 0b11100000, ((value >> 6) & 0b111111) | 0b10000000, (value & 0b111111) | 0b10000000); } } return Uint8Array.from(bytes); }; exports.fromUtf8 = fromUtf8; const toUtf8 = (input) => { let decoded = ""; for (let i = 0, len = input.length; i < len; i++) { const byte = input[i]; if (byte < 0x80) { decoded += String.fromCharCode(byte); } else if (0b11000000 <= byte && byte < 0b11100000) { const nextByte = input[++i]; decoded += String.fromCharCode(((byte & 0b11111) << 6) | (nextByte & 0b111111)); } else if (0b11110000 <= byte && byte < 0b101101101) { const surrogatePair = [byte, input[++i], input[++i], input[++i]]; const encoded = "%" + surrogatePair.map((byteValue) => byteValue.toString(16)).join("%"); decoded += decodeURIComponent(encoded); } else { decoded += String.fromCharCode(((byte & 0b1111) << 12) | ((input[++i] & 0b111111) << 6) | (input[++i] & 0b111111)); } } return decoded; }; exports.toUtf8 = toUtf8; /***/ }), /***/ 89215: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toUtf8 = exports.fromUtf8 = void 0; function fromUtf8(input) { return new TextEncoder().encode(input); } exports.fromUtf8 = fromUtf8; function toUtf8(input) { return new TextDecoder("utf-8").decode(input); } exports.toUtf8 = toUtf8; /***/ }), /***/ 43779: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = exports.DEFAULT_USE_DUALSTACK_ENDPOINT = exports.CONFIG_USE_DUALSTACK_ENDPOINT = exports.ENV_USE_DUALSTACK_ENDPOINT = void 0; const util_config_provider_1 = __nccwpck_require__(83375); exports.ENV_USE_DUALSTACK_ENDPOINT = "AWS_USE_DUALSTACK_ENDPOINT"; exports.CONFIG_USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint"; exports.DEFAULT_USE_DUALSTACK_ENDPOINT = false; exports.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = { environmentVariableSelector: (env) => (0, util_config_provider_1.booleanSelector)(env, exports.ENV_USE_DUALSTACK_ENDPOINT, util_config_provider_1.SelectorType.ENV), configFileSelector: (profile) => (0, util_config_provider_1.booleanSelector)(profile, exports.CONFIG_USE_DUALSTACK_ENDPOINT, util_config_provider_1.SelectorType.CONFIG), default: false, }; /***/ }), /***/ 17994: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = exports.DEFAULT_USE_FIPS_ENDPOINT = exports.CONFIG_USE_FIPS_ENDPOINT = exports.ENV_USE_FIPS_ENDPOINT = void 0; const util_config_provider_1 = __nccwpck_require__(83375); exports.ENV_USE_FIPS_ENDPOINT = "AWS_USE_FIPS_ENDPOINT"; exports.CONFIG_USE_FIPS_ENDPOINT = "use_fips_endpoint"; exports.DEFAULT_USE_FIPS_ENDPOINT = false; exports.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = { environmentVariableSelector: (env) => (0, util_config_provider_1.booleanSelector)(env, exports.ENV_USE_FIPS_ENDPOINT, util_config_provider_1.SelectorType.ENV), configFileSelector: (profile) => (0, util_config_provider_1.booleanSelector)(profile, exports.CONFIG_USE_FIPS_ENDPOINT, util_config_provider_1.SelectorType.CONFIG), default: false, }; /***/ }), /***/ 18421: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(43779), exports); tslib_1.__exportStar(__nccwpck_require__(17994), exports); tslib_1.__exportStar(__nccwpck_require__(37432), exports); tslib_1.__exportStar(__nccwpck_require__(61892), exports); /***/ }), /***/ 37432: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveCustomEndpointsConfig = void 0; const util_middleware_1 = __nccwpck_require__(2390); const resolveCustomEndpointsConfig = (input) => { var _a, _b; const { endpoint, urlParser } = input; return { ...input, tls: (_a = input.tls) !== null && _a !== void 0 ? _a : true, endpoint: (0, util_middleware_1.normalizeProvider)(typeof endpoint === "string" ? urlParser(endpoint) : endpoint), isCustomEndpoint: true, useDualstackEndpoint: (0, util_middleware_1.normalizeProvider)((_b = input.useDualstackEndpoint) !== null && _b !== void 0 ? _b : false), }; }; exports.resolveCustomEndpointsConfig = resolveCustomEndpointsConfig; /***/ }), /***/ 61892: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveEndpointsConfig = void 0; const util_middleware_1 = __nccwpck_require__(2390); const getEndpointFromRegion_1 = __nccwpck_require__(48570); const resolveEndpointsConfig = (input) => { var _a, _b; const useDualstackEndpoint = (0, util_middleware_1.normalizeProvider)((_a = input.useDualstackEndpoint) !== null && _a !== void 0 ? _a : false); const { endpoint, useFipsEndpoint, urlParser } = input; return { ...input, tls: (_b = input.tls) !== null && _b !== void 0 ? _b : true, endpoint: endpoint ? (0, util_middleware_1.normalizeProvider)(typeof endpoint === "string" ? urlParser(endpoint) : endpoint) : () => (0, getEndpointFromRegion_1.getEndpointFromRegion)({ ...input, useDualstackEndpoint, useFipsEndpoint }), isCustomEndpoint: !!endpoint, useDualstackEndpoint, }; }; exports.resolveEndpointsConfig = resolveEndpointsConfig; /***/ }), /***/ 48570: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getEndpointFromRegion = void 0; const getEndpointFromRegion = async (input) => { var _a; const { tls = true } = input; const region = await input.region(); const dnsHostRegex = new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/); if (!dnsHostRegex.test(region)) { throw new Error("Invalid region in client config"); } const useDualstackEndpoint = await input.useDualstackEndpoint(); const useFipsEndpoint = await input.useFipsEndpoint(); const { hostname } = (_a = (await input.regionInfoProvider(region, { useDualstackEndpoint, useFipsEndpoint }))) !== null && _a !== void 0 ? _a : {}; if (!hostname) { throw new Error("Cannot resolve hostname from client config"); } return input.urlParser(`${tls ? "https:" : "http:"}//${hostname}`); }; exports.getEndpointFromRegion = getEndpointFromRegion; /***/ }), /***/ 53098: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(18421), exports); tslib_1.__exportStar(__nccwpck_require__(221), exports); tslib_1.__exportStar(__nccwpck_require__(86985), exports); /***/ }), /***/ 33898: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NODE_REGION_CONFIG_FILE_OPTIONS = exports.NODE_REGION_CONFIG_OPTIONS = exports.REGION_INI_NAME = exports.REGION_ENV_NAME = void 0; exports.REGION_ENV_NAME = "AWS_REGION"; exports.REGION_INI_NAME = "region"; exports.NODE_REGION_CONFIG_OPTIONS = { environmentVariableSelector: (env) => env[exports.REGION_ENV_NAME], configFileSelector: (profile) => profile[exports.REGION_INI_NAME], default: () => { throw new Error("Region is missing"); }, }; exports.NODE_REGION_CONFIG_FILE_OPTIONS = { preferredFile: "credentials", }; /***/ }), /***/ 49506: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getRealRegion = void 0; const isFipsRegion_1 = __nccwpck_require__(43870); const getRealRegion = (region) => (0, isFipsRegion_1.isFipsRegion)(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region; exports.getRealRegion = getRealRegion; /***/ }), /***/ 221: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(33898), exports); tslib_1.__exportStar(__nccwpck_require__(87065), exports); /***/ }), /***/ 43870: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isFipsRegion = void 0; const isFipsRegion = (region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")); exports.isFipsRegion = isFipsRegion; /***/ }), /***/ 87065: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveRegionConfig = void 0; const getRealRegion_1 = __nccwpck_require__(49506); const isFipsRegion_1 = __nccwpck_require__(43870); const resolveRegionConfig = (input) => { const { region, useFipsEndpoint } = input; if (!region) { throw new Error("Region is missing"); } return { ...input, region: async () => { if (typeof region === "string") { return (0, getRealRegion_1.getRealRegion)(region); } const providedRegion = await region(); return (0, getRealRegion_1.getRealRegion)(providedRegion); }, useFipsEndpoint: async () => { const providedRegion = typeof region === "string" ? region : await region(); if ((0, isFipsRegion_1.isFipsRegion)(providedRegion)) { return true; } return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint(); }, }; }; exports.resolveRegionConfig = resolveRegionConfig; /***/ }), /***/ 19814: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 14832: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 99760: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getHostnameFromVariants = void 0; const getHostnameFromVariants = (variants = [], { useFipsEndpoint, useDualstackEndpoint }) => { var _a; return (_a = variants.find(({ tags }) => useFipsEndpoint === tags.includes("fips") && useDualstackEndpoint === tags.includes("dualstack"))) === null || _a === void 0 ? void 0 : _a.hostname; }; exports.getHostnameFromVariants = getHostnameFromVariants; /***/ }), /***/ 77792: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getRegionInfo = void 0; const getHostnameFromVariants_1 = __nccwpck_require__(99760); const getResolvedHostname_1 = __nccwpck_require__(1487); const getResolvedPartition_1 = __nccwpck_require__(44441); const getResolvedSigningRegion_1 = __nccwpck_require__(92281); const getRegionInfo = (region, { useFipsEndpoint = false, useDualstackEndpoint = false, signingService, regionHash, partitionHash, }) => { var _a, _b, _c, _d, _e, _f; const partition = (0, getResolvedPartition_1.getResolvedPartition)(region, { partitionHash }); const resolvedRegion = region in regionHash ? region : (_b = (_a = partitionHash[partition]) === null || _a === void 0 ? void 0 : _a.endpoint) !== null && _b !== void 0 ? _b : region; const hostnameOptions = { useFipsEndpoint, useDualstackEndpoint }; const regionHostname = (0, getHostnameFromVariants_1.getHostnameFromVariants)((_c = regionHash[resolvedRegion]) === null || _c === void 0 ? void 0 : _c.variants, hostnameOptions); const partitionHostname = (0, getHostnameFromVariants_1.getHostnameFromVariants)((_d = partitionHash[partition]) === null || _d === void 0 ? void 0 : _d.variants, hostnameOptions); const hostname = (0, getResolvedHostname_1.getResolvedHostname)(resolvedRegion, { regionHostname, partitionHostname }); if (hostname === undefined) { throw new Error(`Endpoint resolution failed for: ${{ resolvedRegion, useFipsEndpoint, useDualstackEndpoint }}`); } const signingRegion = (0, getResolvedSigningRegion_1.getResolvedSigningRegion)(hostname, { signingRegion: (_e = regionHash[resolvedRegion]) === null || _e === void 0 ? void 0 : _e.signingRegion, regionRegex: partitionHash[partition].regionRegex, useFipsEndpoint, }); return { partition, signingService, hostname, ...(signingRegion && { signingRegion }), ...(((_f = regionHash[resolvedRegion]) === null || _f === void 0 ? void 0 : _f.signingService) && { signingService: regionHash[resolvedRegion].signingService, }), }; }; exports.getRegionInfo = getRegionInfo; /***/ }), /***/ 1487: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getResolvedHostname = void 0; const getResolvedHostname = (resolvedRegion, { regionHostname, partitionHostname }) => regionHostname ? regionHostname : partitionHostname ? partitionHostname.replace("{region}", resolvedRegion) : undefined; exports.getResolvedHostname = getResolvedHostname; /***/ }), /***/ 44441: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getResolvedPartition = void 0; const getResolvedPartition = (region, { partitionHash }) => { var _a; return (_a = Object.keys(partitionHash || {}).find((key) => partitionHash[key].regions.includes(region))) !== null && _a !== void 0 ? _a : "aws"; }; exports.getResolvedPartition = getResolvedPartition; /***/ }), /***/ 92281: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getResolvedSigningRegion = void 0; const getResolvedSigningRegion = (hostname, { signingRegion, regionRegex, useFipsEndpoint }) => { if (signingRegion) { return signingRegion; } else if (useFipsEndpoint) { const regionRegexJs = regionRegex.replace("\\\\", "\\").replace(/^\^/g, "\\.").replace(/\$$/g, "\\."); const regionRegexmatchArray = hostname.match(regionRegexJs); if (regionRegexmatchArray) { return regionRegexmatchArray[0].slice(1, -1); } } }; exports.getResolvedSigningRegion = getResolvedSigningRegion; /***/ }), /***/ 86985: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(19814), exports); tslib_1.__exportStar(__nccwpck_require__(14832), exports); tslib_1.__exportStar(__nccwpck_require__(77792), exports); /***/ }), /***/ 18044: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Endpoint = void 0; var Endpoint; (function (Endpoint) { Endpoint["IPv4"] = "http://169.254.169.254"; Endpoint["IPv6"] = "http://[fd00:ec2::254]"; })(Endpoint = exports.Endpoint || (exports.Endpoint = {})); /***/ }), /***/ 57342: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ENDPOINT_CONFIG_OPTIONS = exports.CONFIG_ENDPOINT_NAME = exports.ENV_ENDPOINT_NAME = void 0; exports.ENV_ENDPOINT_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT"; exports.CONFIG_ENDPOINT_NAME = "ec2_metadata_service_endpoint"; exports.ENDPOINT_CONFIG_OPTIONS = { environmentVariableSelector: (env) => env[exports.ENV_ENDPOINT_NAME], configFileSelector: (profile) => profile[exports.CONFIG_ENDPOINT_NAME], default: undefined, }; /***/ }), /***/ 80991: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.EndpointMode = void 0; var EndpointMode; (function (EndpointMode) { EndpointMode["IPv4"] = "IPv4"; EndpointMode["IPv6"] = "IPv6"; })(EndpointMode = exports.EndpointMode || (exports.EndpointMode = {})); /***/ }), /***/ 88337: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ENDPOINT_MODE_CONFIG_OPTIONS = exports.CONFIG_ENDPOINT_MODE_NAME = exports.ENV_ENDPOINT_MODE_NAME = void 0; const EndpointMode_1 = __nccwpck_require__(80991); exports.ENV_ENDPOINT_MODE_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE"; exports.CONFIG_ENDPOINT_MODE_NAME = "ec2_metadata_service_endpoint_mode"; exports.ENDPOINT_MODE_CONFIG_OPTIONS = { environmentVariableSelector: (env) => env[exports.ENV_ENDPOINT_MODE_NAME], configFileSelector: (profile) => profile[exports.CONFIG_ENDPOINT_MODE_NAME], default: EndpointMode_1.EndpointMode.IPv4, }; /***/ }), /***/ 58232: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.InstanceMetadataV1FallbackError = void 0; const property_provider_1 = __nccwpck_require__(79721); class InstanceMetadataV1FallbackError extends property_provider_1.CredentialsProviderError { constructor(message, tryNextLink = true) { super(message, tryNextLink); this.tryNextLink = tryNextLink; this.name = "InstanceMetadataV1FallbackError"; Object.setPrototypeOf(this, InstanceMetadataV1FallbackError.prototype); } } exports.InstanceMetadataV1FallbackError = InstanceMetadataV1FallbackError; /***/ }), /***/ 89227: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fromContainerMetadata = exports.ENV_CMDS_AUTH_TOKEN = exports.ENV_CMDS_RELATIVE_URI = exports.ENV_CMDS_FULL_URI = void 0; const property_provider_1 = __nccwpck_require__(79721); const url_1 = __nccwpck_require__(57310); const httpRequest_1 = __nccwpck_require__(32199); const ImdsCredentials_1 = __nccwpck_require__(6894); const RemoteProviderInit_1 = __nccwpck_require__(98533); const retry_1 = __nccwpck_require__(91351); exports.ENV_CMDS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; exports.ENV_CMDS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; exports.ENV_CMDS_AUTH_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; const fromContainerMetadata = (init = {}) => { const { timeout, maxRetries } = (0, RemoteProviderInit_1.providerConfigFromInit)(init); return () => (0, retry_1.retry)(async () => { const requestOptions = await getCmdsUri(); const credsResponse = JSON.parse(await requestFromEcsImds(timeout, requestOptions)); if (!(0, ImdsCredentials_1.isImdsCredentials)(credsResponse)) { throw new property_provider_1.CredentialsProviderError("Invalid response received from instance metadata service."); } return (0, ImdsCredentials_1.fromImdsCredentials)(credsResponse); }, maxRetries); }; exports.fromContainerMetadata = fromContainerMetadata; const requestFromEcsImds = async (timeout, options) => { if (process.env[exports.ENV_CMDS_AUTH_TOKEN]) { options.headers = { ...options.headers, Authorization: process.env[exports.ENV_CMDS_AUTH_TOKEN], }; } const buffer = await (0, httpRequest_1.httpRequest)({ ...options, timeout, }); return buffer.toString(); }; const CMDS_IP = "169.254.170.2"; const GREENGRASS_HOSTS = { localhost: true, "127.0.0.1": true, }; const GREENGRASS_PROTOCOLS = { "http:": true, "https:": true, }; const getCmdsUri = async () => { if (process.env[exports.ENV_CMDS_RELATIVE_URI]) { return { hostname: CMDS_IP, path: process.env[exports.ENV_CMDS_RELATIVE_URI], }; } if (process.env[exports.ENV_CMDS_FULL_URI]) { const parsed = (0, url_1.parse)(process.env[exports.ENV_CMDS_FULL_URI]); if (!parsed.hostname || !(parsed.hostname in GREENGRASS_HOSTS)) { throw new property_provider_1.CredentialsProviderError(`${parsed.hostname} is not a valid container metadata service hostname`, false); } if (!parsed.protocol || !(parsed.protocol in GREENGRASS_PROTOCOLS)) { throw new property_provider_1.CredentialsProviderError(`${parsed.protocol} is not a valid container metadata service protocol`, false); } return { ...parsed, port: parsed.port ? parseInt(parsed.port, 10) : undefined, }; } throw new property_provider_1.CredentialsProviderError("The container metadata credential provider cannot be used unless" + ` the ${exports.ENV_CMDS_RELATIVE_URI} or ${exports.ENV_CMDS_FULL_URI} environment` + " variable is set", false); }; /***/ }), /***/ 52207: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fromInstanceMetadata = void 0; const node_config_provider_1 = __nccwpck_require__(33461); const property_provider_1 = __nccwpck_require__(79721); const InstanceMetadataV1FallbackError_1 = __nccwpck_require__(58232); const httpRequest_1 = __nccwpck_require__(32199); const ImdsCredentials_1 = __nccwpck_require__(6894); const RemoteProviderInit_1 = __nccwpck_require__(98533); const retry_1 = __nccwpck_require__(91351); const getInstanceMetadataEndpoint_1 = __nccwpck_require__(92460); const staticStabilityProvider_1 = __nccwpck_require__(74035); const IMDS_PATH = "/latest/meta-data/iam/security-credentials/"; const IMDS_TOKEN_PATH = "/latest/api/token"; const AWS_EC2_METADATA_V1_DISABLED = "AWS_EC2_METADATA_V1_DISABLED"; const PROFILE_AWS_EC2_METADATA_V1_DISABLED = "ec2_metadata_v1_disabled"; const X_AWS_EC2_METADATA_TOKEN = "x-aws-ec2-metadata-token"; const fromInstanceMetadata = (init = {}) => (0, staticStabilityProvider_1.staticStabilityProvider)(getInstanceImdsProvider(init), { logger: init.logger }); exports.fromInstanceMetadata = fromInstanceMetadata; const getInstanceImdsProvider = (init) => { let disableFetchToken = false; const { logger, profile } = init; const { timeout, maxRetries } = (0, RemoteProviderInit_1.providerConfigFromInit)(init); const getCredentials = async (maxRetries, options) => { var _a; const isImdsV1Fallback = disableFetchToken || ((_a = options.headers) === null || _a === void 0 ? void 0 : _a[X_AWS_EC2_METADATA_TOKEN]) == null; if (isImdsV1Fallback) { let fallbackBlockedFromProfile = false; let fallbackBlockedFromProcessEnv = false; const configValue = await (0, node_config_provider_1.loadConfig)({ environmentVariableSelector: (env) => { const envValue = env[AWS_EC2_METADATA_V1_DISABLED]; fallbackBlockedFromProcessEnv = !!envValue && envValue !== "false"; if (envValue === undefined) { throw new property_provider_1.CredentialsProviderError(`${AWS_EC2_METADATA_V1_DISABLED} not set in env, checking config file next.`); } return fallbackBlockedFromProcessEnv; }, configFileSelector: (profile) => { const profileValue = profile[PROFILE_AWS_EC2_METADATA_V1_DISABLED]; fallbackBlockedFromProfile = !!profileValue && profileValue !== "false"; return fallbackBlockedFromProfile; }, default: false, }, { profile, })(); if (init.ec2MetadataV1Disabled || configValue) { const causes = []; if (init.ec2MetadataV1Disabled) causes.push("credential provider initialization (runtime option ec2MetadataV1Disabled)"); if (fallbackBlockedFromProfile) causes.push(`config file profile (${PROFILE_AWS_EC2_METADATA_V1_DISABLED})`); if (fallbackBlockedFromProcessEnv) causes.push(`process environment variable (${AWS_EC2_METADATA_V1_DISABLED})`); throw new InstanceMetadataV1FallbackError_1.InstanceMetadataV1FallbackError(`AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${causes.join(", ")}].`); } } const imdsProfile = (await (0, retry_1.retry)(async () => { let profile; try { profile = await getProfile(options); } catch (err) { if (err.statusCode === 401) { disableFetchToken = false; } throw err; } return profile; }, maxRetries)).trim(); return (0, retry_1.retry)(async () => { let creds; try { creds = await getCredentialsFromProfile(imdsProfile, options); } catch (err) { if (err.statusCode === 401) { disableFetchToken = false; } throw err; } return creds; }, maxRetries); }; return async () => { const endpoint = await (0, getInstanceMetadataEndpoint_1.getInstanceMetadataEndpoint)(); if (disableFetchToken) { logger === null || logger === void 0 ? void 0 : logger.debug("AWS SDK Instance Metadata", "using v1 fallback (no token fetch)"); return getCredentials(maxRetries, { ...endpoint, timeout }); } else { let token; try { token = (await getMetadataToken({ ...endpoint, timeout })).toString(); } catch (error) { if ((error === null || error === void 0 ? void 0 : error.statusCode) === 400) { throw Object.assign(error, { message: "EC2 Metadata token request returned error", }); } else if (error.message === "TimeoutError" || [403, 404, 405].includes(error.statusCode)) { disableFetchToken = true; } logger === null || logger === void 0 ? void 0 : logger.debug("AWS SDK Instance Metadata", "using v1 fallback (initial)"); return getCredentials(maxRetries, { ...endpoint, timeout }); } return getCredentials(maxRetries, { ...endpoint, headers: { [X_AWS_EC2_METADATA_TOKEN]: token, }, timeout, }); } }; }; const getMetadataToken = async (options) => (0, httpRequest_1.httpRequest)({ ...options, path: IMDS_TOKEN_PATH, method: "PUT", headers: { "x-aws-ec2-metadata-token-ttl-seconds": "21600", }, }); const getProfile = async (options) => (await (0, httpRequest_1.httpRequest)({ ...options, path: IMDS_PATH })).toString(); const getCredentialsFromProfile = async (profile, options) => { const credsResponse = JSON.parse((await (0, httpRequest_1.httpRequest)({ ...options, path: IMDS_PATH + profile, })).toString()); if (!(0, ImdsCredentials_1.isImdsCredentials)(credsResponse)) { throw new property_provider_1.CredentialsProviderError("Invalid response received from instance metadata service."); } return (0, ImdsCredentials_1.fromImdsCredentials)(credsResponse); }; /***/ }), /***/ 7477: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getInstanceMetadataEndpoint = exports.httpRequest = void 0; const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(89227), exports); tslib_1.__exportStar(__nccwpck_require__(52207), exports); tslib_1.__exportStar(__nccwpck_require__(98533), exports); tslib_1.__exportStar(__nccwpck_require__(45036), exports); var httpRequest_1 = __nccwpck_require__(32199); Object.defineProperty(exports, "httpRequest", ({ enumerable: true, get: function () { return httpRequest_1.httpRequest; } })); var getInstanceMetadataEndpoint_1 = __nccwpck_require__(92460); Object.defineProperty(exports, "getInstanceMetadataEndpoint", ({ enumerable: true, get: function () { return getInstanceMetadataEndpoint_1.getInstanceMetadataEndpoint; } })); /***/ }), /***/ 6894: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fromImdsCredentials = exports.isImdsCredentials = void 0; const isImdsCredentials = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.AccessKeyId === "string" && typeof arg.SecretAccessKey === "string" && typeof arg.Token === "string" && typeof arg.Expiration === "string"; exports.isImdsCredentials = isImdsCredentials; const fromImdsCredentials = (creds) => ({ accessKeyId: creds.AccessKeyId, secretAccessKey: creds.SecretAccessKey, sessionToken: creds.Token, expiration: new Date(creds.Expiration), }); exports.fromImdsCredentials = fromImdsCredentials; /***/ }), /***/ 98533: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.providerConfigFromInit = exports.DEFAULT_MAX_RETRIES = exports.DEFAULT_TIMEOUT = void 0; exports.DEFAULT_TIMEOUT = 1000; exports.DEFAULT_MAX_RETRIES = 0; const providerConfigFromInit = ({ maxRetries = exports.DEFAULT_MAX_RETRIES, timeout = exports.DEFAULT_TIMEOUT, }) => ({ maxRetries, timeout }); exports.providerConfigFromInit = providerConfigFromInit; /***/ }), /***/ 32199: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.httpRequest = void 0; const property_provider_1 = __nccwpck_require__(79721); const buffer_1 = __nccwpck_require__(14300); const http_1 = __nccwpck_require__(13685); function httpRequest(options) { return new Promise((resolve, reject) => { var _a; const req = (0, http_1.request)({ method: "GET", ...options, hostname: (_a = options.hostname) === null || _a === void 0 ? void 0 : _a.replace(/^\[(.+)\]$/, "$1"), }); req.on("error", (err) => { reject(Object.assign(new property_provider_1.ProviderError("Unable to connect to instance metadata service"), err)); req.destroy(); }); req.on("timeout", () => { reject(new property_provider_1.ProviderError("TimeoutError from instance metadata service")); req.destroy(); }); req.on("response", (res) => { const { statusCode = 400 } = res; if (statusCode < 200 || 300 <= statusCode) { reject(Object.assign(new property_provider_1.ProviderError("Error response received from instance metadata service"), { statusCode })); req.destroy(); } const chunks = []; res.on("data", (chunk) => { chunks.push(chunk); }); res.on("end", () => { resolve(buffer_1.Buffer.concat(chunks)); req.destroy(); }); }); req.end(); }); } exports.httpRequest = httpRequest; /***/ }), /***/ 91351: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.retry = void 0; const retry = (toRetry, maxRetries) => { let promise = toRetry(); for (let i = 0; i < maxRetries; i++) { promise = promise.catch(toRetry); } return promise; }; exports.retry = retry; /***/ }), /***/ 45036: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 22666: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getExtendedInstanceMetadataCredentials = void 0; const STATIC_STABILITY_REFRESH_INTERVAL_SECONDS = 5 * 60; const STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS = 5 * 60; const STATIC_STABILITY_DOC_URL = "https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html"; const getExtendedInstanceMetadataCredentials = (credentials, logger) => { var _a; const refreshInterval = STATIC_STABILITY_REFRESH_INTERVAL_SECONDS + Math.floor(Math.random() * STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS); const newExpiration = new Date(Date.now() + refreshInterval * 1000); logger.warn("Attempting credential expiration extension due to a credential service availability issue. A refresh of these " + "credentials will be attempted after ${new Date(newExpiration)}.\nFor more information, please visit: " + STATIC_STABILITY_DOC_URL); const originalExpiration = (_a = credentials.originalExpiration) !== null && _a !== void 0 ? _a : credentials.expiration; return { ...credentials, ...(originalExpiration ? { originalExpiration } : {}), expiration: newExpiration, }; }; exports.getExtendedInstanceMetadataCredentials = getExtendedInstanceMetadataCredentials; /***/ }), /***/ 92460: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getInstanceMetadataEndpoint = void 0; const node_config_provider_1 = __nccwpck_require__(33461); const url_parser_1 = __nccwpck_require__(14681); const Endpoint_1 = __nccwpck_require__(18044); const EndpointConfigOptions_1 = __nccwpck_require__(57342); const EndpointMode_1 = __nccwpck_require__(80991); const EndpointModeConfigOptions_1 = __nccwpck_require__(88337); const getInstanceMetadataEndpoint = async () => (0, url_parser_1.parseUrl)((await getFromEndpointConfig()) || (await getFromEndpointModeConfig())); exports.getInstanceMetadataEndpoint = getInstanceMetadataEndpoint; const getFromEndpointConfig = async () => (0, node_config_provider_1.loadConfig)(EndpointConfigOptions_1.ENDPOINT_CONFIG_OPTIONS)(); const getFromEndpointModeConfig = async () => { const endpointMode = await (0, node_config_provider_1.loadConfig)(EndpointModeConfigOptions_1.ENDPOINT_MODE_CONFIG_OPTIONS)(); switch (endpointMode) { case EndpointMode_1.EndpointMode.IPv4: return Endpoint_1.Endpoint.IPv4; case EndpointMode_1.EndpointMode.IPv6: return Endpoint_1.Endpoint.IPv6; default: throw new Error(`Unsupported endpoint mode: ${endpointMode}.` + ` Select from ${Object.values(EndpointMode_1.EndpointMode)}`); } }; /***/ }), /***/ 74035: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.staticStabilityProvider = void 0; const getExtendedInstanceMetadataCredentials_1 = __nccwpck_require__(22666); const staticStabilityProvider = (provider, options = {}) => { const logger = (options === null || options === void 0 ? void 0 : options.logger) || console; let pastCredentials; return async () => { let credentials; try { credentials = await provider(); if (credentials.expiration && credentials.expiration.getTime() < Date.now()) { credentials = (0, getExtendedInstanceMetadataCredentials_1.getExtendedInstanceMetadataCredentials)(credentials, logger); } } catch (e) { if (pastCredentials) { logger.warn("Credential renew failed: ", e); credentials = (0, getExtendedInstanceMetadataCredentials_1.getExtendedInstanceMetadataCredentials)(pastCredentials, logger); } else { throw e; } } pastCredentials = credentials; return credentials; }; }; exports.staticStabilityProvider = staticStabilityProvider; /***/ }), /***/ 11014: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.EventStreamCodec = void 0; const crc32_1 = __nccwpck_require__(47327); const HeaderMarshaller_1 = __nccwpck_require__(74712); const splitMessage_1 = __nccwpck_require__(20597); class EventStreamCodec { constructor(toUtf8, fromUtf8) { this.headerMarshaller = new HeaderMarshaller_1.HeaderMarshaller(toUtf8, fromUtf8); this.messageBuffer = []; this.isEndOfStream = false; } feed(message) { this.messageBuffer.push(this.decode(message)); } endOfStream() { this.isEndOfStream = true; } getMessage() { const message = this.messageBuffer.pop(); const isEndOfStream = this.isEndOfStream; return { getMessage() { return message; }, isEndOfStream() { return isEndOfStream; }, }; } getAvailableMessages() { const messages = this.messageBuffer; this.messageBuffer = []; const isEndOfStream = this.isEndOfStream; return { getMessages() { return messages; }, isEndOfStream() { return isEndOfStream; }, }; } encode({ headers: rawHeaders, body }) { const headers = this.headerMarshaller.format(rawHeaders); const length = headers.byteLength + body.byteLength + 16; const out = new Uint8Array(length); const view = new DataView(out.buffer, out.byteOffset, out.byteLength); const checksum = new crc32_1.Crc32(); view.setUint32(0, length, false); view.setUint32(4, headers.byteLength, false); view.setUint32(8, checksum.update(out.subarray(0, 8)).digest(), false); out.set(headers, 12); out.set(body, headers.byteLength + 12); view.setUint32(length - 4, checksum.update(out.subarray(8, length - 4)).digest(), false); return out; } decode(message) { const { headers, body } = (0, splitMessage_1.splitMessage)(message); return { headers: this.headerMarshaller.parse(headers), body }; } formatHeaders(rawHeaders) { return this.headerMarshaller.format(rawHeaders); } } exports.EventStreamCodec = EventStreamCodec; /***/ }), /***/ 74712: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.HeaderMarshaller = void 0; const util_hex_encoding_1 = __nccwpck_require__(45364); const Int64_1 = __nccwpck_require__(46086); class HeaderMarshaller { constructor(toUtf8, fromUtf8) { this.toUtf8 = toUtf8; this.fromUtf8 = fromUtf8; } format(headers) { const chunks = []; for (const headerName of Object.keys(headers)) { const bytes = this.fromUtf8(headerName); chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); } const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); let position = 0; for (const chunk of chunks) { out.set(chunk, position); position += chunk.byteLength; } return out; } formatHeaderValue(header) { switch (header.type) { case "boolean": return Uint8Array.from([header.value ? 0 : 1]); case "byte": return Uint8Array.from([2, header.value]); case "short": const shortView = new DataView(new ArrayBuffer(3)); shortView.setUint8(0, 3); shortView.setInt16(1, header.value, false); return new Uint8Array(shortView.buffer); case "integer": const intView = new DataView(new ArrayBuffer(5)); intView.setUint8(0, 4); intView.setInt32(1, header.value, false); return new Uint8Array(intView.buffer); case "long": const longBytes = new Uint8Array(9); longBytes[0] = 5; longBytes.set(header.value.bytes, 1); return longBytes; case "binary": const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); binView.setUint8(0, 6); binView.setUint16(1, header.value.byteLength, false); const binBytes = new Uint8Array(binView.buffer); binBytes.set(header.value, 3); return binBytes; case "string": const utf8Bytes = this.fromUtf8(header.value); const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); strView.setUint8(0, 7); strView.setUint16(1, utf8Bytes.byteLength, false); const strBytes = new Uint8Array(strView.buffer); strBytes.set(utf8Bytes, 3); return strBytes; case "timestamp": const tsBytes = new Uint8Array(9); tsBytes[0] = 8; tsBytes.set(Int64_1.Int64.fromNumber(header.value.valueOf()).bytes, 1); return tsBytes; case "uuid": if (!UUID_PATTERN.test(header.value)) { throw new Error(`Invalid UUID received: ${header.value}`); } const uuidBytes = new Uint8Array(17); uuidBytes[0] = 9; uuidBytes.set((0, util_hex_encoding_1.fromHex)(header.value.replace(/\-/g, "")), 1); return uuidBytes; } } parse(headers) { const out = {}; let position = 0; while (position < headers.byteLength) { const nameLength = headers.getUint8(position++); const name = this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, nameLength)); position += nameLength; switch (headers.getUint8(position++)) { case 0: out[name] = { type: BOOLEAN_TAG, value: true, }; break; case 1: out[name] = { type: BOOLEAN_TAG, value: false, }; break; case 2: out[name] = { type: BYTE_TAG, value: headers.getInt8(position++), }; break; case 3: out[name] = { type: SHORT_TAG, value: headers.getInt16(position, false), }; position += 2; break; case 4: out[name] = { type: INT_TAG, value: headers.getInt32(position, false), }; position += 4; break; case 5: out[name] = { type: LONG_TAG, value: new Int64_1.Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)), }; position += 8; break; case 6: const binaryLength = headers.getUint16(position, false); position += 2; out[name] = { type: BINARY_TAG, value: new Uint8Array(headers.buffer, headers.byteOffset + position, binaryLength), }; position += binaryLength; break; case 7: const stringLength = headers.getUint16(position, false); position += 2; out[name] = { type: STRING_TAG, value: this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, stringLength)), }; position += stringLength; break; case 8: out[name] = { type: TIMESTAMP_TAG, value: new Date(new Int64_1.Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)).valueOf()), }; position += 8; break; case 9: const uuidBytes = new Uint8Array(headers.buffer, headers.byteOffset + position, 16); position += 16; out[name] = { type: UUID_TAG, value: `${(0, util_hex_encoding_1.toHex)(uuidBytes.subarray(0, 4))}-${(0, util_hex_encoding_1.toHex)(uuidBytes.subarray(4, 6))}-${(0, util_hex_encoding_1.toHex)(uuidBytes.subarray(6, 8))}-${(0, util_hex_encoding_1.toHex)(uuidBytes.subarray(8, 10))}-${(0, util_hex_encoding_1.toHex)(uuidBytes.subarray(10))}`, }; break; default: throw new Error(`Unrecognized header type tag`); } } return out; } } exports.HeaderMarshaller = HeaderMarshaller; var HEADER_VALUE_TYPE; (function (HEADER_VALUE_TYPE) { HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["boolTrue"] = 0] = "boolTrue"; HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["boolFalse"] = 1] = "boolFalse"; HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["byte"] = 2] = "byte"; HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["short"] = 3] = "short"; HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["integer"] = 4] = "integer"; HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["long"] = 5] = "long"; HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["byteArray"] = 6] = "byteArray"; HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["string"] = 7] = "string"; HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["timestamp"] = 8] = "timestamp"; HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["uuid"] = 9] = "uuid"; })(HEADER_VALUE_TYPE || (HEADER_VALUE_TYPE = {})); const BOOLEAN_TAG = "boolean"; const BYTE_TAG = "byte"; const SHORT_TAG = "short"; const INT_TAG = "integer"; const LONG_TAG = "long"; const BINARY_TAG = "binary"; const STRING_TAG = "string"; const TIMESTAMP_TAG = "timestamp"; const UUID_TAG = "uuid"; const UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; /***/ }), /***/ 46086: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Int64 = void 0; const util_hex_encoding_1 = __nccwpck_require__(45364); class Int64 { constructor(bytes) { this.bytes = bytes; if (bytes.byteLength !== 8) { throw new Error("Int64 buffers must be exactly 8 bytes"); } } static fromNumber(number) { if (number > 9223372036854776000 || number < -9223372036854776000) { throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`); } const bytes = new Uint8Array(8); for (let i = 7, remaining = Math.abs(Math.round(number)); i > -1 && remaining > 0; i--, remaining /= 256) { bytes[i] = remaining; } if (number < 0) { negate(bytes); } return new Int64(bytes); } valueOf() { const bytes = this.bytes.slice(0); const negative = bytes[0] & 0b10000000; if (negative) { negate(bytes); } return parseInt((0, util_hex_encoding_1.toHex)(bytes), 16) * (negative ? -1 : 1); } toString() { return String(this.valueOf()); } } exports.Int64 = Int64; function negate(bytes) { for (let i = 0; i < 8; i++) { bytes[i] ^= 0xff; } for (let i = 7; i > -1; i--) { bytes[i]++; if (bytes[i] !== 0) break; } } /***/ }), /***/ 73684: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 57255: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MessageDecoderStream = void 0; class MessageDecoderStream { constructor(options) { this.options = options; } [Symbol.asyncIterator]() { return this.asyncIterator(); } async *asyncIterator() { for await (const bytes of this.options.inputStream) { const decoded = this.options.decoder.decode(bytes); yield decoded; } } } exports.MessageDecoderStream = MessageDecoderStream; /***/ }), /***/ 52362: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MessageEncoderStream = void 0; class MessageEncoderStream { constructor(options) { this.options = options; } [Symbol.asyncIterator]() { return this.asyncIterator(); } async *asyncIterator() { for await (const msg of this.options.messageStream) { const encoded = this.options.encoder.encode(msg); yield encoded; } if (this.options.includeEndFrame) { yield new Uint8Array(0); } } } exports.MessageEncoderStream = MessageEncoderStream; /***/ }), /***/ 62379: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SmithyMessageDecoderStream = void 0; class SmithyMessageDecoderStream { constructor(options) { this.options = options; } [Symbol.asyncIterator]() { return this.asyncIterator(); } async *asyncIterator() { for await (const message of this.options.messageStream) { const deserialized = await this.options.deserializer(message); if (deserialized === undefined) continue; yield deserialized; } } } exports.SmithyMessageDecoderStream = SmithyMessageDecoderStream; /***/ }), /***/ 12484: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SmithyMessageEncoderStream = void 0; class SmithyMessageEncoderStream { constructor(options) { this.options = options; } [Symbol.asyncIterator]() { return this.asyncIterator(); } async *asyncIterator() { for await (const chunk of this.options.inputStream) { const payloadBuf = this.options.serializer(chunk); yield payloadBuf; } } } exports.SmithyMessageEncoderStream = SmithyMessageEncoderStream; /***/ }), /***/ 56459: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(11014), exports); tslib_1.__exportStar(__nccwpck_require__(74712), exports); tslib_1.__exportStar(__nccwpck_require__(46086), exports); tslib_1.__exportStar(__nccwpck_require__(73684), exports); tslib_1.__exportStar(__nccwpck_require__(57255), exports); tslib_1.__exportStar(__nccwpck_require__(52362), exports); tslib_1.__exportStar(__nccwpck_require__(62379), exports); tslib_1.__exportStar(__nccwpck_require__(12484), exports); /***/ }), /***/ 20597: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.splitMessage = void 0; const crc32_1 = __nccwpck_require__(47327); const PRELUDE_MEMBER_LENGTH = 4; const PRELUDE_LENGTH = PRELUDE_MEMBER_LENGTH * 2; const CHECKSUM_LENGTH = 4; const MINIMUM_MESSAGE_LENGTH = PRELUDE_LENGTH + CHECKSUM_LENGTH * 2; function splitMessage({ byteLength, byteOffset, buffer }) { if (byteLength < MINIMUM_MESSAGE_LENGTH) { throw new Error("Provided message too short to accommodate event stream message overhead"); } const view = new DataView(buffer, byteOffset, byteLength); const messageLength = view.getUint32(0, false); if (byteLength !== messageLength) { throw new Error("Reported message length does not match received message length"); } const headerLength = view.getUint32(PRELUDE_MEMBER_LENGTH, false); const expectedPreludeChecksum = view.getUint32(PRELUDE_LENGTH, false); const expectedMessageChecksum = view.getUint32(byteLength - CHECKSUM_LENGTH, false); const checksummer = new crc32_1.Crc32().update(new Uint8Array(buffer, byteOffset, PRELUDE_LENGTH)); if (expectedPreludeChecksum !== checksummer.digest()) { throw new Error(`The prelude checksum specified in the message (${expectedPreludeChecksum}) does not match the calculated CRC32 checksum (${checksummer.digest()})`); } checksummer.update(new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH, byteLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH))); if (expectedMessageChecksum !== checksummer.digest()) { throw new Error(`The message checksum (${checksummer.digest()}) did not match the expected value of ${expectedMessageChecksum}`); } return { headers: new DataView(buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH, headerLength), body: new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH + headerLength, messageLength - headerLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH + CHECKSUM_LENGTH)), }; } exports.splitMessage = splitMessage; /***/ }), /***/ 3081: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Hash = void 0; const util_buffer_from_1 = __nccwpck_require__(31381); const util_utf8_1 = __nccwpck_require__(41895); const buffer_1 = __nccwpck_require__(14300); const crypto_1 = __nccwpck_require__(6113); class Hash { constructor(algorithmIdentifier, secret) { this.algorithmIdentifier = algorithmIdentifier; this.secret = secret; this.reset(); } update(toHash, encoding) { this.hash.update((0, util_utf8_1.toUint8Array)(castSourceData(toHash, encoding))); } digest() { return Promise.resolve(this.hash.digest()); } reset() { this.hash = this.secret ? (0, crypto_1.createHmac)(this.algorithmIdentifier, castSourceData(this.secret)) : (0, crypto_1.createHash)(this.algorithmIdentifier); } } exports.Hash = Hash; function castSourceData(toCast, encoding) { if (buffer_1.Buffer.isBuffer(toCast)) { return toCast; } if (typeof toCast === "string") { return (0, util_buffer_from_1.fromString)(toCast, encoding); } if (ArrayBuffer.isView(toCast)) { return (0, util_buffer_from_1.fromArrayBuffer)(toCast.buffer, toCast.byteOffset, toCast.byteLength); } return (0, util_buffer_from_1.fromArrayBuffer)(toCast); } /***/ }), /***/ 10780: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isArrayBuffer = void 0; const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; exports.isArrayBuffer = isArrayBuffer; /***/ }), /***/ 82800: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getContentLengthPlugin = exports.contentLengthMiddlewareOptions = exports.contentLengthMiddleware = void 0; const protocol_http_1 = __nccwpck_require__(64418); const CONTENT_LENGTH_HEADER = "content-length"; function contentLengthMiddleware(bodyLengthChecker) { return (next) => async (args) => { const request = args.request; if (protocol_http_1.HttpRequest.isInstance(request)) { const { body, headers } = request; if (body && Object.keys(headers) .map((str) => str.toLowerCase()) .indexOf(CONTENT_LENGTH_HEADER) === -1) { try { const length = bodyLengthChecker(body); request.headers = { ...request.headers, [CONTENT_LENGTH_HEADER]: String(length), }; } catch (error) { } } } return next({ ...args, request, }); }; } exports.contentLengthMiddleware = contentLengthMiddleware; exports.contentLengthMiddlewareOptions = { step: "build", tags: ["SET_CONTENT_LENGTH", "CONTENT_LENGTH"], name: "contentLengthMiddleware", override: true, }; const getContentLengthPlugin = (options) => ({ applyToStack: (clientStack) => { clientStack.add(contentLengthMiddleware(options.bodyLengthChecker), exports.contentLengthMiddlewareOptions); }, }); exports.getContentLengthPlugin = getContentLengthPlugin; /***/ }), /***/ 465: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createConfigValueProvider = void 0; const createConfigValueProvider = (configKey, canonicalEndpointParamKey, config) => { const configProvider = async () => { var _a; const configValue = (_a = config[configKey]) !== null && _a !== void 0 ? _a : config[canonicalEndpointParamKey]; if (typeof configValue === "function") { return configValue(); } return configValue; }; if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") { return async () => { const endpoint = await configProvider(); if (endpoint && typeof endpoint === "object") { if ("url" in endpoint) { return endpoint.url.href; } if ("hostname" in endpoint) { const { protocol, hostname, port, path } = endpoint; return `${protocol}//${hostname}${port ? ":" + port : ""}${path}`; } } return endpoint; }; } return configProvider; }; exports.createConfigValueProvider = createConfigValueProvider; /***/ }), /***/ 31518: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getEndpointFromConfig = void 0; const node_config_provider_1 = __nccwpck_require__(33461); const getEndpointUrlConfig_1 = __nccwpck_require__(7574); const getEndpointFromConfig = async (serviceId) => (0, node_config_provider_1.loadConfig)((0, getEndpointUrlConfig_1.getEndpointUrlConfig)(serviceId))(); exports.getEndpointFromConfig = getEndpointFromConfig; /***/ }), /***/ 73929: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveParams = exports.getEndpointFromInstructions = void 0; const service_customizations_1 = __nccwpck_require__(13105); const createConfigValueProvider_1 = __nccwpck_require__(465); const getEndpointFromConfig_1 = __nccwpck_require__(31518); const toEndpointV1_1 = __nccwpck_require__(38938); const getEndpointFromInstructions = async (commandInput, instructionsSupplier, clientConfig, context) => { if (!clientConfig.endpoint) { const endpointFromConfig = await (0, getEndpointFromConfig_1.getEndpointFromConfig)(clientConfig.serviceId || ""); if (endpointFromConfig) { clientConfig.endpoint = () => Promise.resolve((0, toEndpointV1_1.toEndpointV1)(endpointFromConfig)); } } const endpointParams = await (0, exports.resolveParams)(commandInput, instructionsSupplier, clientConfig); if (typeof clientConfig.endpointProvider !== "function") { throw new Error("config.endpointProvider is not set."); } const endpoint = clientConfig.endpointProvider(endpointParams, context); return endpoint; }; exports.getEndpointFromInstructions = getEndpointFromInstructions; const resolveParams = async (commandInput, instructionsSupplier, clientConfig) => { var _a; const endpointParams = {}; const instructions = ((_a = instructionsSupplier === null || instructionsSupplier === void 0 ? void 0 : instructionsSupplier.getEndpointParameterInstructions) === null || _a === void 0 ? void 0 : _a.call(instructionsSupplier)) || {}; for (const [name, instruction] of Object.entries(instructions)) { switch (instruction.type) { case "staticContextParams": endpointParams[name] = instruction.value; break; case "contextParams": endpointParams[name] = commandInput[instruction.name]; break; case "clientContextParams": case "builtInParams": endpointParams[name] = await (0, createConfigValueProvider_1.createConfigValueProvider)(instruction.name, name, clientConfig)(); break; default: throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(instruction)); } } if (Object.keys(instructions).length === 0) { Object.assign(endpointParams, clientConfig); } if (String(clientConfig.serviceId).toLowerCase() === "s3") { await (0, service_customizations_1.resolveParamsForS3)(endpointParams); } return endpointParams; }; exports.resolveParams = resolveParams; /***/ }), /***/ 7574: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getEndpointUrlConfig = void 0; const shared_ini_file_loader_1 = __nccwpck_require__(43507); const ENV_ENDPOINT_URL = "AWS_ENDPOINT_URL"; const CONFIG_ENDPOINT_URL = "endpoint_url"; const getEndpointUrlConfig = (serviceId) => ({ environmentVariableSelector: (env) => { const serviceSuffixParts = serviceId.split(" ").map((w) => w.toUpperCase()); const serviceEndpointUrl = env[[ENV_ENDPOINT_URL, ...serviceSuffixParts].join("_")]; if (serviceEndpointUrl) return serviceEndpointUrl; const endpointUrl = env[ENV_ENDPOINT_URL]; if (endpointUrl) return endpointUrl; return undefined; }, configFileSelector: (profile, config) => { if (config && profile.services) { const servicesSection = config[["services", profile.services].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; if (servicesSection) { const servicePrefixParts = serviceId.split(" ").map((w) => w.toLowerCase()); const endpointUrl = servicesSection[[servicePrefixParts.join("_"), CONFIG_ENDPOINT_URL].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; if (endpointUrl) return endpointUrl; } } const endpointUrl = profile[CONFIG_ENDPOINT_URL]; if (endpointUrl) return endpointUrl; return undefined; }, default: undefined, }); exports.getEndpointUrlConfig = getEndpointUrlConfig; /***/ }), /***/ 50890: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(73929), exports); tslib_1.__exportStar(__nccwpck_require__(38938), exports); /***/ }), /***/ 38938: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toEndpointV1 = void 0; const url_parser_1 = __nccwpck_require__(14681); const toEndpointV1 = (endpoint) => { if (typeof endpoint === "object") { if ("url" in endpoint) { return (0, url_parser_1.parseUrl)(endpoint.url); } return endpoint; } return (0, url_parser_1.parseUrl)(endpoint); }; exports.toEndpointV1 = toEndpointV1; /***/ }), /***/ 55520: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.endpointMiddleware = void 0; const util_middleware_1 = __nccwpck_require__(2390); const getEndpointFromInstructions_1 = __nccwpck_require__(73929); const endpointMiddleware = ({ config, instructions, }) => { return (next, context) => async (args) => { var _a, _b, _c; const endpoint = await (0, getEndpointFromInstructions_1.getEndpointFromInstructions)(args.input, { getEndpointParameterInstructions() { return instructions; }, }, { ...config }, context); context.endpointV2 = endpoint; context.authSchemes = (_a = endpoint.properties) === null || _a === void 0 ? void 0 : _a.authSchemes; const authScheme = (_b = context.authSchemes) === null || _b === void 0 ? void 0 : _b[0]; if (authScheme) { context["signing_region"] = authScheme.signingRegion; context["signing_service"] = authScheme.signingName; const smithyContext = (0, util_middleware_1.getSmithyContext)(context); const httpAuthOption = (_c = smithyContext === null || smithyContext === void 0 ? void 0 : smithyContext.selectedHttpAuthScheme) === null || _c === void 0 ? void 0 : _c.httpAuthOption; if (httpAuthOption) { httpAuthOption.signingProperties = Object.assign(httpAuthOption.signingProperties || {}, { signing_region: authScheme.signingRegion, signingRegion: authScheme.signingRegion, signing_service: authScheme.signingName, signingName: authScheme.signingName, signingRegionSet: authScheme.signingRegionSet, }, authScheme.properties); } } return next({ ...args, }); }; }; exports.endpointMiddleware = endpointMiddleware; /***/ }), /***/ 71329: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getEndpointPlugin = exports.endpointMiddlewareOptions = void 0; const middleware_serde_1 = __nccwpck_require__(81238); const endpointMiddleware_1 = __nccwpck_require__(55520); exports.endpointMiddlewareOptions = { step: "serialize", tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"], name: "endpointV2Middleware", override: true, relation: "before", toMiddleware: middleware_serde_1.serializerMiddlewareOption.name, }; const getEndpointPlugin = (config, instructions) => ({ applyToStack: (clientStack) => { clientStack.addRelativeTo((0, endpointMiddleware_1.endpointMiddleware)({ config, instructions, }), exports.endpointMiddlewareOptions); }, }); exports.getEndpointPlugin = getEndpointPlugin; /***/ }), /***/ 82918: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(50890), exports); tslib_1.__exportStar(__nccwpck_require__(55520), exports); tslib_1.__exportStar(__nccwpck_require__(71329), exports); tslib_1.__exportStar(__nccwpck_require__(74139), exports); tslib_1.__exportStar(__nccwpck_require__(39720), exports); /***/ }), /***/ 74139: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveEndpointConfig = void 0; const util_middleware_1 = __nccwpck_require__(2390); const toEndpointV1_1 = __nccwpck_require__(38938); const resolveEndpointConfig = (input) => { var _a, _b, _c; const tls = (_a = input.tls) !== null && _a !== void 0 ? _a : true; const { endpoint } = input; const customEndpointProvider = endpoint != null ? async () => (0, toEndpointV1_1.toEndpointV1)(await (0, util_middleware_1.normalizeProvider)(endpoint)()) : undefined; const isCustomEndpoint = !!endpoint; return { ...input, endpoint: customEndpointProvider, tls, isCustomEndpoint, useDualstackEndpoint: (0, util_middleware_1.normalizeProvider)((_b = input.useDualstackEndpoint) !== null && _b !== void 0 ? _b : false), useFipsEndpoint: (0, util_middleware_1.normalizeProvider)((_c = input.useFipsEndpoint) !== null && _c !== void 0 ? _c : false), }; }; exports.resolveEndpointConfig = resolveEndpointConfig; /***/ }), /***/ 13105: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(19194), exports); /***/ }), /***/ 19194: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isArnBucketName = exports.isDnsCompatibleBucketName = exports.S3_HOSTNAME_PATTERN = exports.DOT_PATTERN = exports.resolveParamsForS3 = void 0; const resolveParamsForS3 = async (endpointParams) => { const bucket = (endpointParams === null || endpointParams === void 0 ? void 0 : endpointParams.Bucket) || ""; if (typeof endpointParams.Bucket === "string") { endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?")); } if ((0, exports.isArnBucketName)(bucket)) { if (endpointParams.ForcePathStyle === true) { throw new Error("Path-style addressing cannot be used with ARN buckets"); } } else if (!(0, exports.isDnsCompatibleBucketName)(bucket) || (bucket.indexOf(".") !== -1 && !String(endpointParams.Endpoint).startsWith("http:")) || bucket.toLowerCase() !== bucket || bucket.length < 3) { endpointParams.ForcePathStyle = true; } if (endpointParams.DisableMultiRegionAccessPoints) { endpointParams.disableMultiRegionAccessPoints = true; endpointParams.DisableMRAP = true; } return endpointParams; }; exports.resolveParamsForS3 = resolveParamsForS3; const DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/; const IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/; const DOTS_PATTERN = /\.\./; exports.DOT_PATTERN = /\./; exports.S3_HOSTNAME_PATTERN = /^(.+\.)?s3(-fips)?(\.dualstack)?[.-]([a-z0-9-]+)\./; const isDnsCompatibleBucketName = (bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName); exports.isDnsCompatibleBucketName = isDnsCompatibleBucketName; const isArnBucketName = (bucketName) => { const [arn, partition, service, region, account, typeOrId] = bucketName.split(":"); const isArn = arn === "arn" && bucketName.split(":").length >= 6; const isValidArn = [arn, partition, service, account, typeOrId].filter(Boolean).length === 5; if (isArn && !isValidArn) { throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`); } return arn === "arn" && !!partition && !!service && !!account && !!typeOrId; }; exports.isArnBucketName = isArnBucketName; /***/ }), /***/ 39720: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 80155: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AdaptiveRetryStrategy = void 0; const util_retry_1 = __nccwpck_require__(84902); const StandardRetryStrategy_1 = __nccwpck_require__(94582); class AdaptiveRetryStrategy extends StandardRetryStrategy_1.StandardRetryStrategy { constructor(maxAttemptsProvider, options) { const { rateLimiter, ...superOptions } = options !== null && options !== void 0 ? options : {}; super(maxAttemptsProvider, superOptions); this.rateLimiter = rateLimiter !== null && rateLimiter !== void 0 ? rateLimiter : new util_retry_1.DefaultRateLimiter(); this.mode = util_retry_1.RETRY_MODES.ADAPTIVE; } async retry(next, args) { return super.retry(next, args, { beforeRequest: async () => { return this.rateLimiter.getSendToken(); }, afterRequest: (response) => { this.rateLimiter.updateClientSendingRate(response); }, }); } } exports.AdaptiveRetryStrategy = AdaptiveRetryStrategy; /***/ }), /***/ 94582: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.StandardRetryStrategy = void 0; const protocol_http_1 = __nccwpck_require__(64418); const service_error_classification_1 = __nccwpck_require__(6375); const util_retry_1 = __nccwpck_require__(84902); const uuid_1 = __nccwpck_require__(75840); const defaultRetryQuota_1 = __nccwpck_require__(29991); const delayDecider_1 = __nccwpck_require__(9465); const retryDecider_1 = __nccwpck_require__(67653); const util_1 = __nccwpck_require__(42827); class StandardRetryStrategy { constructor(maxAttemptsProvider, options) { var _a, _b, _c; this.maxAttemptsProvider = maxAttemptsProvider; this.mode = util_retry_1.RETRY_MODES.STANDARD; this.retryDecider = (_a = options === null || options === void 0 ? void 0 : options.retryDecider) !== null && _a !== void 0 ? _a : retryDecider_1.defaultRetryDecider; this.delayDecider = (_b = options === null || options === void 0 ? void 0 : options.delayDecider) !== null && _b !== void 0 ? _b : delayDecider_1.defaultDelayDecider; this.retryQuota = (_c = options === null || options === void 0 ? void 0 : options.retryQuota) !== null && _c !== void 0 ? _c : (0, defaultRetryQuota_1.getDefaultRetryQuota)(util_retry_1.INITIAL_RETRY_TOKENS); } shouldRetry(error, attempts, maxAttempts) { return attempts < maxAttempts && this.retryDecider(error) && this.retryQuota.hasRetryTokens(error); } async getMaxAttempts() { let maxAttempts; try { maxAttempts = await this.maxAttemptsProvider(); } catch (error) { maxAttempts = util_retry_1.DEFAULT_MAX_ATTEMPTS; } return maxAttempts; } async retry(next, args, options) { let retryTokenAmount; let attempts = 0; let totalDelay = 0; const maxAttempts = await this.getMaxAttempts(); const { request } = args; if (protocol_http_1.HttpRequest.isInstance(request)) { request.headers[util_retry_1.INVOCATION_ID_HEADER] = (0, uuid_1.v4)(); } while (true) { try { if (protocol_http_1.HttpRequest.isInstance(request)) { request.headers[util_retry_1.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; } if (options === null || options === void 0 ? void 0 : options.beforeRequest) { await options.beforeRequest(); } const { response, output } = await next(args); if (options === null || options === void 0 ? void 0 : options.afterRequest) { options.afterRequest(response); } this.retryQuota.releaseRetryTokens(retryTokenAmount); output.$metadata.attempts = attempts + 1; output.$metadata.totalRetryDelay = totalDelay; return { response, output }; } catch (e) { const err = (0, util_1.asSdkError)(e); attempts++; if (this.shouldRetry(err, attempts, maxAttempts)) { retryTokenAmount = this.retryQuota.retrieveRetryTokens(err); const delayFromDecider = this.delayDecider((0, service_error_classification_1.isThrottlingError)(err) ? util_retry_1.THROTTLING_RETRY_DELAY_BASE : util_retry_1.DEFAULT_RETRY_DELAY_BASE, attempts); const delayFromResponse = getDelayFromRetryAfterHeader(err.$response); const delay = Math.max(delayFromResponse || 0, delayFromDecider); totalDelay += delay; await new Promise((resolve) => setTimeout(resolve, delay)); continue; } if (!err.$metadata) { err.$metadata = {}; } err.$metadata.attempts = attempts; err.$metadata.totalRetryDelay = totalDelay; throw err; } } } } exports.StandardRetryStrategy = StandardRetryStrategy; const getDelayFromRetryAfterHeader = (response) => { if (!protocol_http_1.HttpResponse.isInstance(response)) return; const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after"); if (!retryAfterHeaderName) return; const retryAfter = response.headers[retryAfterHeaderName]; const retryAfterSeconds = Number(retryAfter); if (!Number.isNaN(retryAfterSeconds)) return retryAfterSeconds * 1000; const retryAfterDate = new Date(retryAfter); return retryAfterDate.getTime() - Date.now(); }; /***/ }), /***/ 58709: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NODE_RETRY_MODE_CONFIG_OPTIONS = exports.CONFIG_RETRY_MODE = exports.ENV_RETRY_MODE = exports.resolveRetryConfig = exports.NODE_MAX_ATTEMPT_CONFIG_OPTIONS = exports.CONFIG_MAX_ATTEMPTS = exports.ENV_MAX_ATTEMPTS = void 0; const util_middleware_1 = __nccwpck_require__(2390); const util_retry_1 = __nccwpck_require__(84902); exports.ENV_MAX_ATTEMPTS = "AWS_MAX_ATTEMPTS"; exports.CONFIG_MAX_ATTEMPTS = "max_attempts"; exports.NODE_MAX_ATTEMPT_CONFIG_OPTIONS = { environmentVariableSelector: (env) => { const value = env[exports.ENV_MAX_ATTEMPTS]; if (!value) return undefined; const maxAttempt = parseInt(value); if (Number.isNaN(maxAttempt)) { throw new Error(`Environment variable ${exports.ENV_MAX_ATTEMPTS} mast be a number, got "${value}"`); } return maxAttempt; }, configFileSelector: (profile) => { const value = profile[exports.CONFIG_MAX_ATTEMPTS]; if (!value) return undefined; const maxAttempt = parseInt(value); if (Number.isNaN(maxAttempt)) { throw new Error(`Shared config file entry ${exports.CONFIG_MAX_ATTEMPTS} mast be a number, got "${value}"`); } return maxAttempt; }, default: util_retry_1.DEFAULT_MAX_ATTEMPTS, }; const resolveRetryConfig = (input) => { var _a; const { retryStrategy } = input; const maxAttempts = (0, util_middleware_1.normalizeProvider)((_a = input.maxAttempts) !== null && _a !== void 0 ? _a : util_retry_1.DEFAULT_MAX_ATTEMPTS); return { ...input, maxAttempts, retryStrategy: async () => { if (retryStrategy) { return retryStrategy; } const retryMode = await (0, util_middleware_1.normalizeProvider)(input.retryMode)(); if (retryMode === util_retry_1.RETRY_MODES.ADAPTIVE) { return new util_retry_1.AdaptiveRetryStrategy(maxAttempts); } return new util_retry_1.StandardRetryStrategy(maxAttempts); }, }; }; exports.resolveRetryConfig = resolveRetryConfig; exports.ENV_RETRY_MODE = "AWS_RETRY_MODE"; exports.CONFIG_RETRY_MODE = "retry_mode"; exports.NODE_RETRY_MODE_CONFIG_OPTIONS = { environmentVariableSelector: (env) => env[exports.ENV_RETRY_MODE], configFileSelector: (profile) => profile[exports.CONFIG_RETRY_MODE], default: util_retry_1.DEFAULT_RETRY_MODE, }; /***/ }), /***/ 29991: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getDefaultRetryQuota = void 0; const util_retry_1 = __nccwpck_require__(84902); const getDefaultRetryQuota = (initialRetryTokens, options) => { var _a, _b, _c; const MAX_CAPACITY = initialRetryTokens; const noRetryIncrement = (_a = options === null || options === void 0 ? void 0 : options.noRetryIncrement) !== null && _a !== void 0 ? _a : util_retry_1.NO_RETRY_INCREMENT; const retryCost = (_b = options === null || options === void 0 ? void 0 : options.retryCost) !== null && _b !== void 0 ? _b : util_retry_1.RETRY_COST; const timeoutRetryCost = (_c = options === null || options === void 0 ? void 0 : options.timeoutRetryCost) !== null && _c !== void 0 ? _c : util_retry_1.TIMEOUT_RETRY_COST; let availableCapacity = initialRetryTokens; const getCapacityAmount = (error) => (error.name === "TimeoutError" ? timeoutRetryCost : retryCost); const hasRetryTokens = (error) => getCapacityAmount(error) <= availableCapacity; const retrieveRetryTokens = (error) => { if (!hasRetryTokens(error)) { throw new Error("No retry token available"); } const capacityAmount = getCapacityAmount(error); availableCapacity -= capacityAmount; return capacityAmount; }; const releaseRetryTokens = (capacityReleaseAmount) => { availableCapacity += capacityReleaseAmount !== null && capacityReleaseAmount !== void 0 ? capacityReleaseAmount : noRetryIncrement; availableCapacity = Math.min(availableCapacity, MAX_CAPACITY); }; return Object.freeze({ hasRetryTokens, retrieveRetryTokens, releaseRetryTokens, }); }; exports.getDefaultRetryQuota = getDefaultRetryQuota; /***/ }), /***/ 9465: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.defaultDelayDecider = void 0; const util_retry_1 = __nccwpck_require__(84902); const defaultDelayDecider = (delayBase, attempts) => Math.floor(Math.min(util_retry_1.MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)); exports.defaultDelayDecider = defaultDelayDecider; /***/ }), /***/ 96039: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(80155), exports); tslib_1.__exportStar(__nccwpck_require__(94582), exports); tslib_1.__exportStar(__nccwpck_require__(58709), exports); tslib_1.__exportStar(__nccwpck_require__(9465), exports); tslib_1.__exportStar(__nccwpck_require__(76556), exports); tslib_1.__exportStar(__nccwpck_require__(67653), exports); tslib_1.__exportStar(__nccwpck_require__(81434), exports); /***/ }), /***/ 76556: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getOmitRetryHeadersPlugin = exports.omitRetryHeadersMiddlewareOptions = exports.omitRetryHeadersMiddleware = void 0; const protocol_http_1 = __nccwpck_require__(64418); const util_retry_1 = __nccwpck_require__(84902); const omitRetryHeadersMiddleware = () => (next) => async (args) => { const { request } = args; if (protocol_http_1.HttpRequest.isInstance(request)) { delete request.headers[util_retry_1.INVOCATION_ID_HEADER]; delete request.headers[util_retry_1.REQUEST_HEADER]; } return next(args); }; exports.omitRetryHeadersMiddleware = omitRetryHeadersMiddleware; exports.omitRetryHeadersMiddlewareOptions = { name: "omitRetryHeadersMiddleware", tags: ["RETRY", "HEADERS", "OMIT_RETRY_HEADERS"], relation: "before", toMiddleware: "awsAuthMiddleware", override: true, }; const getOmitRetryHeadersPlugin = (options) => ({ applyToStack: (clientStack) => { clientStack.addRelativeTo((0, exports.omitRetryHeadersMiddleware)(), exports.omitRetryHeadersMiddlewareOptions); }, }); exports.getOmitRetryHeadersPlugin = getOmitRetryHeadersPlugin; /***/ }), /***/ 67653: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.defaultRetryDecider = void 0; const service_error_classification_1 = __nccwpck_require__(6375); const defaultRetryDecider = (error) => { if (!error) { return false; } return (0, service_error_classification_1.isRetryableByTrait)(error) || (0, service_error_classification_1.isClockSkewError)(error) || (0, service_error_classification_1.isThrottlingError)(error) || (0, service_error_classification_1.isTransientError)(error); }; exports.defaultRetryDecider = defaultRetryDecider; /***/ }), /***/ 81434: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getRetryAfterHint = exports.getRetryPlugin = exports.retryMiddlewareOptions = exports.retryMiddleware = void 0; const protocol_http_1 = __nccwpck_require__(64418); const service_error_classification_1 = __nccwpck_require__(6375); const util_retry_1 = __nccwpck_require__(84902); const uuid_1 = __nccwpck_require__(75840); const util_1 = __nccwpck_require__(42827); const retryMiddleware = (options) => (next, context) => async (args) => { let retryStrategy = await options.retryStrategy(); const maxAttempts = await options.maxAttempts(); if (isRetryStrategyV2(retryStrategy)) { retryStrategy = retryStrategy; let retryToken = await retryStrategy.acquireInitialRetryToken(context["partition_id"]); let lastError = new Error(); let attempts = 0; let totalRetryDelay = 0; const { request } = args; if (protocol_http_1.HttpRequest.isInstance(request)) { request.headers[util_retry_1.INVOCATION_ID_HEADER] = (0, uuid_1.v4)(); } while (true) { try { if (protocol_http_1.HttpRequest.isInstance(request)) { request.headers[util_retry_1.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; } const { response, output } = await next(args); retryStrategy.recordSuccess(retryToken); output.$metadata.attempts = attempts + 1; output.$metadata.totalRetryDelay = totalRetryDelay; return { response, output }; } catch (e) { const retryErrorInfo = getRetryErrorInfo(e); lastError = (0, util_1.asSdkError)(e); try { retryToken = await retryStrategy.refreshRetryTokenForRetry(retryToken, retryErrorInfo); } catch (refreshError) { if (!lastError.$metadata) { lastError.$metadata = {}; } lastError.$metadata.attempts = attempts + 1; lastError.$metadata.totalRetryDelay = totalRetryDelay; throw lastError; } attempts = retryToken.getRetryCount(); const delay = retryToken.getRetryDelay(); totalRetryDelay += delay; await new Promise((resolve) => setTimeout(resolve, delay)); } } } else { retryStrategy = retryStrategy; if (retryStrategy === null || retryStrategy === void 0 ? void 0 : retryStrategy.mode) context.userAgent = [...(context.userAgent || []), ["cfg/retry-mode", retryStrategy.mode]]; return retryStrategy.retry(next, args); } }; exports.retryMiddleware = retryMiddleware; const isRetryStrategyV2 = (retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== "undefined" && typeof retryStrategy.refreshRetryTokenForRetry !== "undefined" && typeof retryStrategy.recordSuccess !== "undefined"; const getRetryErrorInfo = (error) => { const errorInfo = { errorType: getRetryErrorType(error), }; const retryAfterHint = (0, exports.getRetryAfterHint)(error.$response); if (retryAfterHint) { errorInfo.retryAfterHint = retryAfterHint; } return errorInfo; }; const getRetryErrorType = (error) => { if ((0, service_error_classification_1.isThrottlingError)(error)) return "THROTTLING"; if ((0, service_error_classification_1.isTransientError)(error)) return "TRANSIENT"; if ((0, service_error_classification_1.isServerError)(error)) return "SERVER_ERROR"; return "CLIENT_ERROR"; }; exports.retryMiddlewareOptions = { name: "retryMiddleware", tags: ["RETRY"], step: "finalizeRequest", priority: "high", override: true, }; const getRetryPlugin = (options) => ({ applyToStack: (clientStack) => { clientStack.add((0, exports.retryMiddleware)(options), exports.retryMiddlewareOptions); }, }); exports.getRetryPlugin = getRetryPlugin; const getRetryAfterHint = (response) => { if (!protocol_http_1.HttpResponse.isInstance(response)) return; const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after"); if (!retryAfterHeaderName) return; const retryAfter = response.headers[retryAfterHeaderName]; const retryAfterSeconds = Number(retryAfter); if (!Number.isNaN(retryAfterSeconds)) return new Date(retryAfterSeconds * 1000); const retryAfterDate = new Date(retryAfter); return retryAfterDate; }; exports.getRetryAfterHint = getRetryAfterHint; /***/ }), /***/ 42827: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.asSdkError = void 0; const asSdkError = (error) => { if (error instanceof Error) return error; if (error instanceof Object) return Object.assign(new Error(), error); if (typeof error === "string") return new Error(error); return new Error(`AWS SDK error wrapper for ${error}`); }; exports.asSdkError = asSdkError; /***/ }), /***/ 21595: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.deserializerMiddleware = void 0; const deserializerMiddleware = (options, deserializer) => (next, context) => async (args) => { const { response } = await next(args); try { const parsed = await deserializer(response, options); return { response, output: parsed, }; } catch (error) { Object.defineProperty(error, "$response", { value: response, }); if (!("$metadata" in error)) { const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; error.message += "\n " + hint; } throw error; } }; exports.deserializerMiddleware = deserializerMiddleware; /***/ }), /***/ 81238: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(21595), exports); tslib_1.__exportStar(__nccwpck_require__(72338), exports); tslib_1.__exportStar(__nccwpck_require__(23566), exports); /***/ }), /***/ 72338: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getSerdePlugin = exports.serializerMiddlewareOption = exports.deserializerMiddlewareOption = void 0; const deserializerMiddleware_1 = __nccwpck_require__(21595); const serializerMiddleware_1 = __nccwpck_require__(23566); exports.deserializerMiddlewareOption = { name: "deserializerMiddleware", step: "deserialize", tags: ["DESERIALIZER"], override: true, }; exports.serializerMiddlewareOption = { name: "serializerMiddleware", step: "serialize", tags: ["SERIALIZER"], override: true, }; function getSerdePlugin(config, serializer, deserializer) { return { applyToStack: (commandStack) => { commandStack.add((0, deserializerMiddleware_1.deserializerMiddleware)(config, deserializer), exports.deserializerMiddlewareOption); commandStack.add((0, serializerMiddleware_1.serializerMiddleware)(config, serializer), exports.serializerMiddlewareOption); }, }; } exports.getSerdePlugin = getSerdePlugin; /***/ }), /***/ 23566: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.serializerMiddleware = void 0; const serializerMiddleware = (options, serializer) => (next, context) => async (args) => { var _a; const endpoint = ((_a = context.endpointV2) === null || _a === void 0 ? void 0 : _a.url) && options.urlParser ? async () => options.urlParser(context.endpointV2.url) : options.endpoint; if (!endpoint) { throw new Error("No valid endpoint provider available."); } const request = await serializer(args.input, { ...options, endpoint }); return next({ ...args, request, }); }; exports.serializerMiddleware = serializerMiddleware; /***/ }), /***/ 2404: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.constructStack = void 0; const getAllAliases = (name, aliases) => { const _aliases = []; if (name) { _aliases.push(name); } if (aliases) { for (const alias of aliases) { _aliases.push(alias); } } return _aliases; }; const getMiddlewareNameWithAliases = (name, aliases) => { return `${name || "anonymous"}${aliases && aliases.length > 0 ? ` (a.k.a. ${aliases.join(",")})` : ""}`; }; const constructStack = () => { let absoluteEntries = []; let relativeEntries = []; let identifyOnResolve = false; const entriesNameSet = new Set(); const sort = (entries) => entries.sort((a, b) => stepWeights[b.step] - stepWeights[a.step] || priorityWeights[b.priority || "normal"] - priorityWeights[a.priority || "normal"]); const removeByName = (toRemove) => { let isRemoved = false; const filterCb = (entry) => { const aliases = getAllAliases(entry.name, entry.aliases); if (aliases.includes(toRemove)) { isRemoved = true; for (const alias of aliases) { entriesNameSet.delete(alias); } return false; } return true; }; absoluteEntries = absoluteEntries.filter(filterCb); relativeEntries = relativeEntries.filter(filterCb); return isRemoved; }; const removeByReference = (toRemove) => { let isRemoved = false; const filterCb = (entry) => { if (entry.middleware === toRemove) { isRemoved = true; for (const alias of getAllAliases(entry.name, entry.aliases)) { entriesNameSet.delete(alias); } return false; } return true; }; absoluteEntries = absoluteEntries.filter(filterCb); relativeEntries = relativeEntries.filter(filterCb); return isRemoved; }; const cloneTo = (toStack) => { var _a; absoluteEntries.forEach((entry) => { toStack.add(entry.middleware, { ...entry }); }); relativeEntries.forEach((entry) => { toStack.addRelativeTo(entry.middleware, { ...entry }); }); (_a = toStack.identifyOnResolve) === null || _a === void 0 ? void 0 : _a.call(toStack, stack.identifyOnResolve()); return toStack; }; const expandRelativeMiddlewareList = (from) => { const expandedMiddlewareList = []; from.before.forEach((entry) => { if (entry.before.length === 0 && entry.after.length === 0) { expandedMiddlewareList.push(entry); } else { expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); } }); expandedMiddlewareList.push(from); from.after.reverse().forEach((entry) => { if (entry.before.length === 0 && entry.after.length === 0) { expandedMiddlewareList.push(entry); } else { expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); } }); return expandedMiddlewareList; }; const getMiddlewareList = (debug = false) => { const normalizedAbsoluteEntries = []; const normalizedRelativeEntries = []; const normalizedEntriesNameMap = {}; absoluteEntries.forEach((entry) => { const normalizedEntry = { ...entry, before: [], after: [], }; for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { normalizedEntriesNameMap[alias] = normalizedEntry; } normalizedAbsoluteEntries.push(normalizedEntry); }); relativeEntries.forEach((entry) => { const normalizedEntry = { ...entry, before: [], after: [], }; for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { normalizedEntriesNameMap[alias] = normalizedEntry; } normalizedRelativeEntries.push(normalizedEntry); }); normalizedRelativeEntries.forEach((entry) => { if (entry.toMiddleware) { const toMiddleware = normalizedEntriesNameMap[entry.toMiddleware]; if (toMiddleware === undefined) { if (debug) { return; } throw new Error(`${entry.toMiddleware} is not found when adding ` + `${getMiddlewareNameWithAliases(entry.name, entry.aliases)} ` + `middleware ${entry.relation} ${entry.toMiddleware}`); } if (entry.relation === "after") { toMiddleware.after.push(entry); } if (entry.relation === "before") { toMiddleware.before.push(entry); } } }); const mainChain = sort(normalizedAbsoluteEntries) .map(expandRelativeMiddlewareList) .reduce((wholeList, expandedMiddlewareList) => { wholeList.push(...expandedMiddlewareList); return wholeList; }, []); return mainChain; }; const stack = { add: (middleware, options = {}) => { const { name, override, aliases: _aliases } = options; const entry = { step: "initialize", priority: "normal", middleware, ...options, }; const aliases = getAllAliases(name, _aliases); if (aliases.length > 0) { if (aliases.some((alias) => entriesNameSet.has(alias))) { if (!override) throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); for (const alias of aliases) { const toOverrideIndex = absoluteEntries.findIndex((entry) => { var _a; return entry.name === alias || ((_a = entry.aliases) === null || _a === void 0 ? void 0 : _a.some((a) => a === alias)); }); if (toOverrideIndex === -1) { continue; } const toOverride = absoluteEntries[toOverrideIndex]; if (toOverride.step !== entry.step || entry.priority !== toOverride.priority) { throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware with ` + `${toOverride.priority} priority in ${toOverride.step} step cannot ` + `be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware with ` + `${entry.priority} priority in ${entry.step} step.`); } absoluteEntries.splice(toOverrideIndex, 1); } } for (const alias of aliases) { entriesNameSet.add(alias); } } absoluteEntries.push(entry); }, addRelativeTo: (middleware, options) => { const { name, override, aliases: _aliases } = options; const entry = { middleware, ...options, }; const aliases = getAllAliases(name, _aliases); if (aliases.length > 0) { if (aliases.some((alias) => entriesNameSet.has(alias))) { if (!override) throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); for (const alias of aliases) { const toOverrideIndex = relativeEntries.findIndex((entry) => { var _a; return entry.name === alias || ((_a = entry.aliases) === null || _a === void 0 ? void 0 : _a.some((a) => a === alias)); }); if (toOverrideIndex === -1) { continue; } const toOverride = relativeEntries[toOverrideIndex]; if (toOverride.toMiddleware !== entry.toMiddleware || toOverride.relation !== entry.relation) { throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware ` + `${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden ` + `by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware ${entry.relation} ` + `"${entry.toMiddleware}" middleware.`); } relativeEntries.splice(toOverrideIndex, 1); } } for (const alias of aliases) { entriesNameSet.add(alias); } } relativeEntries.push(entry); }, clone: () => cloneTo((0, exports.constructStack)()), use: (plugin) => { plugin.applyToStack(stack); }, remove: (toRemove) => { if (typeof toRemove === "string") return removeByName(toRemove); else return removeByReference(toRemove); }, removeByTag: (toRemove) => { let isRemoved = false; const filterCb = (entry) => { const { tags, name, aliases: _aliases } = entry; if (tags && tags.includes(toRemove)) { const aliases = getAllAliases(name, _aliases); for (const alias of aliases) { entriesNameSet.delete(alias); } isRemoved = true; return false; } return true; }; absoluteEntries = absoluteEntries.filter(filterCb); relativeEntries = relativeEntries.filter(filterCb); return isRemoved; }, concat: (from) => { var _a, _b; const cloned = cloneTo((0, exports.constructStack)()); cloned.use(from); cloned.identifyOnResolve(identifyOnResolve || cloned.identifyOnResolve() || ((_b = (_a = from.identifyOnResolve) === null || _a === void 0 ? void 0 : _a.call(from)) !== null && _b !== void 0 ? _b : false)); return cloned; }, applyToStack: cloneTo, identify: () => { return getMiddlewareList(true).map((mw) => { var _a; const step = (_a = mw.step) !== null && _a !== void 0 ? _a : mw.relation + " " + mw.toMiddleware; return getMiddlewareNameWithAliases(mw.name, mw.aliases) + " - " + step; }); }, identifyOnResolve(toggle) { if (typeof toggle === "boolean") identifyOnResolve = toggle; return identifyOnResolve; }, resolve: (handler, context) => { for (const middleware of getMiddlewareList() .map((entry) => entry.middleware) .reverse()) { handler = middleware(handler, context); } if (identifyOnResolve) { console.log(stack.identify()); } return handler; }, }; return stack; }; exports.constructStack = constructStack; const stepWeights = { initialize: 5, serialize: 4, build: 3, finalizeRequest: 2, deserialize: 1, }; const priorityWeights = { high: 3, normal: 2, low: 1, }; /***/ }), /***/ 97911: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(2404), exports); /***/ }), /***/ 54766: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.loadConfig = void 0; const property_provider_1 = __nccwpck_require__(79721); const fromEnv_1 = __nccwpck_require__(15606); const fromSharedConfigFiles_1 = __nccwpck_require__(45784); const fromStatic_1 = __nccwpck_require__(23091); const loadConfig = ({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => (0, property_provider_1.memoize)((0, property_provider_1.chain)((0, fromEnv_1.fromEnv)(environmentVariableSelector), (0, fromSharedConfigFiles_1.fromSharedConfigFiles)(configFileSelector, configuration), (0, fromStatic_1.fromStatic)(defaultValue))); exports.loadConfig = loadConfig; /***/ }), /***/ 15606: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fromEnv = void 0; const property_provider_1 = __nccwpck_require__(79721); const fromEnv = (envVarSelector) => async () => { try { const config = envVarSelector(process.env); if (config === undefined) { throw new Error(); } return config; } catch (e) { throw new property_provider_1.CredentialsProviderError(e.message || `Cannot load config from environment variables with getter: ${envVarSelector}`); } }; exports.fromEnv = fromEnv; /***/ }), /***/ 45784: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fromSharedConfigFiles = void 0; const property_provider_1 = __nccwpck_require__(79721); const shared_ini_file_loader_1 = __nccwpck_require__(43507); const fromSharedConfigFiles = (configSelector, { preferredFile = "config", ...init } = {}) => async () => { const profile = (0, shared_ini_file_loader_1.getProfileName)(init); const { configFile, credentialsFile } = await (0, shared_ini_file_loader_1.loadSharedConfigFiles)(init); const profileFromCredentials = credentialsFile[profile] || {}; const profileFromConfig = configFile[profile] || {}; const mergedProfile = preferredFile === "config" ? { ...profileFromCredentials, ...profileFromConfig } : { ...profileFromConfig, ...profileFromCredentials }; try { const cfgFile = preferredFile === "config" ? configFile : credentialsFile; const configValue = configSelector(mergedProfile, cfgFile); if (configValue === undefined) { throw new Error(); } return configValue; } catch (e) { throw new property_provider_1.CredentialsProviderError(e.message || `Cannot load config for profile ${profile} in SDK configuration files with getter: ${configSelector}`); } }; exports.fromSharedConfigFiles = fromSharedConfigFiles; /***/ }), /***/ 23091: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fromStatic = void 0; const property_provider_1 = __nccwpck_require__(79721); const isFunction = (func) => typeof func === "function"; const fromStatic = (defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : (0, property_provider_1.fromStatic)(defaultValue); exports.fromStatic = fromStatic; /***/ }), /***/ 33461: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(54766), exports); /***/ }), /***/ 33946: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NODEJS_TIMEOUT_ERROR_CODES = void 0; exports.NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; /***/ }), /***/ 70508: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getTransformedHeaders = void 0; const getTransformedHeaders = (headers) => { const transformedHeaders = {}; for (const name of Object.keys(headers)) { const headerValues = headers[name]; transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; } return transformedHeaders; }; exports.getTransformedHeaders = getTransformedHeaders; /***/ }), /***/ 20258: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(96948), exports); tslib_1.__exportStar(__nccwpck_require__(46999), exports); tslib_1.__exportStar(__nccwpck_require__(81030), exports); /***/ }), /***/ 96948: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NodeHttpHandler = exports.DEFAULT_REQUEST_TIMEOUT = void 0; const protocol_http_1 = __nccwpck_require__(64418); const querystring_builder_1 = __nccwpck_require__(68031); const http_1 = __nccwpck_require__(13685); const https_1 = __nccwpck_require__(95687); const constants_1 = __nccwpck_require__(33946); const get_transformed_headers_1 = __nccwpck_require__(70508); const set_connection_timeout_1 = __nccwpck_require__(25545); const set_socket_keep_alive_1 = __nccwpck_require__(83751); const set_socket_timeout_1 = __nccwpck_require__(42618); const write_request_body_1 = __nccwpck_require__(73766); exports.DEFAULT_REQUEST_TIMEOUT = 0; class NodeHttpHandler { constructor(options) { this.metadata = { handlerProtocol: "http/1.1" }; this.configProvider = new Promise((resolve, reject) => { if (typeof options === "function") { options() .then((_options) => { resolve(this.resolveDefaultConfig(_options)); }) .catch(reject); } else { resolve(this.resolveDefaultConfig(options)); } }); } resolveDefaultConfig(options) { const { requestTimeout, connectionTimeout, socketTimeout, httpAgent, httpsAgent } = options || {}; const keepAlive = true; const maxSockets = 50; return { connectionTimeout, requestTimeout: requestTimeout !== null && requestTimeout !== void 0 ? requestTimeout : socketTimeout, httpAgent: httpAgent || new http_1.Agent({ keepAlive, maxSockets }), httpsAgent: httpsAgent || new https_1.Agent({ keepAlive, maxSockets }), }; } destroy() { var _a, _b, _c, _d; (_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.httpAgent) === null || _b === void 0 ? void 0 : _b.destroy(); (_d = (_c = this.config) === null || _c === void 0 ? void 0 : _c.httpsAgent) === null || _d === void 0 ? void 0 : _d.destroy(); } async handle(request, { abortSignal } = {}) { if (!this.config) { this.config = await this.configProvider; } return new Promise((_resolve, _reject) => { var _a, _b; let writeRequestBodyPromise = undefined; const resolve = async (arg) => { await writeRequestBodyPromise; _resolve(arg); }; const reject = async (arg) => { await writeRequestBodyPromise; _reject(arg); }; if (!this.config) { throw new Error("Node HTTP request handler config is not resolved"); } if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) { const abortError = new Error("Request aborted"); abortError.name = "AbortError"; reject(abortError); return; } const isSSL = request.protocol === "https:"; const queryString = (0, querystring_builder_1.buildQueryString)(request.query || {}); let auth = undefined; if (request.username != null || request.password != null) { const username = (_a = request.username) !== null && _a !== void 0 ? _a : ""; const password = (_b = request.password) !== null && _b !== void 0 ? _b : ""; auth = `${username}:${password}`; } let path = request.path; if (queryString) { path += `?${queryString}`; } if (request.fragment) { path += `#${request.fragment}`; } const nodeHttpsOptions = { headers: request.headers, host: request.hostname, method: request.method, path, port: request.port, agent: isSSL ? this.config.httpsAgent : this.config.httpAgent, auth, }; const requestFunc = isSSL ? https_1.request : http_1.request; const req = requestFunc(nodeHttpsOptions, (res) => { const httpResponse = new protocol_http_1.HttpResponse({ statusCode: res.statusCode || -1, reason: res.statusMessage, headers: (0, get_transformed_headers_1.getTransformedHeaders)(res.headers), body: res, }); resolve({ response: httpResponse }); }); req.on("error", (err) => { if (constants_1.NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { reject(Object.assign(err, { name: "TimeoutError" })); } else { reject(err); } }); (0, set_connection_timeout_1.setConnectionTimeout)(req, reject, this.config.connectionTimeout); (0, set_socket_timeout_1.setSocketTimeout)(req, reject, this.config.requestTimeout); if (abortSignal) { abortSignal.onabort = () => { req.abort(); const abortError = new Error("Request aborted"); abortError.name = "AbortError"; reject(abortError); }; } const httpAgent = nodeHttpsOptions.agent; if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { (0, set_socket_keep_alive_1.setSocketKeepAlive)(req, { keepAlive: httpAgent.keepAlive, keepAliveMsecs: httpAgent.keepAliveMsecs, }); } writeRequestBodyPromise = (0, write_request_body_1.writeRequestBody)(req, request, this.config.requestTimeout).catch(_reject); }); } updateHttpClientConfig(key, value) { this.config = undefined; this.configProvider = this.configProvider.then((config) => { return { ...config, [key]: value, }; }); } httpHandlerConfigs() { var _a; return (_a = this.config) !== null && _a !== void 0 ? _a : {}; } } exports.NodeHttpHandler = NodeHttpHandler; /***/ }), /***/ 5771: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NodeHttp2ConnectionManager = void 0; const tslib_1 = __nccwpck_require__(4351); const http2_1 = tslib_1.__importDefault(__nccwpck_require__(85158)); const node_http2_connection_pool_1 = __nccwpck_require__(95157); class NodeHttp2ConnectionManager { constructor(config) { this.sessionCache = new Map(); this.config = config; if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { throw new RangeError("maxConcurrency must be greater than zero."); } } lease(requestContext, connectionConfiguration) { const url = this.getUrlString(requestContext); const existingPool = this.sessionCache.get(url); if (existingPool) { const existingSession = existingPool.poll(); if (existingSession && !this.config.disableConcurrency) { return existingSession; } } const session = http2_1.default.connect(url); if (this.config.maxConcurrency) { session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => { if (err) { throw new Error("Fail to set maxConcurrentStreams to " + this.config.maxConcurrency + "when creating new session for " + requestContext.destination.toString()); } }); } session.unref(); const destroySessionCb = () => { session.destroy(); this.deleteSession(url, session); }; session.on("goaway", destroySessionCb); session.on("error", destroySessionCb); session.on("frameError", destroySessionCb); session.on("close", () => this.deleteSession(url, session)); if (connectionConfiguration.requestTimeout) { session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb); } const connectionPool = this.sessionCache.get(url) || new node_http2_connection_pool_1.NodeHttp2ConnectionPool(); connectionPool.offerLast(session); this.sessionCache.set(url, connectionPool); return session; } deleteSession(authority, session) { const existingConnectionPool = this.sessionCache.get(authority); if (!existingConnectionPool) { return; } if (!existingConnectionPool.contains(session)) { return; } existingConnectionPool.remove(session); this.sessionCache.set(authority, existingConnectionPool); } release(requestContext, session) { var _a; const cacheKey = this.getUrlString(requestContext); (_a = this.sessionCache.get(cacheKey)) === null || _a === void 0 ? void 0 : _a.offerLast(session); } destroy() { for (const [key, connectionPool] of this.sessionCache) { for (const session of connectionPool) { if (!session.destroyed) { session.destroy(); } connectionPool.remove(session); } this.sessionCache.delete(key); } } setMaxConcurrentStreams(maxConcurrentStreams) { if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { throw new RangeError("maxConcurrentStreams must be greater than zero."); } this.config.maxConcurrency = maxConcurrentStreams; } setDisableConcurrentStreams(disableConcurrentStreams) { this.config.disableConcurrency = disableConcurrentStreams; } getUrlString(request) { return request.destination.toString(); } } exports.NodeHttp2ConnectionManager = NodeHttp2ConnectionManager; /***/ }), /***/ 95157: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NodeHttp2ConnectionPool = void 0; class NodeHttp2ConnectionPool { constructor(sessions) { this.sessions = []; this.sessions = sessions !== null && sessions !== void 0 ? sessions : []; } poll() { if (this.sessions.length > 0) { return this.sessions.shift(); } } offerLast(session) { this.sessions.push(session); } contains(session) { return this.sessions.includes(session); } remove(session) { this.sessions = this.sessions.filter((s) => s !== session); } [Symbol.iterator]() { return this.sessions[Symbol.iterator](); } destroy(connection) { for (const session of this.sessions) { if (session === connection) { if (!session.destroyed) { session.destroy(); } } } } } exports.NodeHttp2ConnectionPool = NodeHttp2ConnectionPool; /***/ }), /***/ 46999: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NodeHttp2Handler = void 0; const protocol_http_1 = __nccwpck_require__(64418); const querystring_builder_1 = __nccwpck_require__(68031); const http2_1 = __nccwpck_require__(85158); const get_transformed_headers_1 = __nccwpck_require__(70508); const node_http2_connection_manager_1 = __nccwpck_require__(5771); const write_request_body_1 = __nccwpck_require__(73766); class NodeHttp2Handler { constructor(options) { this.metadata = { handlerProtocol: "h2" }; this.connectionManager = new node_http2_connection_manager_1.NodeHttp2ConnectionManager({}); this.configProvider = new Promise((resolve, reject) => { if (typeof options === "function") { options() .then((opts) => { resolve(opts || {}); }) .catch(reject); } else { resolve(options || {}); } }); } destroy() { this.connectionManager.destroy(); } async handle(request, { abortSignal } = {}) { if (!this.config) { this.config = await this.configProvider; this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false); if (this.config.maxConcurrentStreams) { this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams); } } const { requestTimeout, disableConcurrentStreams } = this.config; return new Promise((_resolve, _reject) => { var _a, _b, _c; let fulfilled = false; let writeRequestBodyPromise = undefined; const resolve = async (arg) => { await writeRequestBodyPromise; _resolve(arg); }; const reject = async (arg) => { await writeRequestBodyPromise; _reject(arg); }; if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) { fulfilled = true; const abortError = new Error("Request aborted"); abortError.name = "AbortError"; reject(abortError); return; } const { hostname, method, port, protocol, query } = request; let auth = ""; if (request.username != null || request.password != null) { const username = (_a = request.username) !== null && _a !== void 0 ? _a : ""; const password = (_b = request.password) !== null && _b !== void 0 ? _b : ""; auth = `${username}:${password}@`; } const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`; const requestContext = { destination: new URL(authority) }; const session = this.connectionManager.lease(requestContext, { requestTimeout: (_c = this.config) === null || _c === void 0 ? void 0 : _c.sessionTimeout, disableConcurrentStreams: disableConcurrentStreams || false, }); const rejectWithDestroy = (err) => { if (disableConcurrentStreams) { this.destroySession(session); } fulfilled = true; reject(err); }; const queryString = (0, querystring_builder_1.buildQueryString)(query || {}); let path = request.path; if (queryString) { path += `?${queryString}`; } if (request.fragment) { path += `#${request.fragment}`; } const req = session.request({ ...request.headers, [http2_1.constants.HTTP2_HEADER_PATH]: path, [http2_1.constants.HTTP2_HEADER_METHOD]: method, }); session.ref(); req.on("response", (headers) => { const httpResponse = new protocol_http_1.HttpResponse({ statusCode: headers[":status"] || -1, headers: (0, get_transformed_headers_1.getTransformedHeaders)(headers), body: req, }); fulfilled = true; resolve({ response: httpResponse }); if (disableConcurrentStreams) { session.close(); this.connectionManager.deleteSession(authority, session); } }); if (requestTimeout) { req.setTimeout(requestTimeout, () => { req.close(); const timeoutError = new Error(`Stream timed out because of no activity for ${requestTimeout} ms`); timeoutError.name = "TimeoutError"; rejectWithDestroy(timeoutError); }); } if (abortSignal) { abortSignal.onabort = () => { req.close(); const abortError = new Error("Request aborted"); abortError.name = "AbortError"; rejectWithDestroy(abortError); }; } req.on("frameError", (type, code, id) => { rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`)); }); req.on("error", rejectWithDestroy); req.on("aborted", () => { rejectWithDestroy(new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`)); }); req.on("close", () => { session.unref(); if (disableConcurrentStreams) { session.destroy(); } if (!fulfilled) { rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response")); } }); writeRequestBodyPromise = (0, write_request_body_1.writeRequestBody)(req, request, requestTimeout); }); } updateHttpClientConfig(key, value) { this.config = undefined; this.configProvider = this.configProvider.then((config) => { return { ...config, [key]: value, }; }); } httpHandlerConfigs() { var _a; return (_a = this.config) !== null && _a !== void 0 ? _a : {}; } destroySession(session) { if (!session.destroyed) { session.destroy(); } } } exports.NodeHttp2Handler = NodeHttp2Handler; /***/ }), /***/ 25545: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.setConnectionTimeout = void 0; const setConnectionTimeout = (request, reject, timeoutInMs = 0) => { if (!timeoutInMs) { return; } const timeoutId = setTimeout(() => { request.destroy(); reject(Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), { name: "TimeoutError", })); }, timeoutInMs); request.on("socket", (socket) => { if (socket.connecting) { socket.on("connect", () => { clearTimeout(timeoutId); }); } else { clearTimeout(timeoutId); } }); }; exports.setConnectionTimeout = setConnectionTimeout; /***/ }), /***/ 83751: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.setSocketKeepAlive = void 0; const setSocketKeepAlive = (request, { keepAlive, keepAliveMsecs }) => { if (keepAlive !== true) { return; } request.on("socket", (socket) => { socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); }); }; exports.setSocketKeepAlive = setSocketKeepAlive; /***/ }), /***/ 42618: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.setSocketTimeout = void 0; const setSocketTimeout = (request, reject, timeoutInMs = 0) => { request.setTimeout(timeoutInMs, () => { request.destroy(); reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" })); }); }; exports.setSocketTimeout = setSocketTimeout; /***/ }), /***/ 23211: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Collector = void 0; const stream_1 = __nccwpck_require__(12781); class Collector extends stream_1.Writable { constructor() { super(...arguments); this.bufferedBytes = []; } _write(chunk, encoding, callback) { this.bufferedBytes.push(chunk); callback(); } } exports.Collector = Collector; /***/ }), /***/ 81030: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.streamCollector = void 0; const collector_1 = __nccwpck_require__(23211); const streamCollector = (stream) => new Promise((resolve, reject) => { const collector = new collector_1.Collector(); stream.pipe(collector); stream.on("error", (err) => { collector.end(); reject(err); }); collector.on("error", reject); collector.on("finish", function () { const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes)); resolve(bytes); }); }); exports.streamCollector = streamCollector; /***/ }), /***/ 73766: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.writeRequestBody = void 0; const stream_1 = __nccwpck_require__(12781); const MIN_WAIT_TIME = 1000; async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME) { var _a; const headers = (_a = request.headers) !== null && _a !== void 0 ? _a : {}; const expect = headers["Expect"] || headers["expect"]; let timeoutId = -1; let hasError = false; if (expect === "100-continue") { await Promise.race([ new Promise((resolve) => { timeoutId = Number(setTimeout(resolve, Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); }), new Promise((resolve) => { httpRequest.on("continue", () => { clearTimeout(timeoutId); resolve(); }); httpRequest.on("error", () => { hasError = true; clearTimeout(timeoutId); resolve(); }); }), ]); } if (!hasError) { writeBody(httpRequest, request.body); } } exports.writeRequestBody = writeRequestBody; function writeBody(httpRequest, body) { if (body instanceof stream_1.Readable) { body.pipe(httpRequest); } else if (body) { httpRequest.end(Buffer.from(body)); } else { httpRequest.end(); } } /***/ }), /***/ 63936: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CredentialsProviderError = void 0; const ProviderError_1 = __nccwpck_require__(23324); class CredentialsProviderError extends ProviderError_1.ProviderError { constructor(message, tryNextLink = true) { super(message, tryNextLink); this.tryNextLink = tryNextLink; this.name = "CredentialsProviderError"; Object.setPrototypeOf(this, CredentialsProviderError.prototype); } } exports.CredentialsProviderError = CredentialsProviderError; /***/ }), /***/ 23324: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProviderError = void 0; class ProviderError extends Error { constructor(message, tryNextLink = true) { super(message); this.tryNextLink = tryNextLink; this.name = "ProviderError"; Object.setPrototypeOf(this, ProviderError.prototype); } static from(error, tryNextLink = true) { return Object.assign(new this(error.message, tryNextLink), error); } } exports.ProviderError = ProviderError; /***/ }), /***/ 50429: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TokenProviderError = void 0; const ProviderError_1 = __nccwpck_require__(23324); class TokenProviderError extends ProviderError_1.ProviderError { constructor(message, tryNextLink = true) { super(message, tryNextLink); this.tryNextLink = tryNextLink; this.name = "TokenProviderError"; Object.setPrototypeOf(this, TokenProviderError.prototype); } } exports.TokenProviderError = TokenProviderError; /***/ }), /***/ 45079: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.chain = void 0; const ProviderError_1 = __nccwpck_require__(23324); const chain = (...providers) => async () => { if (providers.length === 0) { throw new ProviderError_1.ProviderError("No providers in chain"); } let lastProviderError; for (const provider of providers) { try { const credentials = await provider(); return credentials; } catch (err) { lastProviderError = err; if (err === null || err === void 0 ? void 0 : err.tryNextLink) { continue; } throw err; } } throw lastProviderError; }; exports.chain = chain; /***/ }), /***/ 51322: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fromStatic = void 0; const fromStatic = (staticValue) => () => Promise.resolve(staticValue); exports.fromStatic = fromStatic; /***/ }), /***/ 79721: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(63936), exports); tslib_1.__exportStar(__nccwpck_require__(23324), exports); tslib_1.__exportStar(__nccwpck_require__(50429), exports); tslib_1.__exportStar(__nccwpck_require__(45079), exports); tslib_1.__exportStar(__nccwpck_require__(51322), exports); tslib_1.__exportStar(__nccwpck_require__(49762), exports); /***/ }), /***/ 49762: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.memoize = void 0; const memoize = (provider, isExpired, requiresRefresh) => { let resolved; let pending; let hasResult; let isConstant = false; const coalesceProvider = async () => { if (!pending) { pending = provider(); } try { resolved = await pending; hasResult = true; isConstant = false; } finally { pending = undefined; } return resolved; }; if (isExpired === undefined) { return async (options) => { if (!hasResult || (options === null || options === void 0 ? void 0 : options.forceRefresh)) { resolved = await coalesceProvider(); } return resolved; }; } return async (options) => { if (!hasResult || (options === null || options === void 0 ? void 0 : options.forceRefresh)) { resolved = await coalesceProvider(); } if (isConstant) { return resolved; } if (requiresRefresh && !requiresRefresh(resolved)) { isConstant = true; return resolved; } if (isExpired(resolved)) { await coalesceProvider(); return resolved; } return resolved; }; }; exports.memoize = memoize; /***/ }), /***/ 89179: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Field = void 0; const types_1 = __nccwpck_require__(55756); class Field { constructor({ name, kind = types_1.FieldPosition.HEADER, values = [] }) { this.name = name; this.kind = kind; this.values = values; } add(value) { this.values.push(value); } set(values) { this.values = values; } remove(value) { this.values = this.values.filter((v) => v !== value); } toString() { return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", "); } get() { return this.values; } } exports.Field = Field; /***/ }), /***/ 99242: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Fields = void 0; class Fields { constructor({ fields = [], encoding = "utf-8" }) { this.entries = {}; fields.forEach(this.setField.bind(this)); this.encoding = encoding; } setField(field) { this.entries[field.name.toLowerCase()] = field; } getField(name) { return this.entries[name.toLowerCase()]; } removeField(name) { delete this.entries[name.toLowerCase()]; } getByType(kind) { return Object.values(this.entries).filter((field) => field.kind === kind); } } exports.Fields = Fields; /***/ }), /***/ 22474: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveHttpHandlerRuntimeConfig = exports.getHttpHandlerExtensionConfiguration = void 0; const getHttpHandlerExtensionConfiguration = (runtimeConfig) => { let httpHandler = runtimeConfig.httpHandler; return { setHttpHandler(handler) { httpHandler = handler; }, httpHandler() { return httpHandler; }, updateHttpClientConfig(key, value) { httpHandler.updateHttpClientConfig(key, value); }, httpHandlerConfigs() { return httpHandler.httpHandlerConfigs(); }, }; }; exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration; const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { return { httpHandler: httpHandlerExtensionConfiguration.httpHandler(), }; }; exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig; /***/ }), /***/ 91654: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(22474), exports); /***/ }), /***/ 63206: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 38746: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.HttpRequest = void 0; class HttpRequest { constructor(options) { this.method = options.method || "GET"; this.hostname = options.hostname || "localhost"; this.port = options.port; this.query = options.query || {}; this.headers = options.headers || {}; this.body = options.body; this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:"; this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/"; this.username = options.username; this.password = options.password; this.fragment = options.fragment; } static isInstance(request) { if (!request) return false; const req = request; return ("method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"); } clone() { const cloned = new HttpRequest({ ...this, headers: { ...this.headers }, }); if (cloned.query) cloned.query = cloneQuery(cloned.query); return cloned; } } exports.HttpRequest = HttpRequest; function cloneQuery(query) { return Object.keys(query).reduce((carry, paramName) => { const param = query[paramName]; return { ...carry, [paramName]: Array.isArray(param) ? [...param] : param, }; }, {}); } /***/ }), /***/ 26322: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.HttpResponse = void 0; class HttpResponse { constructor(options) { this.statusCode = options.statusCode; this.reason = options.reason; this.headers = options.headers || {}; this.body = options.body; } static isInstance(response) { if (!response) return false; const resp = response; return typeof resp.statusCode === "number" && typeof resp.headers === "object"; } } exports.HttpResponse = HttpResponse; /***/ }), /***/ 64418: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(91654), exports); tslib_1.__exportStar(__nccwpck_require__(89179), exports); tslib_1.__exportStar(__nccwpck_require__(99242), exports); tslib_1.__exportStar(__nccwpck_require__(63206), exports); tslib_1.__exportStar(__nccwpck_require__(38746), exports); tslib_1.__exportStar(__nccwpck_require__(26322), exports); tslib_1.__exportStar(__nccwpck_require__(61466), exports); tslib_1.__exportStar(__nccwpck_require__(19135), exports); /***/ }), /***/ 61466: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isValidHostname = void 0; function isValidHostname(hostname) { const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; return hostPattern.test(hostname); } exports.isValidHostname = isValidHostname; /***/ }), /***/ 19135: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 68031: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildQueryString = void 0; const util_uri_escape_1 = __nccwpck_require__(54197); function buildQueryString(query) { const parts = []; for (let key of Object.keys(query).sort()) { const value = query[key]; key = (0, util_uri_escape_1.escapeUri)(key); if (Array.isArray(value)) { for (let i = 0, iLen = value.length; i < iLen; i++) { parts.push(`${key}=${(0, util_uri_escape_1.escapeUri)(value[i])}`); } } else { let qsEntry = key; if (value || typeof value === "string") { qsEntry += `=${(0, util_uri_escape_1.escapeUri)(value)}`; } parts.push(qsEntry); } } return parts.join("&"); } exports.buildQueryString = buildQueryString; /***/ }), /***/ 4769: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseQueryString = void 0; function parseQueryString(querystring) { const query = {}; querystring = querystring.replace(/^\?/, ""); if (querystring) { for (const pair of querystring.split("&")) { let [key, value = null] = pair.split("="); key = decodeURIComponent(key); if (value) { value = decodeURIComponent(value); } if (!(key in query)) { query[key] = value; } else if (Array.isArray(query[key])) { query[key].push(value); } else { query[key] = [query[key], value]; } } } return query; } exports.parseQueryString = parseQueryString; /***/ }), /***/ 68415: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NODEJS_TIMEOUT_ERROR_CODES = exports.TRANSIENT_ERROR_STATUS_CODES = exports.TRANSIENT_ERROR_CODES = exports.THROTTLING_ERROR_CODES = exports.CLOCK_SKEW_ERROR_CODES = void 0; exports.CLOCK_SKEW_ERROR_CODES = [ "AuthFailure", "InvalidSignatureException", "RequestExpired", "RequestInTheFuture", "RequestTimeTooSkewed", "SignatureDoesNotMatch", ]; exports.THROTTLING_ERROR_CODES = [ "BandwidthLimitExceeded", "EC2ThrottledException", "LimitExceededException", "PriorRequestNotComplete", "ProvisionedThroughputExceededException", "RequestLimitExceeded", "RequestThrottled", "RequestThrottledException", "SlowDown", "ThrottledException", "Throttling", "ThrottlingException", "TooManyRequestsException", "TransactionInProgressException", ]; exports.TRANSIENT_ERROR_CODES = ["TimeoutError", "RequestTimeout", "RequestTimeoutException"]; exports.TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504]; exports.NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT"]; /***/ }), /***/ 6375: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isServerError = exports.isTransientError = exports.isThrottlingError = exports.isClockSkewError = exports.isRetryableByTrait = void 0; const constants_1 = __nccwpck_require__(68415); const isRetryableByTrait = (error) => error.$retryable !== undefined; exports.isRetryableByTrait = isRetryableByTrait; const isClockSkewError = (error) => constants_1.CLOCK_SKEW_ERROR_CODES.includes(error.name); exports.isClockSkewError = isClockSkewError; const isThrottlingError = (error) => { var _a, _b; return ((_a = error.$metadata) === null || _a === void 0 ? void 0 : _a.httpStatusCode) === 429 || constants_1.THROTTLING_ERROR_CODES.includes(error.name) || ((_b = error.$retryable) === null || _b === void 0 ? void 0 : _b.throttling) == true; }; exports.isThrottlingError = isThrottlingError; const isTransientError = (error) => { var _a; return constants_1.TRANSIENT_ERROR_CODES.includes(error.name) || constants_1.NODEJS_TIMEOUT_ERROR_CODES.includes((error === null || error === void 0 ? void 0 : error.code) || "") || constants_1.TRANSIENT_ERROR_STATUS_CODES.includes(((_a = error.$metadata) === null || _a === void 0 ? void 0 : _a.httpStatusCode) || 0); }; exports.isTransientError = isTransientError; const isServerError = (error) => { var _a; if (((_a = error.$metadata) === null || _a === void 0 ? void 0 : _a.httpStatusCode) !== undefined) { const statusCode = error.$metadata.httpStatusCode; if (500 <= statusCode && statusCode <= 599 && !(0, exports.isTransientError)(error)) { return true; } return false; } return false; }; exports.isServerError = isServerError; /***/ }), /***/ 46062: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getConfigData = void 0; const types_1 = __nccwpck_require__(55756); const loadSharedConfigFiles_1 = __nccwpck_require__(41879); const getConfigData = (data) => Object.entries(data) .filter(([key]) => { const sections = key.split(loadSharedConfigFiles_1.CONFIG_PREFIX_SEPARATOR); if (sections.length === 2 && Object.values(types_1.IniSectionType).includes(sections[0])) { return true; } return false; }) .reduce((acc, [key, value]) => { const updatedKey = key.startsWith(types_1.IniSectionType.PROFILE) ? key.split(loadSharedConfigFiles_1.CONFIG_PREFIX_SEPARATOR)[1] : key; acc[updatedKey] = value; return acc; }, { ...(data.default && { default: data.default }), }); exports.getConfigData = getConfigData; /***/ }), /***/ 47237: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getConfigFilepath = exports.ENV_CONFIG_PATH = void 0; const path_1 = __nccwpck_require__(71017); const getHomeDir_1 = __nccwpck_require__(68340); exports.ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; const getConfigFilepath = () => process.env[exports.ENV_CONFIG_PATH] || (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "config"); exports.getConfigFilepath = getConfigFilepath; /***/ }), /***/ 99036: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getCredentialsFilepath = exports.ENV_CREDENTIALS_PATH = void 0; const path_1 = __nccwpck_require__(71017); const getHomeDir_1 = __nccwpck_require__(68340); exports.ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; const getCredentialsFilepath = () => process.env[exports.ENV_CREDENTIALS_PATH] || (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "credentials"); exports.getCredentialsFilepath = getCredentialsFilepath; /***/ }), /***/ 68340: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getHomeDir = void 0; const os_1 = __nccwpck_require__(22037); const path_1 = __nccwpck_require__(71017); const homeDirCache = {}; const getHomeDirCacheKey = () => { if (process && process.geteuid) { return `${process.geteuid()}`; } return "DEFAULT"; }; const getHomeDir = () => { const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env; if (HOME) return HOME; if (USERPROFILE) return USERPROFILE; if (HOMEPATH) return `${HOMEDRIVE}${HOMEPATH}`; const homeDirCacheKey = getHomeDirCacheKey(); if (!homeDirCache[homeDirCacheKey]) homeDirCache[homeDirCacheKey] = (0, os_1.homedir)(); return homeDirCache[homeDirCacheKey]; }; exports.getHomeDir = getHomeDir; /***/ }), /***/ 52802: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getProfileName = exports.DEFAULT_PROFILE = exports.ENV_PROFILE = void 0; exports.ENV_PROFILE = "AWS_PROFILE"; exports.DEFAULT_PROFILE = "default"; const getProfileName = (init) => init.profile || process.env[exports.ENV_PROFILE] || exports.DEFAULT_PROFILE; exports.getProfileName = getProfileName; /***/ }), /***/ 24740: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getSSOTokenFilepath = void 0; const crypto_1 = __nccwpck_require__(6113); const path_1 = __nccwpck_require__(71017); const getHomeDir_1 = __nccwpck_require__(68340); const getSSOTokenFilepath = (id) => { const hasher = (0, crypto_1.createHash)("sha1"); const cacheName = hasher.update(id).digest("hex"); return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`); }; exports.getSSOTokenFilepath = getSSOTokenFilepath; /***/ }), /***/ 69678: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getSSOTokenFromFile = void 0; const fs_1 = __nccwpck_require__(57147); const getSSOTokenFilepath_1 = __nccwpck_require__(24740); const { readFile } = fs_1.promises; const getSSOTokenFromFile = async (id) => { const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id); const ssoTokenText = await readFile(ssoTokenFilepath, "utf8"); return JSON.parse(ssoTokenText); }; exports.getSSOTokenFromFile = getSSOTokenFromFile; /***/ }), /***/ 82820: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getSsoSessionData = void 0; const types_1 = __nccwpck_require__(55756); const loadSharedConfigFiles_1 = __nccwpck_require__(41879); const getSsoSessionData = (data) => Object.entries(data) .filter(([key]) => key.startsWith(types_1.IniSectionType.SSO_SESSION + loadSharedConfigFiles_1.CONFIG_PREFIX_SEPARATOR)) .reduce((acc, [key, value]) => ({ ...acc, [key.split(loadSharedConfigFiles_1.CONFIG_PREFIX_SEPARATOR)[1]]: value }), {}); exports.getSsoSessionData = getSsoSessionData; /***/ }), /***/ 43507: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(68340), exports); tslib_1.__exportStar(__nccwpck_require__(52802), exports); tslib_1.__exportStar(__nccwpck_require__(24740), exports); tslib_1.__exportStar(__nccwpck_require__(69678), exports); tslib_1.__exportStar(__nccwpck_require__(41879), exports); tslib_1.__exportStar(__nccwpck_require__(34649), exports); tslib_1.__exportStar(__nccwpck_require__(2546), exports); tslib_1.__exportStar(__nccwpck_require__(63191), exports); /***/ }), /***/ 41879: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.loadSharedConfigFiles = exports.CONFIG_PREFIX_SEPARATOR = void 0; const getConfigData_1 = __nccwpck_require__(46062); const getConfigFilepath_1 = __nccwpck_require__(47237); const getCredentialsFilepath_1 = __nccwpck_require__(99036); const parseIni_1 = __nccwpck_require__(54262); const slurpFile_1 = __nccwpck_require__(19155); const swallowError = () => ({}); exports.CONFIG_PREFIX_SEPARATOR = "."; const loadSharedConfigFiles = async (init = {}) => { const { filepath = (0, getCredentialsFilepath_1.getCredentialsFilepath)(), configFilepath = (0, getConfigFilepath_1.getConfigFilepath)() } = init; const parsedFiles = await Promise.all([ (0, slurpFile_1.slurpFile)(configFilepath, { ignoreCache: init.ignoreCache, }) .then(parseIni_1.parseIni) .then(getConfigData_1.getConfigData) .catch(swallowError), (0, slurpFile_1.slurpFile)(filepath, { ignoreCache: init.ignoreCache, }) .then(parseIni_1.parseIni) .catch(swallowError), ]); return { configFile: parsedFiles[0], credentialsFile: parsedFiles[1], }; }; exports.loadSharedConfigFiles = loadSharedConfigFiles; /***/ }), /***/ 34649: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.loadSsoSessionData = void 0; const getConfigFilepath_1 = __nccwpck_require__(47237); const getSsoSessionData_1 = __nccwpck_require__(82820); const parseIni_1 = __nccwpck_require__(54262); const slurpFile_1 = __nccwpck_require__(19155); const swallowError = () => ({}); const loadSsoSessionData = async (init = {}) => { var _a; return (0, slurpFile_1.slurpFile)((_a = init.configFilepath) !== null && _a !== void 0 ? _a : (0, getConfigFilepath_1.getConfigFilepath)()) .then(parseIni_1.parseIni) .then(getSsoSessionData_1.getSsoSessionData) .catch(swallowError); }; exports.loadSsoSessionData = loadSsoSessionData; /***/ }), /***/ 19447: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.mergeConfigFiles = void 0; const mergeConfigFiles = (...files) => { const merged = {}; for (const file of files) { for (const [key, values] of Object.entries(file)) { if (merged[key] !== undefined) { Object.assign(merged[key], values); } else { merged[key] = values; } } } return merged; }; exports.mergeConfigFiles = mergeConfigFiles; /***/ }), /***/ 54262: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseIni = void 0; const types_1 = __nccwpck_require__(55756); const loadSharedConfigFiles_1 = __nccwpck_require__(41879); const prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; const profileNameBlockList = ["__proto__", "profile __proto__"]; const parseIni = (iniData) => { const map = {}; let currentSection; let currentSubSection; for (const iniLine of iniData.split(/\r?\n/)) { const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; if (isSection) { currentSection = undefined; currentSubSection = undefined; const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); const matches = prefixKeyRegex.exec(sectionName); if (matches) { const [, prefix, , name] = matches; if (Object.values(types_1.IniSectionType).includes(prefix)) { currentSection = [prefix, name].join(loadSharedConfigFiles_1.CONFIG_PREFIX_SEPARATOR); } } else { currentSection = sectionName; } if (profileNameBlockList.includes(sectionName)) { throw new Error(`Found invalid profile name "${sectionName}"`); } } else if (currentSection) { const indexOfEqualsSign = trimmedLine.indexOf("="); if (![0, -1].includes(indexOfEqualsSign)) { const [name, value] = [ trimmedLine.substring(0, indexOfEqualsSign).trim(), trimmedLine.substring(indexOfEqualsSign + 1).trim(), ]; if (value === "") { currentSubSection = name; } else { if (currentSubSection && iniLine.trimStart() === iniLine) { currentSubSection = undefined; } map[currentSection] = map[currentSection] || {}; const key = currentSubSection ? [currentSubSection, name].join(loadSharedConfigFiles_1.CONFIG_PREFIX_SEPARATOR) : name; map[currentSection][key] = value; } } } } return map; }; exports.parseIni = parseIni; /***/ }), /***/ 2546: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseKnownFiles = void 0; const loadSharedConfigFiles_1 = __nccwpck_require__(41879); const mergeConfigFiles_1 = __nccwpck_require__(19447); const parseKnownFiles = async (init) => { const parsedFiles = await (0, loadSharedConfigFiles_1.loadSharedConfigFiles)(init); return (0, mergeConfigFiles_1.mergeConfigFiles)(parsedFiles.configFile, parsedFiles.credentialsFile); }; exports.parseKnownFiles = parseKnownFiles; /***/ }), /***/ 19155: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.slurpFile = void 0; const fs_1 = __nccwpck_require__(57147); const { readFile } = fs_1.promises; const filePromisesHash = {}; const slurpFile = (path, options) => { if (!filePromisesHash[path] || (options === null || options === void 0 ? void 0 : options.ignoreCache)) { filePromisesHash[path] = readFile(path, "utf8"); } return filePromisesHash[path]; }; exports.slurpFile = slurpFile; /***/ }), /***/ 63191: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 39733: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SignatureV4 = void 0; const eventstream_codec_1 = __nccwpck_require__(56459); const util_hex_encoding_1 = __nccwpck_require__(45364); const util_middleware_1 = __nccwpck_require__(2390); const util_utf8_1 = __nccwpck_require__(41895); const constants_1 = __nccwpck_require__(48644); const credentialDerivation_1 = __nccwpck_require__(19623); const getCanonicalHeaders_1 = __nccwpck_require__(51393); const getCanonicalQuery_1 = __nccwpck_require__(33243); const getPayloadHash_1 = __nccwpck_require__(48545); const headerUtil_1 = __nccwpck_require__(62179); const moveHeadersToQuery_1 = __nccwpck_require__(49828); const prepareRequest_1 = __nccwpck_require__(60075); const utilDate_1 = __nccwpck_require__(39299); class SignatureV4 { constructor({ applyChecksum, credentials, region, service, sha256, uriEscapePath = true, }) { this.headerMarshaller = new eventstream_codec_1.HeaderMarshaller(util_utf8_1.toUtf8, util_utf8_1.fromUtf8); this.service = service; this.sha256 = sha256; this.uriEscapePath = uriEscapePath; this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true; this.regionProvider = (0, util_middleware_1.normalizeProvider)(region); this.credentialProvider = (0, util_middleware_1.normalizeProvider)(credentials); } async presign(originalRequest, options = {}) { const { signingDate = new Date(), expiresIn = 3600, unsignableHeaders, unhoistableHeaders, signableHeaders, signingRegion, signingService, } = options; const credentials = await this.credentialProvider(); this.validateResolvedCredentials(credentials); const region = signingRegion !== null && signingRegion !== void 0 ? signingRegion : (await this.regionProvider()); const { longDate, shortDate } = formatDate(signingDate); if (expiresIn > constants_1.MAX_PRESIGNED_TTL) { return Promise.reject("Signature version 4 presigned URLs" + " must have an expiration date less than one week in" + " the future"); } const scope = (0, credentialDerivation_1.createScope)(shortDate, region, signingService !== null && signingService !== void 0 ? signingService : this.service); const request = (0, moveHeadersToQuery_1.moveHeadersToQuery)((0, prepareRequest_1.prepareRequest)(originalRequest), { unhoistableHeaders }); if (credentials.sessionToken) { request.query[constants_1.TOKEN_QUERY_PARAM] = credentials.sessionToken; } request.query[constants_1.ALGORITHM_QUERY_PARAM] = constants_1.ALGORITHM_IDENTIFIER; request.query[constants_1.CREDENTIAL_QUERY_PARAM] = `${credentials.accessKeyId}/${scope}`; request.query[constants_1.AMZ_DATE_QUERY_PARAM] = longDate; request.query[constants_1.EXPIRES_QUERY_PARAM] = expiresIn.toString(10); const canonicalHeaders = (0, getCanonicalHeaders_1.getCanonicalHeaders)(request, unsignableHeaders, signableHeaders); request.query[constants_1.SIGNED_HEADERS_QUERY_PARAM] = getCanonicalHeaderList(canonicalHeaders); request.query[constants_1.SIGNATURE_QUERY_PARAM] = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, await (0, getPayloadHash_1.getPayloadHash)(originalRequest, this.sha256))); return request; } async sign(toSign, options) { if (typeof toSign === "string") { return this.signString(toSign, options); } else if (toSign.headers && toSign.payload) { return this.signEvent(toSign, options); } else if (toSign.message) { return this.signMessage(toSign, options); } else { return this.signRequest(toSign, options); } } async signEvent({ headers, payload }, { signingDate = new Date(), priorSignature, signingRegion, signingService }) { const region = signingRegion !== null && signingRegion !== void 0 ? signingRegion : (await this.regionProvider()); const { shortDate, longDate } = formatDate(signingDate); const scope = (0, credentialDerivation_1.createScope)(shortDate, region, signingService !== null && signingService !== void 0 ? signingService : this.service); const hashedPayload = await (0, getPayloadHash_1.getPayloadHash)({ headers: {}, body: payload }, this.sha256); const hash = new this.sha256(); hash.update(headers); const hashedHeaders = (0, util_hex_encoding_1.toHex)(await hash.digest()); const stringToSign = [ constants_1.EVENT_ALGORITHM_IDENTIFIER, longDate, scope, priorSignature, hashedHeaders, hashedPayload, ].join("\n"); return this.signString(stringToSign, { signingDate, signingRegion: region, signingService }); } async signMessage(signableMessage, { signingDate = new Date(), signingRegion, signingService }) { const promise = this.signEvent({ headers: this.headerMarshaller.format(signableMessage.message.headers), payload: signableMessage.message.body, }, { signingDate, signingRegion, signingService, priorSignature: signableMessage.priorSignature, }); return promise.then((signature) => { return { message: signableMessage.message, signature }; }); } async signString(stringToSign, { signingDate = new Date(), signingRegion, signingService } = {}) { const credentials = await this.credentialProvider(); this.validateResolvedCredentials(credentials); const region = signingRegion !== null && signingRegion !== void 0 ? signingRegion : (await this.regionProvider()); const { shortDate } = formatDate(signingDate); const hash = new this.sha256(await this.getSigningKey(credentials, region, shortDate, signingService)); hash.update((0, util_utf8_1.toUint8Array)(stringToSign)); return (0, util_hex_encoding_1.toHex)(await hash.digest()); } async signRequest(requestToSign, { signingDate = new Date(), signableHeaders, unsignableHeaders, signingRegion, signingService, } = {}) { const credentials = await this.credentialProvider(); this.validateResolvedCredentials(credentials); const region = signingRegion !== null && signingRegion !== void 0 ? signingRegion : (await this.regionProvider()); const request = (0, prepareRequest_1.prepareRequest)(requestToSign); const { longDate, shortDate } = formatDate(signingDate); const scope = (0, credentialDerivation_1.createScope)(shortDate, region, signingService !== null && signingService !== void 0 ? signingService : this.service); request.headers[constants_1.AMZ_DATE_HEADER] = longDate; if (credentials.sessionToken) { request.headers[constants_1.TOKEN_HEADER] = credentials.sessionToken; } const payloadHash = await (0, getPayloadHash_1.getPayloadHash)(request, this.sha256); if (!(0, headerUtil_1.hasHeader)(constants_1.SHA256_HEADER, request.headers) && this.applyChecksum) { request.headers[constants_1.SHA256_HEADER] = payloadHash; } const canonicalHeaders = (0, getCanonicalHeaders_1.getCanonicalHeaders)(request, unsignableHeaders, signableHeaders); const signature = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, payloadHash)); request.headers[constants_1.AUTH_HEADER] = `${constants_1.ALGORITHM_IDENTIFIER} ` + `Credential=${credentials.accessKeyId}/${scope}, ` + `SignedHeaders=${getCanonicalHeaderList(canonicalHeaders)}, ` + `Signature=${signature}`; return request; } createCanonicalRequest(request, canonicalHeaders, payloadHash) { const sortedHeaders = Object.keys(canonicalHeaders).sort(); return `${request.method} ${this.getCanonicalPath(request)} ${(0, getCanonicalQuery_1.getCanonicalQuery)(request)} ${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join("\n")} ${sortedHeaders.join(";")} ${payloadHash}`; } async createStringToSign(longDate, credentialScope, canonicalRequest) { const hash = new this.sha256(); hash.update((0, util_utf8_1.toUint8Array)(canonicalRequest)); const hashedRequest = await hash.digest(); return `${constants_1.ALGORITHM_IDENTIFIER} ${longDate} ${credentialScope} ${(0, util_hex_encoding_1.toHex)(hashedRequest)}`; } getCanonicalPath({ path }) { if (this.uriEscapePath) { const normalizedPathSegments = []; for (const pathSegment of path.split("/")) { if ((pathSegment === null || pathSegment === void 0 ? void 0 : pathSegment.length) === 0) continue; if (pathSegment === ".") continue; if (pathSegment === "..") { normalizedPathSegments.pop(); } else { normalizedPathSegments.push(pathSegment); } } const normalizedPath = `${(path === null || path === void 0 ? void 0 : path.startsWith("/")) ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && (path === null || path === void 0 ? void 0 : path.endsWith("/")) ? "/" : ""}`; const doubleEncoded = encodeURIComponent(normalizedPath); return doubleEncoded.replace(/%2F/g, "/"); } return path; } async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) { const stringToSign = await this.createStringToSign(longDate, credentialScope, canonicalRequest); const hash = new this.sha256(await keyPromise); hash.update((0, util_utf8_1.toUint8Array)(stringToSign)); return (0, util_hex_encoding_1.toHex)(await hash.digest()); } getSigningKey(credentials, region, shortDate, service) { return (0, credentialDerivation_1.getSigningKey)(this.sha256, credentials, shortDate, region, service || this.service); } validateResolvedCredentials(credentials) { if (typeof credentials !== "object" || typeof credentials.accessKeyId !== "string" || typeof credentials.secretAccessKey !== "string") { throw new Error("Resolved credential object is not valid"); } } } exports.SignatureV4 = SignatureV4; const formatDate = (now) => { const longDate = (0, utilDate_1.iso8601)(now).replace(/[\-:]/g, ""); return { longDate, shortDate: longDate.slice(0, 8), }; }; const getCanonicalHeaderList = (headers) => Object.keys(headers).sort().join(";"); /***/ }), /***/ 69098: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.cloneQuery = exports.cloneRequest = void 0; const cloneRequest = ({ headers, query, ...rest }) => ({ ...rest, headers: { ...headers }, query: query ? (0, exports.cloneQuery)(query) : undefined, }); exports.cloneRequest = cloneRequest; const cloneQuery = (query) => Object.keys(query).reduce((carry, paramName) => { const param = query[paramName]; return { ...carry, [paramName]: Array.isArray(param) ? [...param] : param, }; }, {}); exports.cloneQuery = cloneQuery; /***/ }), /***/ 48644: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MAX_PRESIGNED_TTL = exports.KEY_TYPE_IDENTIFIER = exports.MAX_CACHE_SIZE = exports.UNSIGNED_PAYLOAD = exports.EVENT_ALGORITHM_IDENTIFIER = exports.ALGORITHM_IDENTIFIER_V4A = exports.ALGORITHM_IDENTIFIER = exports.UNSIGNABLE_PATTERNS = exports.SEC_HEADER_PATTERN = exports.PROXY_HEADER_PATTERN = exports.ALWAYS_UNSIGNABLE_HEADERS = exports.HOST_HEADER = exports.TOKEN_HEADER = exports.SHA256_HEADER = exports.SIGNATURE_HEADER = exports.GENERATED_HEADERS = exports.DATE_HEADER = exports.AMZ_DATE_HEADER = exports.AUTH_HEADER = exports.REGION_SET_PARAM = exports.TOKEN_QUERY_PARAM = exports.SIGNATURE_QUERY_PARAM = exports.EXPIRES_QUERY_PARAM = exports.SIGNED_HEADERS_QUERY_PARAM = exports.AMZ_DATE_QUERY_PARAM = exports.CREDENTIAL_QUERY_PARAM = exports.ALGORITHM_QUERY_PARAM = void 0; exports.ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm"; exports.CREDENTIAL_QUERY_PARAM = "X-Amz-Credential"; exports.AMZ_DATE_QUERY_PARAM = "X-Amz-Date"; exports.SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders"; exports.EXPIRES_QUERY_PARAM = "X-Amz-Expires"; exports.SIGNATURE_QUERY_PARAM = "X-Amz-Signature"; exports.TOKEN_QUERY_PARAM = "X-Amz-Security-Token"; exports.REGION_SET_PARAM = "X-Amz-Region-Set"; exports.AUTH_HEADER = "authorization"; exports.AMZ_DATE_HEADER = exports.AMZ_DATE_QUERY_PARAM.toLowerCase(); exports.DATE_HEADER = "date"; exports.GENERATED_HEADERS = [exports.AUTH_HEADER, exports.AMZ_DATE_HEADER, exports.DATE_HEADER]; exports.SIGNATURE_HEADER = exports.SIGNATURE_QUERY_PARAM.toLowerCase(); exports.SHA256_HEADER = "x-amz-content-sha256"; exports.TOKEN_HEADER = exports.TOKEN_QUERY_PARAM.toLowerCase(); exports.HOST_HEADER = "host"; exports.ALWAYS_UNSIGNABLE_HEADERS = { authorization: true, "cache-control": true, connection: true, expect: true, from: true, "keep-alive": true, "max-forwards": true, pragma: true, referer: true, te: true, trailer: true, "transfer-encoding": true, upgrade: true, "user-agent": true, "x-amzn-trace-id": true, }; exports.PROXY_HEADER_PATTERN = /^proxy-/; exports.SEC_HEADER_PATTERN = /^sec-/; exports.UNSIGNABLE_PATTERNS = [/^proxy-/i, /^sec-/i]; exports.ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256"; exports.ALGORITHM_IDENTIFIER_V4A = "AWS4-ECDSA-P256-SHA256"; exports.EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD"; exports.UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"; exports.MAX_CACHE_SIZE = 50; exports.KEY_TYPE_IDENTIFIER = "aws4_request"; exports.MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7; /***/ }), /***/ 19623: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.clearCredentialCache = exports.getSigningKey = exports.createScope = void 0; const util_hex_encoding_1 = __nccwpck_require__(45364); const util_utf8_1 = __nccwpck_require__(41895); const constants_1 = __nccwpck_require__(48644); const signingKeyCache = {}; const cacheQueue = []; const createScope = (shortDate, region, service) => `${shortDate}/${region}/${service}/${constants_1.KEY_TYPE_IDENTIFIER}`; exports.createScope = createScope; const getSigningKey = async (sha256Constructor, credentials, shortDate, region, service) => { const credsHash = await hmac(sha256Constructor, credentials.secretAccessKey, credentials.accessKeyId); const cacheKey = `${shortDate}:${region}:${service}:${(0, util_hex_encoding_1.toHex)(credsHash)}:${credentials.sessionToken}`; if (cacheKey in signingKeyCache) { return signingKeyCache[cacheKey]; } cacheQueue.push(cacheKey); while (cacheQueue.length > constants_1.MAX_CACHE_SIZE) { delete signingKeyCache[cacheQueue.shift()]; } let key = `AWS4${credentials.secretAccessKey}`; for (const signable of [shortDate, region, service, constants_1.KEY_TYPE_IDENTIFIER]) { key = await hmac(sha256Constructor, key, signable); } return (signingKeyCache[cacheKey] = key); }; exports.getSigningKey = getSigningKey; const clearCredentialCache = () => { cacheQueue.length = 0; Object.keys(signingKeyCache).forEach((cacheKey) => { delete signingKeyCache[cacheKey]; }); }; exports.clearCredentialCache = clearCredentialCache; const hmac = (ctor, secret, data) => { const hash = new ctor(secret); hash.update((0, util_utf8_1.toUint8Array)(data)); return hash.digest(); }; /***/ }), /***/ 51393: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getCanonicalHeaders = void 0; const constants_1 = __nccwpck_require__(48644); const getCanonicalHeaders = ({ headers }, unsignableHeaders, signableHeaders) => { const canonical = {}; for (const headerName of Object.keys(headers).sort()) { if (headers[headerName] == undefined) { continue; } const canonicalHeaderName = headerName.toLowerCase(); if (canonicalHeaderName in constants_1.ALWAYS_UNSIGNABLE_HEADERS || (unsignableHeaders === null || unsignableHeaders === void 0 ? void 0 : unsignableHeaders.has(canonicalHeaderName)) || constants_1.PROXY_HEADER_PATTERN.test(canonicalHeaderName) || constants_1.SEC_HEADER_PATTERN.test(canonicalHeaderName)) { if (!signableHeaders || (signableHeaders && !signableHeaders.has(canonicalHeaderName))) { continue; } } canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " "); } return canonical; }; exports.getCanonicalHeaders = getCanonicalHeaders; /***/ }), /***/ 33243: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getCanonicalQuery = void 0; const util_uri_escape_1 = __nccwpck_require__(54197); const constants_1 = __nccwpck_require__(48644); const getCanonicalQuery = ({ query = {} }) => { const keys = []; const serialized = {}; for (const key of Object.keys(query).sort()) { if (key.toLowerCase() === constants_1.SIGNATURE_HEADER) { continue; } keys.push(key); const value = query[key]; if (typeof value === "string") { serialized[key] = `${(0, util_uri_escape_1.escapeUri)(key)}=${(0, util_uri_escape_1.escapeUri)(value)}`; } else if (Array.isArray(value)) { serialized[key] = value .slice(0) .reduce((encoded, value) => encoded.concat([`${(0, util_uri_escape_1.escapeUri)(key)}=${(0, util_uri_escape_1.escapeUri)(value)}`]), []) .sort() .join("&"); } } return keys .map((key) => serialized[key]) .filter((serialized) => serialized) .join("&"); }; exports.getCanonicalQuery = getCanonicalQuery; /***/ }), /***/ 48545: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getPayloadHash = void 0; const is_array_buffer_1 = __nccwpck_require__(10780); const util_hex_encoding_1 = __nccwpck_require__(45364); const util_utf8_1 = __nccwpck_require__(41895); const constants_1 = __nccwpck_require__(48644); const getPayloadHash = async ({ headers, body }, hashConstructor) => { for (const headerName of Object.keys(headers)) { if (headerName.toLowerCase() === constants_1.SHA256_HEADER) { return headers[headerName]; } } if (body == undefined) { return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; } else if (typeof body === "string" || ArrayBuffer.isView(body) || (0, is_array_buffer_1.isArrayBuffer)(body)) { const hashCtor = new hashConstructor(); hashCtor.update((0, util_utf8_1.toUint8Array)(body)); return (0, util_hex_encoding_1.toHex)(await hashCtor.digest()); } return constants_1.UNSIGNED_PAYLOAD; }; exports.getPayloadHash = getPayloadHash; /***/ }), /***/ 62179: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.deleteHeader = exports.getHeaderValue = exports.hasHeader = void 0; const hasHeader = (soughtHeader, headers) => { soughtHeader = soughtHeader.toLowerCase(); for (const headerName of Object.keys(headers)) { if (soughtHeader === headerName.toLowerCase()) { return true; } } return false; }; exports.hasHeader = hasHeader; const getHeaderValue = (soughtHeader, headers) => { soughtHeader = soughtHeader.toLowerCase(); for (const headerName of Object.keys(headers)) { if (soughtHeader === headerName.toLowerCase()) { return headers[headerName]; } } return undefined; }; exports.getHeaderValue = getHeaderValue; const deleteHeader = (soughtHeader, headers) => { soughtHeader = soughtHeader.toLowerCase(); for (const headerName of Object.keys(headers)) { if (soughtHeader === headerName.toLowerCase()) { delete headers[headerName]; } } }; exports.deleteHeader = deleteHeader; /***/ }), /***/ 11528: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.prepareRequest = exports.moveHeadersToQuery = exports.getPayloadHash = exports.getCanonicalQuery = exports.getCanonicalHeaders = void 0; const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(39733), exports); var getCanonicalHeaders_1 = __nccwpck_require__(51393); Object.defineProperty(exports, "getCanonicalHeaders", ({ enumerable: true, get: function () { return getCanonicalHeaders_1.getCanonicalHeaders; } })); var getCanonicalQuery_1 = __nccwpck_require__(33243); Object.defineProperty(exports, "getCanonicalQuery", ({ enumerable: true, get: function () { return getCanonicalQuery_1.getCanonicalQuery; } })); var getPayloadHash_1 = __nccwpck_require__(48545); Object.defineProperty(exports, "getPayloadHash", ({ enumerable: true, get: function () { return getPayloadHash_1.getPayloadHash; } })); var moveHeadersToQuery_1 = __nccwpck_require__(49828); Object.defineProperty(exports, "moveHeadersToQuery", ({ enumerable: true, get: function () { return moveHeadersToQuery_1.moveHeadersToQuery; } })); var prepareRequest_1 = __nccwpck_require__(60075); Object.defineProperty(exports, "prepareRequest", ({ enumerable: true, get: function () { return prepareRequest_1.prepareRequest; } })); tslib_1.__exportStar(__nccwpck_require__(19623), exports); /***/ }), /***/ 49828: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.moveHeadersToQuery = void 0; const cloneRequest_1 = __nccwpck_require__(69098); const moveHeadersToQuery = (request, options = {}) => { var _a; const { headers, query = {} } = typeof request.clone === "function" ? request.clone() : (0, cloneRequest_1.cloneRequest)(request); for (const name of Object.keys(headers)) { const lname = name.toLowerCase(); if (lname.slice(0, 6) === "x-amz-" && !((_a = options.unhoistableHeaders) === null || _a === void 0 ? void 0 : _a.has(lname))) { query[name] = headers[name]; delete headers[name]; } } return { ...request, headers, query, }; }; exports.moveHeadersToQuery = moveHeadersToQuery; /***/ }), /***/ 60075: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.prepareRequest = void 0; const cloneRequest_1 = __nccwpck_require__(69098); const constants_1 = __nccwpck_require__(48644); const prepareRequest = (request) => { request = typeof request.clone === "function" ? request.clone() : (0, cloneRequest_1.cloneRequest)(request); for (const headerName of Object.keys(request.headers)) { if (constants_1.GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) { delete request.headers[headerName]; } } return request; }; exports.prepareRequest = prepareRequest; /***/ }), /***/ 39299: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toDate = exports.iso8601 = void 0; const iso8601 = (time) => (0, exports.toDate)(time) .toISOString() .replace(/\.\d{3}Z$/, "Z"); exports.iso8601 = iso8601; const toDate = (time) => { if (typeof time === "number") { return new Date(time * 1000); } if (typeof time === "string") { if (Number(time)) { return new Date(Number(time) * 1000); } return new Date(time); } return time; }; exports.toDate = toDate; /***/ }), /***/ 70438: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoOpLogger = void 0; class NoOpLogger { trace() { } debug() { } info() { } warn() { } error() { } } exports.NoOpLogger = NoOpLogger; /***/ }), /***/ 61600: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Client = void 0; const middleware_stack_1 = __nccwpck_require__(97911); class Client { constructor(config) { this.middlewareStack = (0, middleware_stack_1.constructStack)(); this.config = config; } send(command, optionsOrCb, cb) { const options = typeof optionsOrCb !== "function" ? optionsOrCb : undefined; const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb; const handler = command.resolveMiddleware(this.middlewareStack, this.config, options); if (callback) { handler(command) .then((result) => callback(null, result.output), (err) => callback(err)) .catch(() => { }); } else { return handler(command).then((result) => result.output); } } destroy() { if (this.config.requestHandler.destroy) this.config.requestHandler.destroy(); } } exports.Client = Client; /***/ }), /***/ 32813: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.collectBody = void 0; const util_stream_1 = __nccwpck_require__(96607); const collectBody = async (streamBody = new Uint8Array(), context) => { if (streamBody instanceof Uint8Array) { return util_stream_1.Uint8ArrayBlobAdapter.mutate(streamBody); } if (!streamBody) { return util_stream_1.Uint8ArrayBlobAdapter.mutate(new Uint8Array()); } const fromContext = context.streamCollector(streamBody); return util_stream_1.Uint8ArrayBlobAdapter.mutate(await fromContext); }; exports.collectBody = collectBody; /***/ }), /***/ 75414: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Command = void 0; const middleware_stack_1 = __nccwpck_require__(97911); class Command { constructor() { this.middlewareStack = (0, middleware_stack_1.constructStack)(); } } exports.Command = Command; /***/ }), /***/ 92541: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SENSITIVE_STRING = void 0; exports.SENSITIVE_STRING = "***SensitiveInformation***"; /***/ }), /***/ 56929: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createAggregatedClient = void 0; const createAggregatedClient = (commands, Client) => { for (const command of Object.keys(commands)) { const CommandCtor = commands[command]; const methodImpl = async function (args, optionsOrCb, cb) { const command = new CommandCtor(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expected http options but got ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } }; const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, ""); Client.prototype[methodName] = methodImpl; } }; exports.createAggregatedClient = createAggregatedClient; /***/ }), /***/ 21737: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseEpochTimestamp = exports.parseRfc7231DateTime = exports.parseRfc3339DateTimeWithOffset = exports.parseRfc3339DateTime = exports.dateToUtcString = void 0; const parse_utils_1 = __nccwpck_require__(74857); const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; function dateToUtcString(date) { const year = date.getUTCFullYear(); const month = date.getUTCMonth(); const dayOfWeek = date.getUTCDay(); const dayOfMonthInt = date.getUTCDate(); const hoursInt = date.getUTCHours(); const minutesInt = date.getUTCMinutes(); const secondsInt = date.getUTCSeconds(); const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`; const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`; const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`; const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`; return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`; } exports.dateToUtcString = dateToUtcString; const RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); const parseRfc3339DateTime = (value) => { if (value === null || value === undefined) { return undefined; } if (typeof value !== "string") { throw new TypeError("RFC-3339 date-times must be expressed as strings"); } const match = RFC3339.exec(value); if (!match) { throw new TypeError("Invalid RFC-3339 date-time value"); } const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match; const year = (0, parse_utils_1.strictParseShort)(stripLeadingZeroes(yearStr)); const month = parseDateValue(monthStr, "month", 1, 12); const day = parseDateValue(dayStr, "day", 1, 31); return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); }; exports.parseRfc3339DateTime = parseRfc3339DateTime; const RFC3339_WITH_OFFSET = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/); const parseRfc3339DateTimeWithOffset = (value) => { if (value === null || value === undefined) { return undefined; } if (typeof value !== "string") { throw new TypeError("RFC-3339 date-times must be expressed as strings"); } const match = RFC3339_WITH_OFFSET.exec(value); if (!match) { throw new TypeError("Invalid RFC-3339 date-time value"); } const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match; const year = (0, parse_utils_1.strictParseShort)(stripLeadingZeroes(yearStr)); const month = parseDateValue(monthStr, "month", 1, 12); const day = parseDateValue(dayStr, "day", 1, 31); const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); if (offsetStr.toUpperCase() != "Z") { date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr)); } return date; }; exports.parseRfc3339DateTimeWithOffset = parseRfc3339DateTimeWithOffset; const IMF_FIXDATE = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/); const RFC_850_DATE = new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/); const ASC_TIME = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/); const parseRfc7231DateTime = (value) => { if (value === null || value === undefined) { return undefined; } if (typeof value !== "string") { throw new TypeError("RFC-7231 date-times must be expressed as strings"); } let match = IMF_FIXDATE.exec(value); if (match) { const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; return buildDate((0, parse_utils_1.strictParseShort)(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds }); } match = RFC_850_DATE.exec(value); if (match) { const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; return adjustRfc850Year(buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds, })); } match = ASC_TIME.exec(value); if (match) { const [_, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match; return buildDate((0, parse_utils_1.strictParseShort)(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr.trimLeft(), "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds }); } throw new TypeError("Invalid RFC-7231 date-time value"); }; exports.parseRfc7231DateTime = parseRfc7231DateTime; const parseEpochTimestamp = (value) => { if (value === null || value === undefined) { return undefined; } let valueAsDouble; if (typeof value === "number") { valueAsDouble = value; } else if (typeof value === "string") { valueAsDouble = (0, parse_utils_1.strictParseDouble)(value); } else { throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation"); } if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) { throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics"); } return new Date(Math.round(valueAsDouble * 1000)); }; exports.parseEpochTimestamp = parseEpochTimestamp; const buildDate = (year, month, day, time) => { const adjustedMonth = month - 1; validateDayOfMonth(year, adjustedMonth, day); return new Date(Date.UTC(year, adjustedMonth, day, parseDateValue(time.hours, "hour", 0, 23), parseDateValue(time.minutes, "minute", 0, 59), parseDateValue(time.seconds, "seconds", 0, 60), parseMilliseconds(time.fractionalMilliseconds))); }; const parseTwoDigitYear = (value) => { const thisYear = new Date().getUTCFullYear(); const valueInThisCentury = Math.floor(thisYear / 100) * 100 + (0, parse_utils_1.strictParseShort)(stripLeadingZeroes(value)); if (valueInThisCentury < thisYear) { return valueInThisCentury + 100; } return valueInThisCentury; }; const FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1000; const adjustRfc850Year = (input) => { if (input.getTime() - new Date().getTime() > FIFTY_YEARS_IN_MILLIS) { return new Date(Date.UTC(input.getUTCFullYear() - 100, input.getUTCMonth(), input.getUTCDate(), input.getUTCHours(), input.getUTCMinutes(), input.getUTCSeconds(), input.getUTCMilliseconds())); } return input; }; const parseMonthByShortName = (value) => { const monthIdx = MONTHS.indexOf(value); if (monthIdx < 0) { throw new TypeError(`Invalid month: ${value}`); } return monthIdx + 1; }; const DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; const validateDayOfMonth = (year, month, day) => { let maxDays = DAYS_IN_MONTH[month]; if (month === 1 && isLeapYear(year)) { maxDays = 29; } if (day > maxDays) { throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`); } }; const isLeapYear = (year) => { return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); }; const parseDateValue = (value, type, lower, upper) => { const dateVal = (0, parse_utils_1.strictParseByte)(stripLeadingZeroes(value)); if (dateVal < lower || dateVal > upper) { throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`); } return dateVal; }; const parseMilliseconds = (value) => { if (value === null || value === undefined) { return 0; } return (0, parse_utils_1.strictParseFloat32)("0." + value) * 1000; }; const parseOffsetToMilliseconds = (value) => { const directionStr = value[0]; let direction = 1; if (directionStr == "+") { direction = 1; } else if (directionStr == "-") { direction = -1; } else { throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`); } const hour = Number(value.substring(1, 3)); const minute = Number(value.substring(4, 6)); return direction * (hour * 60 + minute) * 60 * 1000; }; const stripLeadingZeroes = (value) => { let idx = 0; while (idx < value.length - 1 && value.charAt(idx) === "0") { idx++; } if (idx === 0) { return value; } return value.slice(idx); }; /***/ }), /***/ 9681: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.withBaseException = exports.throwDefaultError = void 0; const exceptions_1 = __nccwpck_require__(88074); const throwDefaultError = ({ output, parsedBody, exceptionCtor, errorCode }) => { const $metadata = deserializeMetadata(output); const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : undefined; const response = new exceptionCtor({ name: (parsedBody === null || parsedBody === void 0 ? void 0 : parsedBody.code) || (parsedBody === null || parsedBody === void 0 ? void 0 : parsedBody.Code) || errorCode || statusCode || "UnknownError", $fault: "client", $metadata, }); throw (0, exceptions_1.decorateServiceException)(response, parsedBody); }; exports.throwDefaultError = throwDefaultError; const withBaseException = (ExceptionCtor) => { return ({ output, parsedBody, errorCode }) => { (0, exports.throwDefaultError)({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode }); }; }; exports.withBaseException = withBaseException; const deserializeMetadata = (output) => { var _a, _b; return ({ httpStatusCode: output.statusCode, requestId: (_b = (_a = output.headers["x-amzn-requestid"]) !== null && _a !== void 0 ? _a : output.headers["x-amzn-request-id"]) !== null && _b !== void 0 ? _b : output.headers["x-amz-request-id"], extendedRequestId: output.headers["x-amz-id-2"], cfId: output.headers["x-amz-cf-id"], }); }; /***/ }), /***/ 11163: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.loadConfigsForDefaultMode = void 0; const loadConfigsForDefaultMode = (mode) => { switch (mode) { case "standard": return { retryMode: "standard", connectionTimeout: 3100, }; case "in-region": return { retryMode: "standard", connectionTimeout: 1100, }; case "cross-region": return { retryMode: "standard", connectionTimeout: 3100, }; case "mobile": return { retryMode: "standard", connectionTimeout: 30000, }; default: return {}; } }; exports.loadConfigsForDefaultMode = loadConfigsForDefaultMode; /***/ }), /***/ 91809: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.emitWarningIfUnsupportedVersion = void 0; let warningEmitted = false; const emitWarningIfUnsupportedVersion = (version) => { if (version && !warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 14) { warningEmitted = true; } }; exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion; /***/ }), /***/ 88074: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.decorateServiceException = exports.ServiceException = void 0; class ServiceException extends Error { constructor(options) { super(options.message); Object.setPrototypeOf(this, ServiceException.prototype); this.name = options.name; this.$fault = options.$fault; this.$metadata = options.$metadata; } } exports.ServiceException = ServiceException; const decorateServiceException = (exception, additions = {}) => { Object.entries(additions) .filter(([, v]) => v !== undefined) .forEach(([k, v]) => { if (exception[k] == undefined || exception[k] === "") { exception[k] = v; } }); const message = exception.message || exception.Message || "UnknownError"; exception.message = message; delete exception.Message; return exception; }; exports.decorateServiceException = decorateServiceException; /***/ }), /***/ 76016: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.extendedEncodeURIComponent = void 0; function extendedEncodeURIComponent(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { return "%" + c.charCodeAt(0).toString(16).toUpperCase(); }); } exports.extendedEncodeURIComponent = extendedEncodeURIComponent; /***/ }), /***/ 30941: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveChecksumRuntimeConfig = exports.getChecksumConfiguration = exports.AlgorithmId = void 0; const types_1 = __nccwpck_require__(55756); Object.defineProperty(exports, "AlgorithmId", ({ enumerable: true, get: function () { return types_1.AlgorithmId; } })); const getChecksumConfiguration = (runtimeConfig) => { const checksumAlgorithms = []; for (const id in types_1.AlgorithmId) { const algorithmId = types_1.AlgorithmId[id]; if (runtimeConfig[algorithmId] === undefined) { continue; } checksumAlgorithms.push({ algorithmId: () => algorithmId, checksumConstructor: () => runtimeConfig[algorithmId], }); } return { _checksumAlgorithms: checksumAlgorithms, addChecksumAlgorithm(algo) { this._checksumAlgorithms.push(algo); }, checksumAlgorithms() { return this._checksumAlgorithms; }, }; }; exports.getChecksumConfiguration = getChecksumConfiguration; const resolveChecksumRuntimeConfig = (clientConfig) => { const runtimeConfig = {}; clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); }); return runtimeConfig; }; exports.resolveChecksumRuntimeConfig = resolveChecksumRuntimeConfig; /***/ }), /***/ 78643: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveDefaultRuntimeConfig = exports.getDefaultClientConfiguration = exports.getDefaultExtensionConfiguration = void 0; const checksum_1 = __nccwpck_require__(30941); const retry_1 = __nccwpck_require__(67367); const getDefaultExtensionConfiguration = (runtimeConfig) => { return { ...(0, checksum_1.getChecksumConfiguration)(runtimeConfig), ...(0, retry_1.getRetryConfiguration)(runtimeConfig), }; }; exports.getDefaultExtensionConfiguration = getDefaultExtensionConfiguration; exports.getDefaultClientConfiguration = exports.getDefaultExtensionConfiguration; const resolveDefaultRuntimeConfig = (config) => { return { ...(0, checksum_1.resolveChecksumRuntimeConfig)(config), ...(0, retry_1.resolveRetryRuntimeConfig)(config), }; }; exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; /***/ }), /***/ 1822: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(78643), exports); /***/ }), /***/ 67367: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveRetryRuntimeConfig = exports.getRetryConfiguration = void 0; const getRetryConfiguration = (runtimeConfig) => { let _retryStrategy = runtimeConfig.retryStrategy; return { setRetryStrategy(retryStrategy) { _retryStrategy = retryStrategy; }, retryStrategy() { return _retryStrategy; }, }; }; exports.getRetryConfiguration = getRetryConfiguration; const resolveRetryRuntimeConfig = (retryStrategyConfiguration) => { const runtimeConfig = {}; runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy(); return runtimeConfig; }; exports.resolveRetryRuntimeConfig = resolveRetryRuntimeConfig; /***/ }), /***/ 42638: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getArrayIfSingleItem = void 0; const getArrayIfSingleItem = (mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray]; exports.getArrayIfSingleItem = getArrayIfSingleItem; /***/ }), /***/ 92188: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getValueFromTextNode = void 0; const getValueFromTextNode = (obj) => { const textNodeName = "#text"; for (const key in obj) { if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== undefined) { obj[key] = obj[key][textNodeName]; } else if (typeof obj[key] === "object" && obj[key] !== null) { obj[key] = (0, exports.getValueFromTextNode)(obj[key]); } } return obj; }; exports.getValueFromTextNode = getValueFromTextNode; /***/ }), /***/ 63570: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(70438), exports); tslib_1.__exportStar(__nccwpck_require__(61600), exports); tslib_1.__exportStar(__nccwpck_require__(32813), exports); tslib_1.__exportStar(__nccwpck_require__(75414), exports); tslib_1.__exportStar(__nccwpck_require__(92541), exports); tslib_1.__exportStar(__nccwpck_require__(56929), exports); tslib_1.__exportStar(__nccwpck_require__(21737), exports); tslib_1.__exportStar(__nccwpck_require__(9681), exports); tslib_1.__exportStar(__nccwpck_require__(11163), exports); tslib_1.__exportStar(__nccwpck_require__(91809), exports); tslib_1.__exportStar(__nccwpck_require__(1822), exports); tslib_1.__exportStar(__nccwpck_require__(88074), exports); tslib_1.__exportStar(__nccwpck_require__(76016), exports); tslib_1.__exportStar(__nccwpck_require__(42638), exports); tslib_1.__exportStar(__nccwpck_require__(92188), exports); tslib_1.__exportStar(__nccwpck_require__(32964), exports); tslib_1.__exportStar(__nccwpck_require__(83495), exports); tslib_1.__exportStar(__nccwpck_require__(74857), exports); tslib_1.__exportStar(__nccwpck_require__(15342), exports); tslib_1.__exportStar(__nccwpck_require__(53456), exports); tslib_1.__exportStar(__nccwpck_require__(1752), exports); tslib_1.__exportStar(__nccwpck_require__(92480), exports); /***/ }), /***/ 32964: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LazyJsonString = exports.StringWrapper = void 0; const StringWrapper = function () { const Class = Object.getPrototypeOf(this).constructor; const Constructor = Function.bind.apply(String, [null, ...arguments]); const instance = new Constructor(); Object.setPrototypeOf(instance, Class.prototype); return instance; }; exports.StringWrapper = StringWrapper; exports.StringWrapper.prototype = Object.create(String.prototype, { constructor: { value: exports.StringWrapper, enumerable: false, writable: true, configurable: true, }, }); Object.setPrototypeOf(exports.StringWrapper, String); class LazyJsonString extends exports.StringWrapper { deserializeJSON() { return JSON.parse(super.toString()); } toJSON() { return super.toString(); } static fromObject(object) { if (object instanceof LazyJsonString) { return object; } else if (object instanceof String || typeof object === "string") { return new LazyJsonString(object); } return new LazyJsonString(JSON.stringify(object)); } } exports.LazyJsonString = LazyJsonString; /***/ }), /***/ 83495: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.take = exports.convertMap = exports.map = void 0; function map(arg0, arg1, arg2) { let target; let filter; let instructions; if (typeof arg1 === "undefined" && typeof arg2 === "undefined") { target = {}; instructions = arg0; } else { target = arg0; if (typeof arg1 === "function") { filter = arg1; instructions = arg2; return mapWithFilter(target, filter, instructions); } else { instructions = arg1; } } for (const key of Object.keys(instructions)) { if (!Array.isArray(instructions[key])) { target[key] = instructions[key]; continue; } applyInstruction(target, null, instructions, key); } return target; } exports.map = map; const convertMap = (target) => { const output = {}; for (const [k, v] of Object.entries(target || {})) { output[k] = [, v]; } return output; }; exports.convertMap = convertMap; const take = (source, instructions) => { const out = {}; for (const key in instructions) { applyInstruction(out, source, instructions, key); } return out; }; exports.take = take; const mapWithFilter = (target, filter, instructions) => { return map(target, Object.entries(instructions).reduce((_instructions, [key, value]) => { if (Array.isArray(value)) { _instructions[key] = value; } else { if (typeof value === "function") { _instructions[key] = [filter, value()]; } else { _instructions[key] = [filter, value]; } } return _instructions; }, {})); }; const applyInstruction = (target, source, instructions, targetKey) => { if (source !== null) { let instruction = instructions[targetKey]; if (typeof instruction === "function") { instruction = [, instruction]; } const [filter = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction; if ((typeof filter === "function" && filter(source[sourceKey])) || (typeof filter !== "function" && !!filter)) { target[targetKey] = valueFn(source[sourceKey]); } return; } let [filter, value] = instructions[targetKey]; if (typeof value === "function") { let _value; const defaultFilterPassed = filter === undefined && (_value = value()) != null; const customFilterPassed = (typeof filter === "function" && !!filter(void 0)) || (typeof filter !== "function" && !!filter); if (defaultFilterPassed) { target[targetKey] = _value; } else if (customFilterPassed) { target[targetKey] = value(); } } else { const defaultFilterPassed = filter === undefined && value != null; const customFilterPassed = (typeof filter === "function" && !!filter(value)) || (typeof filter !== "function" && !!filter); if (defaultFilterPassed || customFilterPassed) { target[targetKey] = value; } } }; const nonNullish = (_) => _ != null; const pass = (_) => _; /***/ }), /***/ 74857: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.logger = exports.strictParseByte = exports.strictParseShort = exports.strictParseInt32 = exports.strictParseInt = exports.strictParseLong = exports.limitedParseFloat32 = exports.limitedParseFloat = exports.handleFloat = exports.limitedParseDouble = exports.strictParseFloat32 = exports.strictParseFloat = exports.strictParseDouble = exports.expectUnion = exports.expectString = exports.expectObject = exports.expectNonNull = exports.expectByte = exports.expectShort = exports.expectInt32 = exports.expectInt = exports.expectLong = exports.expectFloat32 = exports.expectNumber = exports.expectBoolean = exports.parseBoolean = void 0; const parseBoolean = (value) => { switch (value) { case "true": return true; case "false": return false; default: throw new Error(`Unable to parse boolean value "${value}"`); } }; exports.parseBoolean = parseBoolean; const expectBoolean = (value) => { if (value === null || value === undefined) { return undefined; } if (typeof value === "number") { if (value === 0 || value === 1) { exports.logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); } if (value === 0) { return false; } if (value === 1) { return true; } } if (typeof value === "string") { const lower = value.toLowerCase(); if (lower === "false" || lower === "true") { exports.logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); } if (lower === "false") { return false; } if (lower === "true") { return true; } } if (typeof value === "boolean") { return value; } throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`); }; exports.expectBoolean = expectBoolean; const expectNumber = (value) => { if (value === null || value === undefined) { return undefined; } if (typeof value === "string") { const parsed = parseFloat(value); if (!Number.isNaN(parsed)) { if (String(parsed) !== String(value)) { exports.logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); } return parsed; } } if (typeof value === "number") { return value; } throw new TypeError(`Expected number, got ${typeof value}: ${value}`); }; exports.expectNumber = expectNumber; const MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); const expectFloat32 = (value) => { const expected = (0, exports.expectNumber)(value); if (expected !== undefined && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) { if (Math.abs(expected) > MAX_FLOAT) { throw new TypeError(`Expected 32-bit float, got ${value}`); } } return expected; }; exports.expectFloat32 = expectFloat32; const expectLong = (value) => { if (value === null || value === undefined) { return undefined; } if (Number.isInteger(value) && !Number.isNaN(value)) { return value; } throw new TypeError(`Expected integer, got ${typeof value}: ${value}`); }; exports.expectLong = expectLong; exports.expectInt = exports.expectLong; const expectInt32 = (value) => expectSizedInt(value, 32); exports.expectInt32 = expectInt32; const expectShort = (value) => expectSizedInt(value, 16); exports.expectShort = expectShort; const expectByte = (value) => expectSizedInt(value, 8); exports.expectByte = expectByte; const expectSizedInt = (value, size) => { const expected = (0, exports.expectLong)(value); if (expected !== undefined && castInt(expected, size) !== expected) { throw new TypeError(`Expected ${size}-bit integer, got ${value}`); } return expected; }; const castInt = (value, size) => { switch (size) { case 32: return Int32Array.of(value)[0]; case 16: return Int16Array.of(value)[0]; case 8: return Int8Array.of(value)[0]; } }; const expectNonNull = (value, location) => { if (value === null || value === undefined) { if (location) { throw new TypeError(`Expected a non-null value for ${location}`); } throw new TypeError("Expected a non-null value"); } return value; }; exports.expectNonNull = expectNonNull; const expectObject = (value) => { if (value === null || value === undefined) { return undefined; } if (typeof value === "object" && !Array.isArray(value)) { return value; } const receivedType = Array.isArray(value) ? "array" : typeof value; throw new TypeError(`Expected object, got ${receivedType}: ${value}`); }; exports.expectObject = expectObject; const expectString = (value) => { if (value === null || value === undefined) { return undefined; } if (typeof value === "string") { return value; } if (["boolean", "number", "bigint"].includes(typeof value)) { exports.logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`)); return String(value); } throw new TypeError(`Expected string, got ${typeof value}: ${value}`); }; exports.expectString = expectString; const expectUnion = (value) => { if (value === null || value === undefined) { return undefined; } const asObject = (0, exports.expectObject)(value); const setKeys = Object.entries(asObject) .filter(([, v]) => v != null) .map(([k]) => k); if (setKeys.length === 0) { throw new TypeError(`Unions must have exactly one non-null member. None were found.`); } if (setKeys.length > 1) { throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`); } return asObject; }; exports.expectUnion = expectUnion; const strictParseDouble = (value) => { if (typeof value == "string") { return (0, exports.expectNumber)(parseNumber(value)); } return (0, exports.expectNumber)(value); }; exports.strictParseDouble = strictParseDouble; exports.strictParseFloat = exports.strictParseDouble; const strictParseFloat32 = (value) => { if (typeof value == "string") { return (0, exports.expectFloat32)(parseNumber(value)); } return (0, exports.expectFloat32)(value); }; exports.strictParseFloat32 = strictParseFloat32; const NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; const parseNumber = (value) => { const matches = value.match(NUMBER_REGEX); if (matches === null || matches[0].length !== value.length) { throw new TypeError(`Expected real number, got implicit NaN`); } return parseFloat(value); }; const limitedParseDouble = (value) => { if (typeof value == "string") { return parseFloatString(value); } return (0, exports.expectNumber)(value); }; exports.limitedParseDouble = limitedParseDouble; exports.handleFloat = exports.limitedParseDouble; exports.limitedParseFloat = exports.limitedParseDouble; const limitedParseFloat32 = (value) => { if (typeof value == "string") { return parseFloatString(value); } return (0, exports.expectFloat32)(value); }; exports.limitedParseFloat32 = limitedParseFloat32; const parseFloatString = (value) => { switch (value) { case "NaN": return NaN; case "Infinity": return Infinity; case "-Infinity": return -Infinity; default: throw new Error(`Unable to parse float value: ${value}`); } }; const strictParseLong = (value) => { if (typeof value === "string") { return (0, exports.expectLong)(parseNumber(value)); } return (0, exports.expectLong)(value); }; exports.strictParseLong = strictParseLong; exports.strictParseInt = exports.strictParseLong; const strictParseInt32 = (value) => { if (typeof value === "string") { return (0, exports.expectInt32)(parseNumber(value)); } return (0, exports.expectInt32)(value); }; exports.strictParseInt32 = strictParseInt32; const strictParseShort = (value) => { if (typeof value === "string") { return (0, exports.expectShort)(parseNumber(value)); } return (0, exports.expectShort)(value); }; exports.strictParseShort = strictParseShort; const strictParseByte = (value) => { if (typeof value === "string") { return (0, exports.expectByte)(parseNumber(value)); } return (0, exports.expectByte)(value); }; exports.strictParseByte = strictParseByte; const stackTraceWarning = (message) => { return String(new TypeError(message).stack || message) .split("\n") .slice(0, 5) .filter((s) => !s.includes("stackTraceWarning")) .join("\n"); }; exports.logger = { warn: console.warn, }; /***/ }), /***/ 15342: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolvedPath = void 0; const extended_encode_uri_component_1 = __nccwpck_require__(76016); const resolvedPath = (resolvedPath, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => { if (input != null && input[memberName] !== undefined) { const labelValue = labelValueProvider(); if (labelValue.length <= 0) { throw new Error("Empty value provided for input HTTP label: " + memberName + "."); } resolvedPath = resolvedPath.replace(uriLabel, isGreedyLabel ? labelValue .split("/") .map((segment) => (0, extended_encode_uri_component_1.extendedEncodeURIComponent)(segment)) .join("/") : (0, extended_encode_uri_component_1.extendedEncodeURIComponent)(labelValue)); } else { throw new Error("No value provided for input HTTP label: " + memberName + "."); } return resolvedPath; }; exports.resolvedPath = resolvedPath; /***/ }), /***/ 53456: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.serializeFloat = void 0; const serializeFloat = (value) => { if (value !== value) { return "NaN"; } switch (value) { case Infinity: return "Infinity"; case -Infinity: return "-Infinity"; default: return value; } }; exports.serializeFloat = serializeFloat; /***/ }), /***/ 1752: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports._json = void 0; const _json = (obj) => { if (obj == null) { return {}; } if (Array.isArray(obj)) { return obj.filter((_) => _ != null); } if (typeof obj === "object") { const target = {}; for (const key of Object.keys(obj)) { if (obj[key] == null) { continue; } target[key] = (0, exports._json)(obj[key]); } return target; } return obj; }; exports._json = _json; /***/ }), /***/ 92480: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.splitEvery = void 0; function splitEvery(value, delimiter, numDelimiters) { if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) { throw new Error("Invalid number of delimiters (" + numDelimiters + ") for splitEvery."); } const segments = value.split(delimiter); if (numDelimiters === 1) { return segments; } const compoundSegments = []; let currentSegment = ""; for (let i = 0; i < segments.length; i++) { if (currentSegment === "") { currentSegment = segments[i]; } else { currentSegment += delimiter + segments[i]; } if ((i + 1) % numDelimiters === 0) { compoundSegments.push(currentSegment); currentSegment = ""; } } if (currentSegment !== "") { compoundSegments.push(currentSegment); } return compoundSegments; } exports.splitEvery = splitEvery; /***/ }), /***/ 74075: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 93242: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.HttpApiKeyAuthLocation = void 0; var HttpApiKeyAuthLocation; (function (HttpApiKeyAuthLocation) { HttpApiKeyAuthLocation["HEADER"] = "header"; HttpApiKeyAuthLocation["QUERY"] = "query"; })(HttpApiKeyAuthLocation = exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); /***/ }), /***/ 81851: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 91530: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 74020: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 52263: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 79467: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.HttpAuthLocation = void 0; var HttpAuthLocation; (function (HttpAuthLocation) { HttpAuthLocation["HEADER"] = "header"; HttpAuthLocation["QUERY"] = "query"; })(HttpAuthLocation = exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); /***/ }), /***/ 11239: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(79467), exports); tslib_1.__exportStar(__nccwpck_require__(93242), exports); tslib_1.__exportStar(__nccwpck_require__(81851), exports); tslib_1.__exportStar(__nccwpck_require__(91530), exports); tslib_1.__exportStar(__nccwpck_require__(74020), exports); tslib_1.__exportStar(__nccwpck_require__(52263), exports); /***/ }), /***/ 63274: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 78340: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 4744: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 68270: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 39580: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 57628: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(39580), exports); tslib_1.__exportStar(__nccwpck_require__(98398), exports); tslib_1.__exportStar(__nccwpck_require__(76522), exports); /***/ }), /***/ 98398: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 76522: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 89035: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 7225: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 54126: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.EndpointURLScheme = void 0; var EndpointURLScheme; (function (EndpointURLScheme) { EndpointURLScheme["HTTP"] = "http"; EndpointURLScheme["HTTPS"] = "https"; })(EndpointURLScheme = exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); /***/ }), /***/ 55612: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 43084: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 89843: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 63799: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 21550: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(55612), exports); tslib_1.__exportStar(__nccwpck_require__(43084), exports); tslib_1.__exportStar(__nccwpck_require__(89843), exports); tslib_1.__exportStar(__nccwpck_require__(57658), exports); tslib_1.__exportStar(__nccwpck_require__(63799), exports); /***/ }), /***/ 57658: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 88508: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 8947: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveChecksumRuntimeConfig = exports.getChecksumConfiguration = exports.AlgorithmId = void 0; var AlgorithmId; (function (AlgorithmId) { AlgorithmId["MD5"] = "md5"; AlgorithmId["CRC32"] = "crc32"; AlgorithmId["CRC32C"] = "crc32c"; AlgorithmId["SHA1"] = "sha1"; AlgorithmId["SHA256"] = "sha256"; })(AlgorithmId = exports.AlgorithmId || (exports.AlgorithmId = {})); const getChecksumConfiguration = (runtimeConfig) => { const checksumAlgorithms = []; if (runtimeConfig.sha256 !== undefined) { checksumAlgorithms.push({ algorithmId: () => AlgorithmId.SHA256, checksumConstructor: () => runtimeConfig.sha256, }); } if (runtimeConfig.md5 != undefined) { checksumAlgorithms.push({ algorithmId: () => AlgorithmId.MD5, checksumConstructor: () => runtimeConfig.md5, }); } return { _checksumAlgorithms: checksumAlgorithms, addChecksumAlgorithm(algo) { this._checksumAlgorithms.push(algo); }, checksumAlgorithms() { return this._checksumAlgorithms; }, }; }; exports.getChecksumConfiguration = getChecksumConfiguration; const resolveChecksumRuntimeConfig = (clientConfig) => { const runtimeConfig = {}; clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); }); return runtimeConfig; }; exports.resolveChecksumRuntimeConfig = resolveChecksumRuntimeConfig; /***/ }), /***/ 89169: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveDefaultRuntimeConfig = exports.getDefaultClientConfiguration = void 0; const checksum_1 = __nccwpck_require__(8947); const getDefaultClientConfiguration = (runtimeConfig) => { return { ...(0, checksum_1.getChecksumConfiguration)(runtimeConfig), }; }; exports.getDefaultClientConfiguration = getDefaultClientConfiguration; const resolveDefaultRuntimeConfig = (config) => { return { ...(0, checksum_1.resolveChecksumRuntimeConfig)(config), }; }; exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; /***/ }), /***/ 32245: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 47447: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AlgorithmId = void 0; const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(89169), exports); tslib_1.__exportStar(__nccwpck_require__(32245), exports); var checksum_1 = __nccwpck_require__(8947); Object.defineProperty(exports, "AlgorithmId", ({ enumerable: true, get: function () { return checksum_1.AlgorithmId; } })); /***/ }), /***/ 18883: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FieldPosition = void 0; var FieldPosition; (function (FieldPosition) { FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; })(FieldPosition = exports.FieldPosition || (exports.FieldPosition = {})); /***/ }), /***/ 197: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 7545: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 49123: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 28006: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(197), exports); tslib_1.__exportStar(__nccwpck_require__(7545), exports); tslib_1.__exportStar(__nccwpck_require__(49123), exports); tslib_1.__exportStar(__nccwpck_require__(84476), exports); /***/ }), /***/ 84476: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 55756: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(74075), exports); tslib_1.__exportStar(__nccwpck_require__(11239), exports); tslib_1.__exportStar(__nccwpck_require__(63274), exports); tslib_1.__exportStar(__nccwpck_require__(78340), exports); tslib_1.__exportStar(__nccwpck_require__(4744), exports); tslib_1.__exportStar(__nccwpck_require__(68270), exports); tslib_1.__exportStar(__nccwpck_require__(57628), exports); tslib_1.__exportStar(__nccwpck_require__(89035), exports); tslib_1.__exportStar(__nccwpck_require__(7225), exports); tslib_1.__exportStar(__nccwpck_require__(54126), exports); tslib_1.__exportStar(__nccwpck_require__(21550), exports); tslib_1.__exportStar(__nccwpck_require__(88508), exports); tslib_1.__exportStar(__nccwpck_require__(47447), exports); tslib_1.__exportStar(__nccwpck_require__(18883), exports); tslib_1.__exportStar(__nccwpck_require__(28006), exports); tslib_1.__exportStar(__nccwpck_require__(52866), exports); tslib_1.__exportStar(__nccwpck_require__(17756), exports); tslib_1.__exportStar(__nccwpck_require__(45489), exports); tslib_1.__exportStar(__nccwpck_require__(26524), exports); tslib_1.__exportStar(__nccwpck_require__(14603), exports); tslib_1.__exportStar(__nccwpck_require__(83752), exports); tslib_1.__exportStar(__nccwpck_require__(30774), exports); tslib_1.__exportStar(__nccwpck_require__(14089), exports); tslib_1.__exportStar(__nccwpck_require__(45678), exports); tslib_1.__exportStar(__nccwpck_require__(69926), exports); tslib_1.__exportStar(__nccwpck_require__(9945), exports); tslib_1.__exportStar(__nccwpck_require__(28564), exports); tslib_1.__exportStar(__nccwpck_require__(61285), exports); tslib_1.__exportStar(__nccwpck_require__(50364), exports); tslib_1.__exportStar(__nccwpck_require__(69304), exports); tslib_1.__exportStar(__nccwpck_require__(46098), exports); tslib_1.__exportStar(__nccwpck_require__(10375), exports); tslib_1.__exportStar(__nccwpck_require__(66894), exports); tslib_1.__exportStar(__nccwpck_require__(57887), exports); tslib_1.__exportStar(__nccwpck_require__(66255), exports); /***/ }), /***/ 52866: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 17756: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SMITHY_CONTEXT_KEY = void 0; exports.SMITHY_CONTEXT_KEY = "__smithy_context"; /***/ }), /***/ 45489: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 26524: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.IniSectionType = void 0; var IniSectionType; (function (IniSectionType) { IniSectionType["PROFILE"] = "profile"; IniSectionType["SSO_SESSION"] = "sso-session"; IniSectionType["SERVICES"] = "services"; })(IniSectionType = exports.IniSectionType || (exports.IniSectionType = {})); /***/ }), /***/ 14603: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 83752: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 30774: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 14089: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 45678: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 69926: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 9945: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 28564: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 61285: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 50364: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.RequestHandlerProtocol = void 0; var RequestHandlerProtocol; (function (RequestHandlerProtocol) { RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; })(RequestHandlerProtocol = exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); /***/ }), /***/ 69304: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 46098: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 10375: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 66894: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 57887: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 66255: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 14681: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseUrl = void 0; const querystring_parser_1 = __nccwpck_require__(4769); const parseUrl = (url) => { if (typeof url === "string") { return (0, exports.parseUrl)(new URL(url)); } const { hostname, pathname, port, protocol, search } = url; let query; if (search) { query = (0, querystring_parser_1.parseQueryString)(search); } return { hostname, port: port ? parseInt(port) : undefined, protocol, path: pathname, query, }; }; exports.parseUrl = parseUrl; /***/ }), /***/ 30305: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fromBase64 = void 0; const util_buffer_from_1 = __nccwpck_require__(31381); const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; const fromBase64 = (input) => { if ((input.length * 3) % 4 !== 0) { throw new TypeError(`Incorrect padding on base64 string.`); } if (!BASE64_REGEX.exec(input)) { throw new TypeError(`Invalid base64 string.`); } const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); }; exports.fromBase64 = fromBase64; /***/ }), /***/ 75600: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(30305), exports); tslib_1.__exportStar(__nccwpck_require__(74730), exports); /***/ }), /***/ 74730: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toBase64 = void 0; const util_buffer_from_1 = __nccwpck_require__(31381); const toBase64 = (input) => (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); exports.toBase64 = toBase64; /***/ }), /***/ 54880: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.calculateBodyLength = void 0; const fs_1 = __nccwpck_require__(57147); const calculateBodyLength = (body) => { if (!body) { return 0; } if (typeof body === "string") { return Buffer.from(body).length; } else if (typeof body.byteLength === "number") { return body.byteLength; } else if (typeof body.size === "number") { return body.size; } else if (typeof body.start === "number" && typeof body.end === "number") { return body.end + 1 - body.start; } else if (typeof body.path === "string" || Buffer.isBuffer(body.path)) { return (0, fs_1.lstatSync)(body.path).size; } else if (typeof body.fd === "number") { return (0, fs_1.fstatSync)(body.fd).size; } throw new Error(`Body Length computation failed for ${body}`); }; exports.calculateBodyLength = calculateBodyLength; /***/ }), /***/ 68075: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(54880), exports); /***/ }), /***/ 31381: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fromString = exports.fromArrayBuffer = void 0; const is_array_buffer_1 = __nccwpck_require__(10780); const buffer_1 = __nccwpck_require__(14300); const fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => { if (!(0, is_array_buffer_1.isArrayBuffer)(input)) { throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); } return buffer_1.Buffer.from(input, offset, length); }; exports.fromArrayBuffer = fromArrayBuffer; const fromString = (input, encoding) => { if (typeof input !== "string") { throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); } return encoding ? buffer_1.Buffer.from(input, encoding) : buffer_1.Buffer.from(input); }; exports.fromString = fromString; /***/ }), /***/ 42491: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.booleanSelector = exports.SelectorType = void 0; var SelectorType; (function (SelectorType) { SelectorType["ENV"] = "env"; SelectorType["CONFIG"] = "shared config entry"; })(SelectorType = exports.SelectorType || (exports.SelectorType = {})); const booleanSelector = (obj, key, type) => { if (!(key in obj)) return undefined; if (obj[key] === "true") return true; if (obj[key] === "false") return false; throw new Error(`Cannot load ${type} "${key}". Expected "true" or "false", got ${obj[key]}.`); }; exports.booleanSelector = booleanSelector; /***/ }), /***/ 83375: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(42491), exports); /***/ }), /***/ 56470: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.IMDS_REGION_PATH = exports.DEFAULTS_MODE_OPTIONS = exports.ENV_IMDS_DISABLED = exports.AWS_DEFAULT_REGION_ENV = exports.AWS_REGION_ENV = exports.AWS_EXECUTION_ENV = void 0; exports.AWS_EXECUTION_ENV = "AWS_EXECUTION_ENV"; exports.AWS_REGION_ENV = "AWS_REGION"; exports.AWS_DEFAULT_REGION_ENV = "AWS_DEFAULT_REGION"; exports.ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; exports.DEFAULTS_MODE_OPTIONS = ["in-region", "cross-region", "mobile", "standard", "legacy"]; exports.IMDS_REGION_PATH = "/latest/meta-data/placement/region"; /***/ }), /***/ 15577: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NODE_DEFAULTS_MODE_CONFIG_OPTIONS = void 0; const AWS_DEFAULTS_MODE_ENV = "AWS_DEFAULTS_MODE"; const AWS_DEFAULTS_MODE_CONFIG = "defaults_mode"; exports.NODE_DEFAULTS_MODE_CONFIG_OPTIONS = { environmentVariableSelector: (env) => { return env[AWS_DEFAULTS_MODE_ENV]; }, configFileSelector: (profile) => { return profile[AWS_DEFAULTS_MODE_CONFIG]; }, default: "legacy", }; /***/ }), /***/ 72429: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(46217), exports); /***/ }), /***/ 46217: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveDefaultsModeConfig = void 0; const config_resolver_1 = __nccwpck_require__(53098); const credential_provider_imds_1 = __nccwpck_require__(7477); const node_config_provider_1 = __nccwpck_require__(33461); const property_provider_1 = __nccwpck_require__(79721); const constants_1 = __nccwpck_require__(56470); const defaultsModeConfig_1 = __nccwpck_require__(15577); const resolveDefaultsModeConfig = ({ region = (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS), defaultsMode = (0, node_config_provider_1.loadConfig)(defaultsModeConfig_1.NODE_DEFAULTS_MODE_CONFIG_OPTIONS), } = {}) => (0, property_provider_1.memoize)(async () => { const mode = typeof defaultsMode === "function" ? await defaultsMode() : defaultsMode; switch (mode === null || mode === void 0 ? void 0 : mode.toLowerCase()) { case "auto": return resolveNodeDefaultsModeAuto(region); case "in-region": case "cross-region": case "mobile": case "standard": case "legacy": return Promise.resolve(mode === null || mode === void 0 ? void 0 : mode.toLocaleLowerCase()); case undefined: return Promise.resolve("legacy"); default: throw new Error(`Invalid parameter for "defaultsMode", expect ${constants_1.DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}`); } }); exports.resolveDefaultsModeConfig = resolveDefaultsModeConfig; const resolveNodeDefaultsModeAuto = async (clientRegion) => { if (clientRegion) { const resolvedRegion = typeof clientRegion === "function" ? await clientRegion() : clientRegion; const inferredRegion = await inferPhysicalRegion(); if (!inferredRegion) { return "standard"; } if (resolvedRegion === inferredRegion) { return "in-region"; } else { return "cross-region"; } } return "standard"; }; const inferPhysicalRegion = async () => { var _a; if (process.env[constants_1.AWS_EXECUTION_ENV] && (process.env[constants_1.AWS_REGION_ENV] || process.env[constants_1.AWS_DEFAULT_REGION_ENV])) { return (_a = process.env[constants_1.AWS_REGION_ENV]) !== null && _a !== void 0 ? _a : process.env[constants_1.AWS_DEFAULT_REGION_ENV]; } if (!process.env[constants_1.ENV_IMDS_DISABLED]) { try { const endpoint = await (0, credential_provider_imds_1.getInstanceMetadataEndpoint)(); return (await (0, credential_provider_imds_1.httpRequest)({ ...endpoint, path: constants_1.IMDS_REGION_PATH })).toString(); } catch (e) { } } }; /***/ }), /***/ 71280: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.debugId = void 0; exports.debugId = "endpoints"; /***/ }), /***/ 30540: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(71280), exports); tslib_1.__exportStar(__nccwpck_require__(48927), exports); /***/ }), /***/ 48927: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toDebugString = void 0; function toDebugString(input) { if (typeof input !== "object" || input == null) { return input; } if ("ref" in input) { return `$${toDebugString(input.ref)}`; } if ("fn" in input) { return `${input.fn}(${(input.argv || []).map(toDebugString).join(", ")})`; } return JSON.stringify(input, null, 2); } exports.toDebugString = toDebugString; /***/ }), /***/ 45473: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(55402), exports); tslib_1.__exportStar(__nccwpck_require__(55021), exports); tslib_1.__exportStar(__nccwpck_require__(38824), exports); tslib_1.__exportStar(__nccwpck_require__(78693), exports); tslib_1.__exportStar(__nccwpck_require__(75442), exports); /***/ }), /***/ 29132: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.booleanEquals = void 0; const booleanEquals = (value1, value2) => value1 === value2; exports.booleanEquals = booleanEquals; /***/ }), /***/ 84624: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getAttr = void 0; const types_1 = __nccwpck_require__(75442); const getAttrPathList_1 = __nccwpck_require__(91311); const getAttr = (value, path) => (0, getAttrPathList_1.getAttrPathList)(path).reduce((acc, index) => { if (typeof acc !== "object") { throw new types_1.EndpointError(`Index '${index}' in '${path}' not found in '${JSON.stringify(value)}'`); } else if (Array.isArray(acc)) { return acc[parseInt(index)]; } return acc[index]; }, value); exports.getAttr = getAttr; /***/ }), /***/ 91311: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getAttrPathList = void 0; const types_1 = __nccwpck_require__(75442); const getAttrPathList = (path) => { const parts = path.split("."); const pathList = []; for (const part of parts) { const squareBracketIndex = part.indexOf("["); if (squareBracketIndex !== -1) { if (part.indexOf("]") !== part.length - 1) { throw new types_1.EndpointError(`Path: '${path}' does not end with ']'`); } const arrayIndex = part.slice(squareBracketIndex + 1, -1); if (Number.isNaN(parseInt(arrayIndex))) { throw new types_1.EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path}'`); } if (squareBracketIndex !== 0) { pathList.push(part.slice(0, squareBracketIndex)); } pathList.push(arrayIndex); } else { pathList.push(part); } } return pathList; }; exports.getAttrPathList = getAttrPathList; /***/ }), /***/ 36559: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(29132), exports); tslib_1.__exportStar(__nccwpck_require__(84624), exports); tslib_1.__exportStar(__nccwpck_require__(71231), exports); tslib_1.__exportStar(__nccwpck_require__(55021), exports); tslib_1.__exportStar(__nccwpck_require__(42249), exports); tslib_1.__exportStar(__nccwpck_require__(84654), exports); tslib_1.__exportStar(__nccwpck_require__(72512), exports); tslib_1.__exportStar(__nccwpck_require__(49245), exports); tslib_1.__exportStar(__nccwpck_require__(51482), exports); /***/ }), /***/ 55402: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isIpAddress = void 0; const IP_V4_REGEX = new RegExp(`^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$`); const isIpAddress = (value) => IP_V4_REGEX.test(value) || (value.startsWith("[") && value.endsWith("]")); exports.isIpAddress = isIpAddress; /***/ }), /***/ 71231: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isSet = void 0; const isSet = (value) => value != null; exports.isSet = isSet; /***/ }), /***/ 55021: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isValidHostLabel = void 0; const VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`); const isValidHostLabel = (value, allowSubDomains = false) => { if (!allowSubDomains) { return VALID_HOST_LABEL_REGEX.test(value); } const labels = value.split("."); for (const label of labels) { if (!(0, exports.isValidHostLabel)(label)) { return false; } } return true; }; exports.isValidHostLabel = isValidHostLabel; /***/ }), /***/ 42249: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.not = void 0; const not = (value) => !value; exports.not = not; /***/ }), /***/ 84654: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseURL = void 0; const types_1 = __nccwpck_require__(55756); const isIpAddress_1 = __nccwpck_require__(55402); const DEFAULT_PORTS = { [types_1.EndpointURLScheme.HTTP]: 80, [types_1.EndpointURLScheme.HTTPS]: 443, }; const parseURL = (value) => { const whatwgURL = (() => { try { if (value instanceof URL) { return value; } if (typeof value === "object" && "hostname" in value) { const { hostname, port, protocol = "", path = "", query = {} } = value; const url = new URL(`${protocol}//${hostname}${port ? `:${port}` : ""}${path}`); url.search = Object.entries(query) .map(([k, v]) => `${k}=${v}`) .join("&"); return url; } return new URL(value); } catch (error) { return null; } })(); if (!whatwgURL) { console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`); return null; } const urlString = whatwgURL.href; const { host, hostname, pathname, protocol, search } = whatwgURL; if (search) { return null; } const scheme = protocol.slice(0, -1); if (!Object.values(types_1.EndpointURLScheme).includes(scheme)) { return null; } const isIp = (0, isIpAddress_1.isIpAddress)(hostname); const inputContainsDefaultPort = urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`) || (typeof value === "string" && value.includes(`${host}:${DEFAULT_PORTS[scheme]}`)); const authority = `${host}${inputContainsDefaultPort ? `:${DEFAULT_PORTS[scheme]}` : ``}`; return { scheme, authority, path: pathname, normalizedPath: pathname.endsWith("/") ? pathname : `${pathname}/`, isIp, }; }; exports.parseURL = parseURL; /***/ }), /***/ 72512: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.stringEquals = void 0; const stringEquals = (value1, value2) => value1 === value2; exports.stringEquals = stringEquals; /***/ }), /***/ 49245: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.substring = void 0; const substring = (input, start, stop, reverse) => { if (start >= stop || input.length < stop) { return null; } if (!reverse) { return input.substring(start, stop); } return input.substring(input.length - stop, input.length - start); }; exports.substring = substring; /***/ }), /***/ 51482: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.uriEncode = void 0; const uriEncode = (value) => encodeURIComponent(value).replace(/[!*'()]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`); exports.uriEncode = uriEncode; /***/ }), /***/ 78693: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveEndpoint = void 0; const debug_1 = __nccwpck_require__(30540); const types_1 = __nccwpck_require__(75442); const utils_1 = __nccwpck_require__(96871); const resolveEndpoint = (ruleSetObject, options) => { var _a, _b, _c, _d, _e, _f; const { endpointParams, logger } = options; const { parameters, rules } = ruleSetObject; (_b = (_a = options.logger) === null || _a === void 0 ? void 0 : _a.debug) === null || _b === void 0 ? void 0 : _b.call(_a, `${debug_1.debugId} Initial EndpointParams: ${(0, debug_1.toDebugString)(endpointParams)}`); const paramsWithDefault = Object.entries(parameters) .filter(([, v]) => v.default != null) .map(([k, v]) => [k, v.default]); if (paramsWithDefault.length > 0) { for (const [paramKey, paramDefaultValue] of paramsWithDefault) { endpointParams[paramKey] = (_c = endpointParams[paramKey]) !== null && _c !== void 0 ? _c : paramDefaultValue; } } const requiredParams = Object.entries(parameters) .filter(([, v]) => v.required) .map(([k]) => k); for (const requiredParam of requiredParams) { if (endpointParams[requiredParam] == null) { throw new types_1.EndpointError(`Missing required parameter: '${requiredParam}'`); } } const endpoint = (0, utils_1.evaluateRules)(rules, { endpointParams, logger, referenceRecord: {} }); if ((_d = options.endpointParams) === null || _d === void 0 ? void 0 : _d.Endpoint) { try { const givenEndpoint = new URL(options.endpointParams.Endpoint); const { protocol, port } = givenEndpoint; endpoint.url.protocol = protocol; endpoint.url.port = port; } catch (e) { } } (_f = (_e = options.logger) === null || _e === void 0 ? void 0 : _e.debug) === null || _f === void 0 ? void 0 : _f.call(_e, `${debug_1.debugId} Resolved endpoint: ${(0, debug_1.toDebugString)(endpoint)}`); return endpoint; }; exports.resolveEndpoint = resolveEndpoint; /***/ }), /***/ 84213: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.EndpointError = void 0; class EndpointError extends Error { constructor(message) { super(message); this.name = "EndpointError"; } } exports.EndpointError = EndpointError; /***/ }), /***/ 34073: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 72533: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 63135: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 19136: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 28344: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 75442: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(84213), exports); tslib_1.__exportStar(__nccwpck_require__(34073), exports); tslib_1.__exportStar(__nccwpck_require__(72533), exports); tslib_1.__exportStar(__nccwpck_require__(63135), exports); tslib_1.__exportStar(__nccwpck_require__(19136), exports); tslib_1.__exportStar(__nccwpck_require__(28344), exports); tslib_1.__exportStar(__nccwpck_require__(42535), exports); /***/ }), /***/ 42535: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 66318: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.callFunction = void 0; const customEndpointFunctions_1 = __nccwpck_require__(38824); const endpointFunctions_1 = __nccwpck_require__(70953); const evaluateExpression_1 = __nccwpck_require__(91692); const callFunction = ({ fn, argv }, options) => { const evaluatedArgs = argv.map((arg) => ["boolean", "number"].includes(typeof arg) ? arg : (0, evaluateExpression_1.evaluateExpression)(arg, "arg", options)); const fnSegments = fn.split("."); if (fnSegments[0] in customEndpointFunctions_1.customEndpointFunctions && fnSegments[1] != null) { return customEndpointFunctions_1.customEndpointFunctions[fnSegments[0]][fnSegments[1]](...evaluatedArgs); } return endpointFunctions_1.endpointFunctions[fn](...evaluatedArgs); }; exports.callFunction = callFunction; /***/ }), /***/ 38824: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.customEndpointFunctions = void 0; exports.customEndpointFunctions = {}; /***/ }), /***/ 70953: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.endpointFunctions = void 0; const lib_1 = __nccwpck_require__(36559); exports.endpointFunctions = { booleanEquals: lib_1.booleanEquals, getAttr: lib_1.getAttr, isSet: lib_1.isSet, isValidHostLabel: lib_1.isValidHostLabel, not: lib_1.not, parseURL: lib_1.parseURL, stringEquals: lib_1.stringEquals, substring: lib_1.substring, uriEncode: lib_1.uriEncode, }; /***/ }), /***/ 42138: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.evaluateCondition = void 0; const debug_1 = __nccwpck_require__(30540); const types_1 = __nccwpck_require__(75442); const callFunction_1 = __nccwpck_require__(66318); const evaluateCondition = ({ assign, ...fnArgs }, options) => { var _a, _b; if (assign && assign in options.referenceRecord) { throw new types_1.EndpointError(`'${assign}' is already defined in Reference Record.`); } const value = (0, callFunction_1.callFunction)(fnArgs, options); (_b = (_a = options.logger) === null || _a === void 0 ? void 0 : _a.debug) === null || _b === void 0 ? void 0 : _b.call(_a, debug_1.debugId, `evaluateCondition: ${(0, debug_1.toDebugString)(fnArgs)} = ${(0, debug_1.toDebugString)(value)}`); return { result: value === "" ? true : !!value, ...(assign != null && { toAssign: { name: assign, value } }), }; }; exports.evaluateCondition = evaluateCondition; /***/ }), /***/ 69584: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.evaluateConditions = void 0; const debug_1 = __nccwpck_require__(30540); const evaluateCondition_1 = __nccwpck_require__(42138); const evaluateConditions = (conditions = [], options) => { var _a, _b; const conditionsReferenceRecord = {}; for (const condition of conditions) { const { result, toAssign } = (0, evaluateCondition_1.evaluateCondition)(condition, { ...options, referenceRecord: { ...options.referenceRecord, ...conditionsReferenceRecord, }, }); if (!result) { return { result }; } if (toAssign) { conditionsReferenceRecord[toAssign.name] = toAssign.value; (_b = (_a = options.logger) === null || _a === void 0 ? void 0 : _a.debug) === null || _b === void 0 ? void 0 : _b.call(_a, debug_1.debugId, `assign: ${toAssign.name} := ${(0, debug_1.toDebugString)(toAssign.value)}`); } } return { result: true, referenceRecord: conditionsReferenceRecord }; }; exports.evaluateConditions = evaluateConditions; /***/ }), /***/ 14405: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.evaluateEndpointRule = void 0; const debug_1 = __nccwpck_require__(30540); const evaluateConditions_1 = __nccwpck_require__(69584); const getEndpointHeaders_1 = __nccwpck_require__(57225); const getEndpointProperties_1 = __nccwpck_require__(83067); const getEndpointUrl_1 = __nccwpck_require__(25672); const evaluateEndpointRule = (endpointRule, options) => { var _a, _b; const { conditions, endpoint } = endpointRule; const { result, referenceRecord } = (0, evaluateConditions_1.evaluateConditions)(conditions, options); if (!result) { return; } const endpointRuleOptions = { ...options, referenceRecord: { ...options.referenceRecord, ...referenceRecord }, }; const { url, properties, headers } = endpoint; (_b = (_a = options.logger) === null || _a === void 0 ? void 0 : _a.debug) === null || _b === void 0 ? void 0 : _b.call(_a, debug_1.debugId, `Resolving endpoint from template: ${(0, debug_1.toDebugString)(endpoint)}`); return { ...(headers != undefined && { headers: (0, getEndpointHeaders_1.getEndpointHeaders)(headers, endpointRuleOptions), }), ...(properties != undefined && { properties: (0, getEndpointProperties_1.getEndpointProperties)(properties, endpointRuleOptions), }), url: (0, getEndpointUrl_1.getEndpointUrl)(url, endpointRuleOptions), }; }; exports.evaluateEndpointRule = evaluateEndpointRule; /***/ }), /***/ 57563: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.evaluateErrorRule = void 0; const types_1 = __nccwpck_require__(75442); const evaluateConditions_1 = __nccwpck_require__(69584); const evaluateExpression_1 = __nccwpck_require__(91692); const evaluateErrorRule = (errorRule, options) => { const { conditions, error } = errorRule; const { result, referenceRecord } = (0, evaluateConditions_1.evaluateConditions)(conditions, options); if (!result) { return; } throw new types_1.EndpointError((0, evaluateExpression_1.evaluateExpression)(error, "Error", { ...options, referenceRecord: { ...options.referenceRecord, ...referenceRecord }, })); }; exports.evaluateErrorRule = evaluateErrorRule; /***/ }), /***/ 91692: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.evaluateExpression = void 0; const types_1 = __nccwpck_require__(75442); const callFunction_1 = __nccwpck_require__(66318); const evaluateTemplate_1 = __nccwpck_require__(21922); const getReferenceValue_1 = __nccwpck_require__(17142); const evaluateExpression = (obj, keyName, options) => { if (typeof obj === "string") { return (0, evaluateTemplate_1.evaluateTemplate)(obj, options); } else if (obj["fn"]) { return (0, callFunction_1.callFunction)(obj, options); } else if (obj["ref"]) { return (0, getReferenceValue_1.getReferenceValue)(obj, options); } throw new types_1.EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`); }; exports.evaluateExpression = evaluateExpression; /***/ }), /***/ 48830: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.evaluateRules = void 0; const types_1 = __nccwpck_require__(75442); const evaluateEndpointRule_1 = __nccwpck_require__(14405); const evaluateErrorRule_1 = __nccwpck_require__(57563); const evaluateTreeRule_1 = __nccwpck_require__(55085); const evaluateRules = (rules, options) => { for (const rule of rules) { if (rule.type === "endpoint") { const endpointOrUndefined = (0, evaluateEndpointRule_1.evaluateEndpointRule)(rule, options); if (endpointOrUndefined) { return endpointOrUndefined; } } else if (rule.type === "error") { (0, evaluateErrorRule_1.evaluateErrorRule)(rule, options); } else if (rule.type === "tree") { const endpointOrUndefined = (0, evaluateTreeRule_1.evaluateTreeRule)(rule, options); if (endpointOrUndefined) { return endpointOrUndefined; } } else { throw new types_1.EndpointError(`Unknown endpoint rule: ${rule}`); } } throw new types_1.EndpointError(`Rules evaluation failed`); }; exports.evaluateRules = evaluateRules; /***/ }), /***/ 21922: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.evaluateTemplate = void 0; const lib_1 = __nccwpck_require__(36559); const evaluateTemplate = (template, options) => { const evaluatedTemplateArr = []; const templateContext = { ...options.endpointParams, ...options.referenceRecord, }; let currentIndex = 0; while (currentIndex < template.length) { const openingBraceIndex = template.indexOf("{", currentIndex); if (openingBraceIndex === -1) { evaluatedTemplateArr.push(template.slice(currentIndex)); break; } evaluatedTemplateArr.push(template.slice(currentIndex, openingBraceIndex)); const closingBraceIndex = template.indexOf("}", openingBraceIndex); if (closingBraceIndex === -1) { evaluatedTemplateArr.push(template.slice(openingBraceIndex)); break; } if (template[openingBraceIndex + 1] === "{" && template[closingBraceIndex + 1] === "}") { evaluatedTemplateArr.push(template.slice(openingBraceIndex + 1, closingBraceIndex)); currentIndex = closingBraceIndex + 2; } const parameterName = template.substring(openingBraceIndex + 1, closingBraceIndex); if (parameterName.includes("#")) { const [refName, attrName] = parameterName.split("#"); evaluatedTemplateArr.push((0, lib_1.getAttr)(templateContext[refName], attrName)); } else { evaluatedTemplateArr.push(templateContext[parameterName]); } currentIndex = closingBraceIndex + 1; } return evaluatedTemplateArr.join(""); }; exports.evaluateTemplate = evaluateTemplate; /***/ }), /***/ 55085: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.evaluateTreeRule = void 0; const evaluateConditions_1 = __nccwpck_require__(69584); const evaluateRules_1 = __nccwpck_require__(48830); const evaluateTreeRule = (treeRule, options) => { const { conditions, rules } = treeRule; const { result, referenceRecord } = (0, evaluateConditions_1.evaluateConditions)(conditions, options); if (!result) { return; } return (0, evaluateRules_1.evaluateRules)(rules, { ...options, referenceRecord: { ...options.referenceRecord, ...referenceRecord }, }); }; exports.evaluateTreeRule = evaluateTreeRule; /***/ }), /***/ 57225: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getEndpointHeaders = void 0; const types_1 = __nccwpck_require__(75442); const evaluateExpression_1 = __nccwpck_require__(91692); const getEndpointHeaders = (headers, options) => Object.entries(headers).reduce((acc, [headerKey, headerVal]) => ({ ...acc, [headerKey]: headerVal.map((headerValEntry) => { const processedExpr = (0, evaluateExpression_1.evaluateExpression)(headerValEntry, "Header value entry", options); if (typeof processedExpr !== "string") { throw new types_1.EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`); } return processedExpr; }), }), {}); exports.getEndpointHeaders = getEndpointHeaders; /***/ }), /***/ 83067: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getEndpointProperties = void 0; const getEndpointProperty_1 = __nccwpck_require__(26152); const getEndpointProperties = (properties, options) => Object.entries(properties).reduce((acc, [propertyKey, propertyVal]) => ({ ...acc, [propertyKey]: (0, getEndpointProperty_1.getEndpointProperty)(propertyVal, options), }), {}); exports.getEndpointProperties = getEndpointProperties; /***/ }), /***/ 26152: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getEndpointProperty = void 0; const types_1 = __nccwpck_require__(75442); const evaluateTemplate_1 = __nccwpck_require__(21922); const getEndpointProperties_1 = __nccwpck_require__(83067); const getEndpointProperty = (property, options) => { if (Array.isArray(property)) { return property.map((propertyEntry) => (0, exports.getEndpointProperty)(propertyEntry, options)); } switch (typeof property) { case "string": return (0, evaluateTemplate_1.evaluateTemplate)(property, options); case "object": if (property === null) { throw new types_1.EndpointError(`Unexpected endpoint property: ${property}`); } return (0, getEndpointProperties_1.getEndpointProperties)(property, options); case "boolean": return property; default: throw new types_1.EndpointError(`Unexpected endpoint property type: ${typeof property}`); } }; exports.getEndpointProperty = getEndpointProperty; /***/ }), /***/ 25672: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getEndpointUrl = void 0; const types_1 = __nccwpck_require__(75442); const evaluateExpression_1 = __nccwpck_require__(91692); const getEndpointUrl = (endpointUrl, options) => { const expression = (0, evaluateExpression_1.evaluateExpression)(endpointUrl, "Endpoint URL", options); if (typeof expression === "string") { try { return new URL(expression); } catch (error) { console.error(`Failed to construct URL with ${expression}`, error); throw error; } } throw new types_1.EndpointError(`Endpoint URL must be a string, got ${typeof expression}`); }; exports.getEndpointUrl = getEndpointUrl; /***/ }), /***/ 17142: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getReferenceValue = void 0; const getReferenceValue = ({ ref }, options) => { const referenceRecord = { ...options.endpointParams, ...options.referenceRecord, }; return referenceRecord[ref]; }; exports.getReferenceValue = getReferenceValue; /***/ }), /***/ 96871: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(38824), exports); tslib_1.__exportStar(__nccwpck_require__(48830), exports); /***/ }), /***/ 45364: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toHex = exports.fromHex = void 0; const SHORT_TO_HEX = {}; const HEX_TO_SHORT = {}; for (let i = 0; i < 256; i++) { let encodedByte = i.toString(16).toLowerCase(); if (encodedByte.length === 1) { encodedByte = `0${encodedByte}`; } SHORT_TO_HEX[i] = encodedByte; HEX_TO_SHORT[encodedByte] = i; } function fromHex(encoded) { if (encoded.length % 2 !== 0) { throw new Error("Hex encoded strings must have an even number length"); } const out = new Uint8Array(encoded.length / 2); for (let i = 0; i < encoded.length; i += 2) { const encodedByte = encoded.slice(i, i + 2).toLowerCase(); if (encodedByte in HEX_TO_SHORT) { out[i / 2] = HEX_TO_SHORT[encodedByte]; } else { throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); } } return out; } exports.fromHex = fromHex; function toHex(bytes) { let out = ""; for (let i = 0; i < bytes.byteLength; i++) { out += SHORT_TO_HEX[bytes[i]]; } return out; } exports.toHex = toHex; /***/ }), /***/ 85730: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getSmithyContext = void 0; const types_1 = __nccwpck_require__(55756); const getSmithyContext = (context) => context[types_1.SMITHY_CONTEXT_KEY] || (context[types_1.SMITHY_CONTEXT_KEY] = {}); exports.getSmithyContext = getSmithyContext; /***/ }), /***/ 2390: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(85730), exports); tslib_1.__exportStar(__nccwpck_require__(80149), exports); /***/ }), /***/ 80149: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.normalizeProvider = void 0; const normalizeProvider = (input) => { if (typeof input === "function") return input; const promisified = Promise.resolve(input); return () => promisified; }; exports.normalizeProvider = normalizeProvider; /***/ }), /***/ 65053: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AdaptiveRetryStrategy = void 0; const config_1 = __nccwpck_require__(93435); const DefaultRateLimiter_1 = __nccwpck_require__(22234); const StandardRetryStrategy_1 = __nccwpck_require__(48361); class AdaptiveRetryStrategy { constructor(maxAttemptsProvider, options) { this.maxAttemptsProvider = maxAttemptsProvider; this.mode = config_1.RETRY_MODES.ADAPTIVE; const { rateLimiter } = options !== null && options !== void 0 ? options : {}; this.rateLimiter = rateLimiter !== null && rateLimiter !== void 0 ? rateLimiter : new DefaultRateLimiter_1.DefaultRateLimiter(); this.standardRetryStrategy = new StandardRetryStrategy_1.StandardRetryStrategy(maxAttemptsProvider); } async acquireInitialRetryToken(retryTokenScope) { await this.rateLimiter.getSendToken(); return this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope); } async refreshRetryTokenForRetry(tokenToRenew, errorInfo) { this.rateLimiter.updateClientSendingRate(errorInfo); return this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew, errorInfo); } recordSuccess(token) { this.rateLimiter.updateClientSendingRate({}); this.standardRetryStrategy.recordSuccess(token); } } exports.AdaptiveRetryStrategy = AdaptiveRetryStrategy; /***/ }), /***/ 25689: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ConfiguredRetryStrategy = void 0; const constants_1 = __nccwpck_require__(66302); const StandardRetryStrategy_1 = __nccwpck_require__(48361); class ConfiguredRetryStrategy extends StandardRetryStrategy_1.StandardRetryStrategy { constructor(maxAttempts, computeNextBackoffDelay = constants_1.DEFAULT_RETRY_DELAY_BASE) { super(typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts); if (typeof computeNextBackoffDelay === "number") { this.computeNextBackoffDelay = () => computeNextBackoffDelay; } else { this.computeNextBackoffDelay = computeNextBackoffDelay; } } async refreshRetryTokenForRetry(tokenToRenew, errorInfo) { const token = await super.refreshRetryTokenForRetry(tokenToRenew, errorInfo); token.getRetryDelay = () => this.computeNextBackoffDelay(token.getRetryCount()); return token; } } exports.ConfiguredRetryStrategy = ConfiguredRetryStrategy; /***/ }), /***/ 22234: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DefaultRateLimiter = void 0; const service_error_classification_1 = __nccwpck_require__(6375); class DefaultRateLimiter { constructor(options) { var _a, _b, _c, _d, _e; this.currentCapacity = 0; this.enabled = false; this.lastMaxRate = 0; this.measuredTxRate = 0; this.requestCount = 0; this.lastTimestamp = 0; this.timeWindow = 0; this.beta = (_a = options === null || options === void 0 ? void 0 : options.beta) !== null && _a !== void 0 ? _a : 0.7; this.minCapacity = (_b = options === null || options === void 0 ? void 0 : options.minCapacity) !== null && _b !== void 0 ? _b : 1; this.minFillRate = (_c = options === null || options === void 0 ? void 0 : options.minFillRate) !== null && _c !== void 0 ? _c : 0.5; this.scaleConstant = (_d = options === null || options === void 0 ? void 0 : options.scaleConstant) !== null && _d !== void 0 ? _d : 0.4; this.smooth = (_e = options === null || options === void 0 ? void 0 : options.smooth) !== null && _e !== void 0 ? _e : 0.8; const currentTimeInSeconds = this.getCurrentTimeInSeconds(); this.lastThrottleTime = currentTimeInSeconds; this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds()); this.fillRate = this.minFillRate; this.maxCapacity = this.minCapacity; } getCurrentTimeInSeconds() { return Date.now() / 1000; } async getSendToken() { return this.acquireTokenBucket(1); } async acquireTokenBucket(amount) { if (!this.enabled) { return; } this.refillTokenBucket(); if (amount > this.currentCapacity) { const delay = ((amount - this.currentCapacity) / this.fillRate) * 1000; await new Promise((resolve) => setTimeout(resolve, delay)); } this.currentCapacity = this.currentCapacity - amount; } refillTokenBucket() { const timestamp = this.getCurrentTimeInSeconds(); if (!this.lastTimestamp) { this.lastTimestamp = timestamp; return; } const fillAmount = (timestamp - this.lastTimestamp) * this.fillRate; this.currentCapacity = Math.min(this.maxCapacity, this.currentCapacity + fillAmount); this.lastTimestamp = timestamp; } updateClientSendingRate(response) { let calculatedRate; this.updateMeasuredRate(); if ((0, service_error_classification_1.isThrottlingError)(response)) { const rateToUse = !this.enabled ? this.measuredTxRate : Math.min(this.measuredTxRate, this.fillRate); this.lastMaxRate = rateToUse; this.calculateTimeWindow(); this.lastThrottleTime = this.getCurrentTimeInSeconds(); calculatedRate = this.cubicThrottle(rateToUse); this.enableTokenBucket(); } else { this.calculateTimeWindow(); calculatedRate = this.cubicSuccess(this.getCurrentTimeInSeconds()); } const newRate = Math.min(calculatedRate, 2 * this.measuredTxRate); this.updateTokenBucketRate(newRate); } calculateTimeWindow() { this.timeWindow = this.getPrecise(Math.pow((this.lastMaxRate * (1 - this.beta)) / this.scaleConstant, 1 / 3)); } cubicThrottle(rateToUse) { return this.getPrecise(rateToUse * this.beta); } cubicSuccess(timestamp) { return this.getPrecise(this.scaleConstant * Math.pow(timestamp - this.lastThrottleTime - this.timeWindow, 3) + this.lastMaxRate); } enableTokenBucket() { this.enabled = true; } updateTokenBucketRate(newRate) { this.refillTokenBucket(); this.fillRate = Math.max(newRate, this.minFillRate); this.maxCapacity = Math.max(newRate, this.minCapacity); this.currentCapacity = Math.min(this.currentCapacity, this.maxCapacity); } updateMeasuredRate() { const t = this.getCurrentTimeInSeconds(); const timeBucket = Math.floor(t * 2) / 2; this.requestCount++; if (timeBucket > this.lastTxRateBucket) { const currentRate = this.requestCount / (timeBucket - this.lastTxRateBucket); this.measuredTxRate = this.getPrecise(currentRate * this.smooth + this.measuredTxRate * (1 - this.smooth)); this.requestCount = 0; this.lastTxRateBucket = timeBucket; } } getPrecise(num) { return parseFloat(num.toFixed(8)); } } exports.DefaultRateLimiter = DefaultRateLimiter; /***/ }), /***/ 48361: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.StandardRetryStrategy = void 0; const config_1 = __nccwpck_require__(93435); const constants_1 = __nccwpck_require__(66302); const defaultRetryBackoffStrategy_1 = __nccwpck_require__(21337); const defaultRetryToken_1 = __nccwpck_require__(1127); class StandardRetryStrategy { constructor(maxAttempts) { this.maxAttempts = maxAttempts; this.mode = config_1.RETRY_MODES.STANDARD; this.capacity = constants_1.INITIAL_RETRY_TOKENS; this.retryBackoffStrategy = (0, defaultRetryBackoffStrategy_1.getDefaultRetryBackoffStrategy)(); this.maxAttemptsProvider = typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts; } async acquireInitialRetryToken(retryTokenScope) { return (0, defaultRetryToken_1.createDefaultRetryToken)({ retryDelay: constants_1.DEFAULT_RETRY_DELAY_BASE, retryCount: 0, }); } async refreshRetryTokenForRetry(token, errorInfo) { const maxAttempts = await this.getMaxAttempts(); if (this.shouldRetry(token, errorInfo, maxAttempts)) { const errorType = errorInfo.errorType; this.retryBackoffStrategy.setDelayBase(errorType === "THROTTLING" ? constants_1.THROTTLING_RETRY_DELAY_BASE : constants_1.DEFAULT_RETRY_DELAY_BASE); const delayFromErrorType = this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount()); const retryDelay = errorInfo.retryAfterHint ? Math.max(errorInfo.retryAfterHint.getTime() - Date.now() || 0, delayFromErrorType) : delayFromErrorType; const capacityCost = this.getCapacityCost(errorType); this.capacity -= capacityCost; return (0, defaultRetryToken_1.createDefaultRetryToken)({ retryDelay, retryCount: token.getRetryCount() + 1, retryCost: capacityCost, }); } throw new Error("No retry token available"); } recordSuccess(token) { var _a; this.capacity = Math.max(constants_1.INITIAL_RETRY_TOKENS, this.capacity + ((_a = token.getRetryCost()) !== null && _a !== void 0 ? _a : constants_1.NO_RETRY_INCREMENT)); } getCapacity() { return this.capacity; } async getMaxAttempts() { try { return await this.maxAttemptsProvider(); } catch (error) { console.warn(`Max attempts provider could not resolve. Using default of ${config_1.DEFAULT_MAX_ATTEMPTS}`); return config_1.DEFAULT_MAX_ATTEMPTS; } } shouldRetry(tokenToRenew, errorInfo, maxAttempts) { const attempts = tokenToRenew.getRetryCount() + 1; return (attempts < maxAttempts && this.capacity >= this.getCapacityCost(errorInfo.errorType) && this.isRetryableError(errorInfo.errorType)); } getCapacityCost(errorType) { return errorType === "TRANSIENT" ? constants_1.TIMEOUT_RETRY_COST : constants_1.RETRY_COST; } isRetryableError(errorType) { return errorType === "THROTTLING" || errorType === "TRANSIENT"; } } exports.StandardRetryStrategy = StandardRetryStrategy; /***/ }), /***/ 93435: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DEFAULT_RETRY_MODE = exports.DEFAULT_MAX_ATTEMPTS = exports.RETRY_MODES = void 0; var RETRY_MODES; (function (RETRY_MODES) { RETRY_MODES["STANDARD"] = "standard"; RETRY_MODES["ADAPTIVE"] = "adaptive"; })(RETRY_MODES = exports.RETRY_MODES || (exports.RETRY_MODES = {})); exports.DEFAULT_MAX_ATTEMPTS = 3; exports.DEFAULT_RETRY_MODE = RETRY_MODES.STANDARD; /***/ }), /***/ 66302: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.REQUEST_HEADER = exports.INVOCATION_ID_HEADER = exports.NO_RETRY_INCREMENT = exports.TIMEOUT_RETRY_COST = exports.RETRY_COST = exports.INITIAL_RETRY_TOKENS = exports.THROTTLING_RETRY_DELAY_BASE = exports.MAXIMUM_RETRY_DELAY = exports.DEFAULT_RETRY_DELAY_BASE = void 0; exports.DEFAULT_RETRY_DELAY_BASE = 100; exports.MAXIMUM_RETRY_DELAY = 20 * 1000; exports.THROTTLING_RETRY_DELAY_BASE = 500; exports.INITIAL_RETRY_TOKENS = 500; exports.RETRY_COST = 5; exports.TIMEOUT_RETRY_COST = 10; exports.NO_RETRY_INCREMENT = 1; exports.INVOCATION_ID_HEADER = "amz-sdk-invocation-id"; exports.REQUEST_HEADER = "amz-sdk-request"; /***/ }), /***/ 21337: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getDefaultRetryBackoffStrategy = void 0; const constants_1 = __nccwpck_require__(66302); const getDefaultRetryBackoffStrategy = () => { let delayBase = constants_1.DEFAULT_RETRY_DELAY_BASE; const computeNextBackoffDelay = (attempts) => { return Math.floor(Math.min(constants_1.MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)); }; const setDelayBase = (delay) => { delayBase = delay; }; return { computeNextBackoffDelay, setDelayBase, }; }; exports.getDefaultRetryBackoffStrategy = getDefaultRetryBackoffStrategy; /***/ }), /***/ 1127: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createDefaultRetryToken = void 0; const constants_1 = __nccwpck_require__(66302); const createDefaultRetryToken = ({ retryDelay, retryCount, retryCost, }) => { const getRetryCount = () => retryCount; const getRetryDelay = () => Math.min(constants_1.MAXIMUM_RETRY_DELAY, retryDelay); const getRetryCost = () => retryCost; return { getRetryCount, getRetryDelay, getRetryCost, }; }; exports.createDefaultRetryToken = createDefaultRetryToken; /***/ }), /***/ 84902: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(65053), exports); tslib_1.__exportStar(__nccwpck_require__(25689), exports); tslib_1.__exportStar(__nccwpck_require__(22234), exports); tslib_1.__exportStar(__nccwpck_require__(48361), exports); tslib_1.__exportStar(__nccwpck_require__(93435), exports); tslib_1.__exportStar(__nccwpck_require__(66302), exports); tslib_1.__exportStar(__nccwpck_require__(75427), exports); /***/ }), /***/ 75427: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 22094: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Uint8ArrayBlobAdapter = void 0; const transforms_1 = __nccwpck_require__(82098); class Uint8ArrayBlobAdapter extends Uint8Array { static fromString(source, encoding = "utf-8") { switch (typeof source) { case "string": return (0, transforms_1.transformFromString)(source, encoding); default: throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); } } static mutate(source) { Object.setPrototypeOf(source, Uint8ArrayBlobAdapter.prototype); return source; } transformToString(encoding = "utf-8") { return (0, transforms_1.transformToString)(this, encoding); } } exports.Uint8ArrayBlobAdapter = Uint8ArrayBlobAdapter; /***/ }), /***/ 82098: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.transformFromString = exports.transformToString = void 0; const util_base64_1 = __nccwpck_require__(75600); const util_utf8_1 = __nccwpck_require__(41895); const Uint8ArrayBlobAdapter_1 = __nccwpck_require__(22094); function transformToString(payload, encoding = "utf-8") { if (encoding === "base64") { return (0, util_base64_1.toBase64)(payload); } return (0, util_utf8_1.toUtf8)(payload); } exports.transformToString = transformToString; function transformFromString(str, encoding) { if (encoding === "base64") { return Uint8ArrayBlobAdapter_1.Uint8ArrayBlobAdapter.mutate((0, util_base64_1.fromBase64)(str)); } return Uint8ArrayBlobAdapter_1.Uint8ArrayBlobAdapter.mutate((0, util_utf8_1.fromUtf8)(str)); } exports.transformFromString = transformFromString; /***/ }), /***/ 23636: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getAwsChunkedEncodingStream = void 0; const stream_1 = __nccwpck_require__(12781); const getAwsChunkedEncodingStream = (readableStream, options) => { const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; const checksumRequired = base64Encoder !== undefined && checksumAlgorithmFn !== undefined && checksumLocationName !== undefined && streamHasher !== undefined; const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : undefined; const awsChunkedEncodingStream = new stream_1.Readable({ read: () => { } }); readableStream.on("data", (data) => { const length = bodyLengthChecker(data) || 0; awsChunkedEncodingStream.push(`${length.toString(16)}\r\n`); awsChunkedEncodingStream.push(data); awsChunkedEncodingStream.push("\r\n"); }); readableStream.on("end", async () => { awsChunkedEncodingStream.push(`0\r\n`); if (checksumRequired) { const checksum = base64Encoder(await digest); awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r\n`); awsChunkedEncodingStream.push(`\r\n`); } awsChunkedEncodingStream.push(null); }); return awsChunkedEncodingStream; }; exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream; /***/ }), /***/ 96607: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(22094), exports); tslib_1.__exportStar(__nccwpck_require__(23636), exports); tslib_1.__exportStar(__nccwpck_require__(4515), exports); /***/ }), /***/ 4515: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.sdkStreamMixin = void 0; const node_http_handler_1 = __nccwpck_require__(20258); const util_buffer_from_1 = __nccwpck_require__(31381); const stream_1 = __nccwpck_require__(12781); const util_1 = __nccwpck_require__(73837); const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; const sdkStreamMixin = (stream) => { var _a, _b; if (!(stream instanceof stream_1.Readable)) { const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`); } let transformed = false; const transformToByteArray = async () => { if (transformed) { throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); } transformed = true; return await (0, node_http_handler_1.streamCollector)(stream); }; return Object.assign(stream, { transformToByteArray, transformToString: async (encoding) => { const buf = await transformToByteArray(); if (encoding === undefined || Buffer.isEncoding(encoding)) { return (0, util_buffer_from_1.fromArrayBuffer)(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding); } else { const decoder = new util_1.TextDecoder(encoding); return decoder.decode(buf); } }, transformToWebStream: () => { if (transformed) { throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); } if (stream.readableFlowing !== null) { throw new Error("The stream has been consumed by other callbacks."); } if (typeof stream_1.Readable.toWeb !== "function") { throw new Error("Readable.toWeb() is not supported. Please make sure you are using Node.js >= 17.0.0, or polyfill is available."); } transformed = true; return stream_1.Readable.toWeb(stream); }, }); }; exports.sdkStreamMixin = sdkStreamMixin; /***/ }), /***/ 26174: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.escapeUriPath = void 0; const escape_uri_1 = __nccwpck_require__(60010); const escapeUriPath = (uri) => uri.split("/").map(escape_uri_1.escapeUri).join("/"); exports.escapeUriPath = escapeUriPath; /***/ }), /***/ 60010: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.escapeUri = void 0; const escapeUri = (uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode); exports.escapeUri = escapeUri; const hexEncode = (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`; /***/ }), /***/ 54197: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(60010), exports); tslib_1.__exportStar(__nccwpck_require__(26174), exports); /***/ }), /***/ 45917: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fromUtf8 = void 0; const util_buffer_from_1 = __nccwpck_require__(31381); const fromUtf8 = (input) => { const buf = (0, util_buffer_from_1.fromString)(input, "utf8"); return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); }; exports.fromUtf8 = fromUtf8; /***/ }), /***/ 41895: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(4351); tslib_1.__exportStar(__nccwpck_require__(45917), exports); tslib_1.__exportStar(__nccwpck_require__(95470), exports); tslib_1.__exportStar(__nccwpck_require__(99960), exports); /***/ }), /***/ 95470: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toUint8Array = void 0; const fromUtf8_1 = __nccwpck_require__(45917); const toUint8Array = (data) => { if (typeof data === "string") { return (0, fromUtf8_1.fromUtf8)(data); } if (ArrayBuffer.isView(data)) { return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); } return new Uint8Array(data); }; exports.toUint8Array = toUint8Array; /***/ }), /***/ 99960: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toUtf8 = void 0; const util_buffer_from_1 = __nccwpck_require__(31381); const toUtf8 = (input) => (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); exports.toUtf8 = toUtf8; /***/ }), /***/ 14293: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; const asn1 = exports; asn1.bignum = __nccwpck_require__(32664); asn1.define = (__nccwpck_require__(85245).define); asn1.base = __nccwpck_require__(78096); asn1.constants = __nccwpck_require__(3371); asn1.decoders = __nccwpck_require__(94952); asn1.encoders = __nccwpck_require__(79083); /***/ }), /***/ 85245: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; const encoders = __nccwpck_require__(79083); const decoders = __nccwpck_require__(94952); const inherits = __nccwpck_require__(44124); const api = exports; api.define = function define(name, body) { return new Entity(name, body); }; function Entity(name, body) { this.name = name; this.body = body; this.decoders = {}; this.encoders = {}; } Entity.prototype._createNamed = function createNamed(Base) { const name = this.name; function Generated(entity) { this._initNamed(entity, name); } inherits(Generated, Base); Generated.prototype._initNamed = function _initNamed(entity, name) { Base.call(this, entity, name); }; return new Generated(this); }; Entity.prototype._getDecoder = function _getDecoder(enc) { enc = enc || 'der'; // Lazily create decoder if (!this.decoders.hasOwnProperty(enc)) this.decoders[enc] = this._createNamed(decoders[enc]); return this.decoders[enc]; }; Entity.prototype.decode = function decode(data, enc, options) { return this._getDecoder(enc).decode(data, options); }; Entity.prototype._getEncoder = function _getEncoder(enc) { enc = enc || 'der'; // Lazily create encoder if (!this.encoders.hasOwnProperty(enc)) this.encoders[enc] = this._createNamed(encoders[enc]); return this.encoders[enc]; }; Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) { return this._getEncoder(enc).encode(data, reporter); }; /***/ }), /***/ 15298: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; const inherits = __nccwpck_require__(44124); const Reporter = (__nccwpck_require__(23744)/* .Reporter */ .b); const Buffer = (__nccwpck_require__(15118).Buffer); function DecoderBuffer(base, options) { Reporter.call(this, options); if (!Buffer.isBuffer(base)) { this.error('Input not Buffer'); return; } this.base = base; this.offset = 0; this.length = base.length; } inherits(DecoderBuffer, Reporter); exports.C = DecoderBuffer; DecoderBuffer.isDecoderBuffer = function isDecoderBuffer(data) { if (data instanceof DecoderBuffer) { return true; } // Or accept compatible API const isCompatible = typeof data === 'object' && Buffer.isBuffer(data.base) && data.constructor.name === 'DecoderBuffer' && typeof data.offset === 'number' && typeof data.length === 'number' && typeof data.save === 'function' && typeof data.restore === 'function' && typeof data.isEmpty === 'function' && typeof data.readUInt8 === 'function' && typeof data.skip === 'function' && typeof data.raw === 'function'; return isCompatible; }; DecoderBuffer.prototype.save = function save() { return { offset: this.offset, reporter: Reporter.prototype.save.call(this) }; }; DecoderBuffer.prototype.restore = function restore(save) { // Return skipped data const res = new DecoderBuffer(this.base); res.offset = save.offset; res.length = this.offset; this.offset = save.offset; Reporter.prototype.restore.call(this, save.reporter); return res; }; DecoderBuffer.prototype.isEmpty = function isEmpty() { return this.offset === this.length; }; DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) { if (this.offset + 1 <= this.length) return this.base.readUInt8(this.offset++, true); else return this.error(fail || 'DecoderBuffer overrun'); }; DecoderBuffer.prototype.skip = function skip(bytes, fail) { if (!(this.offset + bytes <= this.length)) return this.error(fail || 'DecoderBuffer overrun'); const res = new DecoderBuffer(this.base); // Share reporter state res._reporterState = this._reporterState; res.offset = this.offset; res.length = this.offset + bytes; this.offset += bytes; return res; }; DecoderBuffer.prototype.raw = function raw(save) { return this.base.slice(save ? save.offset : this.offset, this.length); }; function EncoderBuffer(value, reporter) { if (Array.isArray(value)) { this.length = 0; this.value = value.map(function(item) { if (!EncoderBuffer.isEncoderBuffer(item)) item = new EncoderBuffer(item, reporter); this.length += item.length; return item; }, this); } else if (typeof value === 'number') { if (!(0 <= value && value <= 0xff)) return reporter.error('non-byte EncoderBuffer value'); this.value = value; this.length = 1; } else if (typeof value === 'string') { this.value = value; this.length = Buffer.byteLength(value); } else if (Buffer.isBuffer(value)) { this.value = value; this.length = value.length; } else { return reporter.error('Unsupported type: ' + typeof value); } } exports.R = EncoderBuffer; EncoderBuffer.isEncoderBuffer = function isEncoderBuffer(data) { if (data instanceof EncoderBuffer) { return true; } // Or accept compatible API const isCompatible = typeof data === 'object' && data.constructor.name === 'EncoderBuffer' && typeof data.length === 'number' && typeof data.join === 'function'; return isCompatible; }; EncoderBuffer.prototype.join = function join(out, offset) { if (!out) out = Buffer.alloc(this.length); if (!offset) offset = 0; if (this.length === 0) return out; if (Array.isArray(this.value)) { this.value.forEach(function(item) { item.join(out, offset); offset += item.length; }); } else { if (typeof this.value === 'number') out[offset] = this.value; else if (typeof this.value === 'string') out.write(this.value, offset); else if (Buffer.isBuffer(this.value)) this.value.copy(out, offset); offset += this.length; } return out; }; /***/ }), /***/ 78096: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; const base = exports; base.Reporter = (__nccwpck_require__(23744)/* .Reporter */ .b); base.DecoderBuffer = (__nccwpck_require__(15298)/* .DecoderBuffer */ .C); base.EncoderBuffer = (__nccwpck_require__(15298)/* .EncoderBuffer */ .R); base.Node = __nccwpck_require__(80842); /***/ }), /***/ 80842: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Reporter = (__nccwpck_require__(23744)/* .Reporter */ .b); const EncoderBuffer = (__nccwpck_require__(15298)/* .EncoderBuffer */ .R); const DecoderBuffer = (__nccwpck_require__(15298)/* .DecoderBuffer */ .C); const assert = __nccwpck_require__(90910); // Supported tags const tags = [ 'seq', 'seqof', 'set', 'setof', 'objid', 'bool', 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc', 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr' ]; // Public methods list const methods = [ 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', 'any', 'contains' ].concat(tags); // Overrided methods list const overrided = [ '_peekTag', '_decodeTag', '_use', '_decodeStr', '_decodeObjid', '_decodeTime', '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', '_encodeNull', '_encodeInt', '_encodeBool' ]; function Node(enc, parent, name) { const state = {}; this._baseState = state; state.name = name; state.enc = enc; state.parent = parent || null; state.children = null; // State state.tag = null; state.args = null; state.reverseArgs = null; state.choice = null; state.optional = false; state.any = false; state.obj = false; state.use = null; state.useDecoder = null; state.key = null; state['default'] = null; state.explicit = null; state.implicit = null; state.contains = null; // Should create new instance on each method if (!state.parent) { state.children = []; this._wrap(); } } module.exports = Node; const stateProps = [ 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', 'implicit', 'contains' ]; Node.prototype.clone = function clone() { const state = this._baseState; const cstate = {}; stateProps.forEach(function(prop) { cstate[prop] = state[prop]; }); const res = new this.constructor(cstate.parent); res._baseState = cstate; return res; }; Node.prototype._wrap = function wrap() { const state = this._baseState; methods.forEach(function(method) { this[method] = function _wrappedMethod() { const clone = new this.constructor(this); state.children.push(clone); return clone[method].apply(clone, arguments); }; }, this); }; Node.prototype._init = function init(body) { const state = this._baseState; assert(state.parent === null); body.call(this); // Filter children state.children = state.children.filter(function(child) { return child._baseState.parent === this; }, this); assert.equal(state.children.length, 1, 'Root node can have only one child'); }; Node.prototype._useArgs = function useArgs(args) { const state = this._baseState; // Filter children and args const children = args.filter(function(arg) { return arg instanceof this.constructor; }, this); args = args.filter(function(arg) { return !(arg instanceof this.constructor); }, this); if (children.length !== 0) { assert(state.children === null); state.children = children; // Replace parent to maintain backward link children.forEach(function(child) { child._baseState.parent = this; }, this); } if (args.length !== 0) { assert(state.args === null); state.args = args; state.reverseArgs = args.map(function(arg) { if (typeof arg !== 'object' || arg.constructor !== Object) return arg; const res = {}; Object.keys(arg).forEach(function(key) { if (key == (key | 0)) key |= 0; const value = arg[key]; res[value] = key; }); return res; }); } }; // // Overrided methods // overrided.forEach(function(method) { Node.prototype[method] = function _overrided() { const state = this._baseState; throw new Error(method + ' not implemented for encoding: ' + state.enc); }; }); // // Public methods // tags.forEach(function(tag) { Node.prototype[tag] = function _tagMethod() { const state = this._baseState; const args = Array.prototype.slice.call(arguments); assert(state.tag === null); state.tag = tag; this._useArgs(args); return this; }; }); Node.prototype.use = function use(item) { assert(item); const state = this._baseState; assert(state.use === null); state.use = item; return this; }; Node.prototype.optional = function optional() { const state = this._baseState; state.optional = true; return this; }; Node.prototype.def = function def(val) { const state = this._baseState; assert(state['default'] === null); state['default'] = val; state.optional = true; return this; }; Node.prototype.explicit = function explicit(num) { const state = this._baseState; assert(state.explicit === null && state.implicit === null); state.explicit = num; return this; }; Node.prototype.implicit = function implicit(num) { const state = this._baseState; assert(state.explicit === null && state.implicit === null); state.implicit = num; return this; }; Node.prototype.obj = function obj() { const state = this._baseState; const args = Array.prototype.slice.call(arguments); state.obj = true; if (args.length !== 0) this._useArgs(args); return this; }; Node.prototype.key = function key(newKey) { const state = this._baseState; assert(state.key === null); state.key = newKey; return this; }; Node.prototype.any = function any() { const state = this._baseState; state.any = true; return this; }; Node.prototype.choice = function choice(obj) { const state = this._baseState; assert(state.choice === null); state.choice = obj; this._useArgs(Object.keys(obj).map(function(key) { return obj[key]; })); return this; }; Node.prototype.contains = function contains(item) { const state = this._baseState; assert(state.use === null); state.contains = item; return this; }; // // Decoding // Node.prototype._decode = function decode(input, options) { const state = this._baseState; // Decode root node if (state.parent === null) return input.wrapResult(state.children[0]._decode(input, options)); let result = state['default']; let present = true; let prevKey = null; if (state.key !== null) prevKey = input.enterKey(state.key); // Check if tag is there if (state.optional) { let tag = null; if (state.explicit !== null) tag = state.explicit; else if (state.implicit !== null) tag = state.implicit; else if (state.tag !== null) tag = state.tag; if (tag === null && !state.any) { // Trial and Error const save = input.save(); try { if (state.choice === null) this._decodeGeneric(state.tag, input, options); else this._decodeChoice(input, options); present = true; } catch (e) { present = false; } input.restore(save); } else { present = this._peekTag(input, tag, state.any); if (input.isError(present)) return present; } } // Push object on stack let prevObj; if (state.obj && present) prevObj = input.enterObject(); if (present) { // Unwrap explicit values if (state.explicit !== null) { const explicit = this._decodeTag(input, state.explicit); if (input.isError(explicit)) return explicit; input = explicit; } const start = input.offset; // Unwrap implicit and normal values if (state.use === null && state.choice === null) { let save; if (state.any) save = input.save(); const body = this._decodeTag( input, state.implicit !== null ? state.implicit : state.tag, state.any ); if (input.isError(body)) return body; if (state.any) result = input.raw(save); else input = body; } if (options && options.track && state.tag !== null) options.track(input.path(), start, input.length, 'tagged'); if (options && options.track && state.tag !== null) options.track(input.path(), input.offset, input.length, 'content'); // Select proper method for tag if (state.any) { // no-op } else if (state.choice === null) { result = this._decodeGeneric(state.tag, input, options); } else { result = this._decodeChoice(input, options); } if (input.isError(result)) return result; // Decode children if (!state.any && state.choice === null && state.children !== null) { state.children.forEach(function decodeChildren(child) { // NOTE: We are ignoring errors here, to let parser continue with other // parts of encoded data child._decode(input, options); }); } // Decode contained/encoded by schema, only in bit or octet strings if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { const data = new DecoderBuffer(result); result = this._getUse(state.contains, input._reporterState.obj) ._decode(data, options); } } // Pop object if (state.obj && present) result = input.leaveObject(prevObj); // Set key if (state.key !== null && (result !== null || present === true)) input.leaveKey(prevKey, state.key, result); else if (prevKey !== null) input.exitKey(prevKey); return result; }; Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) { const state = this._baseState; if (tag === 'seq' || tag === 'set') return null; if (tag === 'seqof' || tag === 'setof') return this._decodeList(input, tag, state.args[0], options); else if (/str$/.test(tag)) return this._decodeStr(input, tag, options); else if (tag === 'objid' && state.args) return this._decodeObjid(input, state.args[0], state.args[1], options); else if (tag === 'objid') return this._decodeObjid(input, null, null, options); else if (tag === 'gentime' || tag === 'utctime') return this._decodeTime(input, tag, options); else if (tag === 'null_') return this._decodeNull(input, options); else if (tag === 'bool') return this._decodeBool(input, options); else if (tag === 'objDesc') return this._decodeStr(input, tag, options); else if (tag === 'int' || tag === 'enum') return this._decodeInt(input, state.args && state.args[0], options); if (state.use !== null) { return this._getUse(state.use, input._reporterState.obj) ._decode(input, options); } else { return input.error('unknown tag: ' + tag); } }; Node.prototype._getUse = function _getUse(entity, obj) { const state = this._baseState; // Create altered use decoder if implicit is set state.useDecoder = this._use(entity, obj); assert(state.useDecoder._baseState.parent === null); state.useDecoder = state.useDecoder._baseState.children[0]; if (state.implicit !== state.useDecoder._baseState.implicit) { state.useDecoder = state.useDecoder.clone(); state.useDecoder._baseState.implicit = state.implicit; } return state.useDecoder; }; Node.prototype._decodeChoice = function decodeChoice(input, options) { const state = this._baseState; let result = null; let match = false; Object.keys(state.choice).some(function(key) { const save = input.save(); const node = state.choice[key]; try { const value = node._decode(input, options); if (input.isError(value)) return false; result = { type: key, value: value }; match = true; } catch (e) { input.restore(save); return false; } return true; }, this); if (!match) return input.error('Choice not matched'); return result; }; // // Encoding // Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) { return new EncoderBuffer(data, this.reporter); }; Node.prototype._encode = function encode(data, reporter, parent) { const state = this._baseState; if (state['default'] !== null && state['default'] === data) return; const result = this._encodeValue(data, reporter, parent); if (result === undefined) return; if (this._skipDefault(result, reporter, parent)) return; return result; }; Node.prototype._encodeValue = function encode(data, reporter, parent) { const state = this._baseState; // Decode root node if (state.parent === null) return state.children[0]._encode(data, reporter || new Reporter()); let result = null; // Set reporter to share it with a child class this.reporter = reporter; // Check if data is there if (state.optional && data === undefined) { if (state['default'] !== null) data = state['default']; else return; } // Encode children first let content = null; let primitive = false; if (state.any) { // Anything that was given is translated to buffer result = this._createEncoderBuffer(data); } else if (state.choice) { result = this._encodeChoice(data, reporter); } else if (state.contains) { content = this._getUse(state.contains, parent)._encode(data, reporter); primitive = true; } else if (state.children) { content = state.children.map(function(child) { if (child._baseState.tag === 'null_') return child._encode(null, reporter, data); if (child._baseState.key === null) return reporter.error('Child should have a key'); const prevKey = reporter.enterKey(child._baseState.key); if (typeof data !== 'object') return reporter.error('Child expected, but input is not object'); const res = child._encode(data[child._baseState.key], reporter, data); reporter.leaveKey(prevKey); return res; }, this).filter(function(child) { return child; }); content = this._createEncoderBuffer(content); } else { if (state.tag === 'seqof' || state.tag === 'setof') { // TODO(indutny): this should be thrown on DSL level if (!(state.args && state.args.length === 1)) return reporter.error('Too many args for : ' + state.tag); if (!Array.isArray(data)) return reporter.error('seqof/setof, but data is not Array'); const child = this.clone(); child._baseState.implicit = null; content = this._createEncoderBuffer(data.map(function(item) { const state = this._baseState; return this._getUse(state.args[0], data)._encode(item, reporter); }, child)); } else if (state.use !== null) { result = this._getUse(state.use, parent)._encode(data, reporter); } else { content = this._encodePrimitive(state.tag, data); primitive = true; } } // Encode data itself if (!state.any && state.choice === null) { const tag = state.implicit !== null ? state.implicit : state.tag; const cls = state.implicit === null ? 'universal' : 'context'; if (tag === null) { if (state.use === null) reporter.error('Tag could be omitted only for .use()'); } else { if (state.use === null) result = this._encodeComposite(tag, primitive, cls, content); } } // Wrap in explicit if (state.explicit !== null) result = this._encodeComposite(state.explicit, false, 'context', result); return result; }; Node.prototype._encodeChoice = function encodeChoice(data, reporter) { const state = this._baseState; const node = state.choice[data.type]; if (!node) { assert( false, data.type + ' not found in ' + JSON.stringify(Object.keys(state.choice))); } return node._encode(data.value, reporter); }; Node.prototype._encodePrimitive = function encodePrimitive(tag, data) { const state = this._baseState; if (/str$/.test(tag)) return this._encodeStr(data, tag); else if (tag === 'objid' && state.args) return this._encodeObjid(data, state.reverseArgs[0], state.args[1]); else if (tag === 'objid') return this._encodeObjid(data, null, null); else if (tag === 'gentime' || tag === 'utctime') return this._encodeTime(data, tag); else if (tag === 'null_') return this._encodeNull(); else if (tag === 'int' || tag === 'enum') return this._encodeInt(data, state.args && state.reverseArgs[0]); else if (tag === 'bool') return this._encodeBool(data); else if (tag === 'objDesc') return this._encodeStr(data, tag); else throw new Error('Unsupported tag: ' + tag); }; Node.prototype._isNumstr = function isNumstr(str) { return /^[0-9 ]*$/.test(str); }; Node.prototype._isPrintstr = function isPrintstr(str) { return /^[A-Za-z0-9 '()+,-./:=?]*$/.test(str); }; /***/ }), /***/ 23744: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; const inherits = __nccwpck_require__(44124); function Reporter(options) { this._reporterState = { obj: null, path: [], options: options || {}, errors: [] }; } exports.b = Reporter; Reporter.prototype.isError = function isError(obj) { return obj instanceof ReporterError; }; Reporter.prototype.save = function save() { const state = this._reporterState; return { obj: state.obj, pathLen: state.path.length }; }; Reporter.prototype.restore = function restore(data) { const state = this._reporterState; state.obj = data.obj; state.path = state.path.slice(0, data.pathLen); }; Reporter.prototype.enterKey = function enterKey(key) { return this._reporterState.path.push(key); }; Reporter.prototype.exitKey = function exitKey(index) { const state = this._reporterState; state.path = state.path.slice(0, index - 1); }; Reporter.prototype.leaveKey = function leaveKey(index, key, value) { const state = this._reporterState; this.exitKey(index); if (state.obj !== null) state.obj[key] = value; }; Reporter.prototype.path = function path() { return this._reporterState.path.join('/'); }; Reporter.prototype.enterObject = function enterObject() { const state = this._reporterState; const prev = state.obj; state.obj = {}; return prev; }; Reporter.prototype.leaveObject = function leaveObject(prev) { const state = this._reporterState; const now = state.obj; state.obj = prev; return now; }; Reporter.prototype.error = function error(msg) { let err; const state = this._reporterState; const inherited = msg instanceof ReporterError; if (inherited) { err = msg; } else { err = new ReporterError(state.path.map(function(elem) { return '[' + JSON.stringify(elem) + ']'; }).join(''), msg.message || msg, msg.stack); } if (!state.options.partial) throw err; if (!inherited) state.errors.push(err); return err; }; Reporter.prototype.wrapResult = function wrapResult(result) { const state = this._reporterState; if (!state.options.partial) return result; return { result: this.isError(result) ? null : result, errors: state.errors }; }; function ReporterError(path, msg) { this.path = path; this.rethrow(msg); } inherits(ReporterError, Error); ReporterError.prototype.rethrow = function rethrow(msg) { this.message = msg + ' at: ' + (this.path || '(shallow)'); if (Error.captureStackTrace) Error.captureStackTrace(this, ReporterError); if (!this.stack) { try { // IE only adds stack when thrown throw new Error(this.message); } catch (e) { this.stack = e.stack; } } return this; }; /***/ }), /***/ 64293: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Helper function reverse(map) { const res = {}; Object.keys(map).forEach(function(key) { // Convert key to integer if it is stringified if ((key | 0) == key) key = key | 0; const value = map[key]; res[value] = key; }); return res; } exports.tagClass = { 0: 'universal', 1: 'application', 2: 'context', 3: 'private' }; exports.tagClassByName = reverse(exports.tagClass); exports.tag = { 0x00: 'end', 0x01: 'bool', 0x02: 'int', 0x03: 'bitstr', 0x04: 'octstr', 0x05: 'null_', 0x06: 'objid', 0x07: 'objDesc', 0x08: 'external', 0x09: 'real', 0x0a: 'enum', 0x0b: 'embed', 0x0c: 'utf8str', 0x0d: 'relativeOid', 0x10: 'seq', 0x11: 'set', 0x12: 'numstr', 0x13: 'printstr', 0x14: 't61str', 0x15: 'videostr', 0x16: 'ia5str', 0x17: 'utctime', 0x18: 'gentime', 0x19: 'graphstr', 0x1a: 'iso646str', 0x1b: 'genstr', 0x1c: 'unistr', 0x1d: 'charstr', 0x1e: 'bmpstr' }; exports.tagByName = reverse(exports.tag); /***/ }), /***/ 3371: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; const constants = exports; // Helper constants._reverse = function reverse(map) { const res = {}; Object.keys(map).forEach(function(key) { // Convert key to integer if it is stringified if ((key | 0) == key) key = key | 0; const value = map[key]; res[value] = key; }); return res; }; constants.der = __nccwpck_require__(64293); /***/ }), /***/ 3332: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const inherits = __nccwpck_require__(44124); const bignum = __nccwpck_require__(32664); const DecoderBuffer = (__nccwpck_require__(15298)/* .DecoderBuffer */ .C); const Node = __nccwpck_require__(80842); // Import DER constants const der = __nccwpck_require__(64293); function DERDecoder(entity) { this.enc = 'der'; this.name = entity.name; this.entity = entity; // Construct base tree this.tree = new DERNode(); this.tree._init(entity.body); } module.exports = DERDecoder; DERDecoder.prototype.decode = function decode(data, options) { if (!DecoderBuffer.isDecoderBuffer(data)) { data = new DecoderBuffer(data, options); } return this.tree._decode(data, options); }; // Tree methods function DERNode(parent) { Node.call(this, 'der', parent); } inherits(DERNode, Node); DERNode.prototype._peekTag = function peekTag(buffer, tag, any) { if (buffer.isEmpty()) return false; const state = buffer.save(); const decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"'); if (buffer.isError(decodedTag)) return decodedTag; buffer.restore(state); return decodedTag.tag === tag || decodedTag.tagStr === tag || (decodedTag.tagStr + 'of') === tag || any; }; DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) { const decodedTag = derDecodeTag(buffer, 'Failed to decode tag of "' + tag + '"'); if (buffer.isError(decodedTag)) return decodedTag; let len = derDecodeLen(buffer, decodedTag.primitive, 'Failed to get length of "' + tag + '"'); // Failure if (buffer.isError(len)) return len; if (!any && decodedTag.tag !== tag && decodedTag.tagStr !== tag && decodedTag.tagStr + 'of' !== tag) { return buffer.error('Failed to match tag: "' + tag + '"'); } if (decodedTag.primitive || len !== null) return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); // Indefinite length... find END tag const state = buffer.save(); const res = this._skipUntilEnd( buffer, 'Failed to skip indefinite length body: "' + this.tag + '"'); if (buffer.isError(res)) return res; len = buffer.offset - state.offset; buffer.restore(state); return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); }; DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) { for (;;) { const tag = derDecodeTag(buffer, fail); if (buffer.isError(tag)) return tag; const len = derDecodeLen(buffer, tag.primitive, fail); if (buffer.isError(len)) return len; let res; if (tag.primitive || len !== null) res = buffer.skip(len); else res = this._skipUntilEnd(buffer, fail); // Failure if (buffer.isError(res)) return res; if (tag.tagStr === 'end') break; } }; DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder, options) { const result = []; while (!buffer.isEmpty()) { const possibleEnd = this._peekTag(buffer, 'end'); if (buffer.isError(possibleEnd)) return possibleEnd; const res = decoder.decode(buffer, 'der', options); if (buffer.isError(res) && possibleEnd) break; result.push(res); } return result; }; DERNode.prototype._decodeStr = function decodeStr(buffer, tag) { if (tag === 'bitstr') { const unused = buffer.readUInt8(); if (buffer.isError(unused)) return unused; return { unused: unused, data: buffer.raw() }; } else if (tag === 'bmpstr') { const raw = buffer.raw(); if (raw.length % 2 === 1) return buffer.error('Decoding of string type: bmpstr length mismatch'); let str = ''; for (let i = 0; i < raw.length / 2; i++) { str += String.fromCharCode(raw.readUInt16BE(i * 2)); } return str; } else if (tag === 'numstr') { const numstr = buffer.raw().toString('ascii'); if (!this._isNumstr(numstr)) { return buffer.error('Decoding of string type: ' + 'numstr unsupported characters'); } return numstr; } else if (tag === 'octstr') { return buffer.raw(); } else if (tag === 'objDesc') { return buffer.raw(); } else if (tag === 'printstr') { const printstr = buffer.raw().toString('ascii'); if (!this._isPrintstr(printstr)) { return buffer.error('Decoding of string type: ' + 'printstr unsupported characters'); } return printstr; } else if (/str$/.test(tag)) { return buffer.raw().toString(); } else { return buffer.error('Decoding of string type: ' + tag + ' unsupported'); } }; DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) { let result; const identifiers = []; let ident = 0; let subident = 0; while (!buffer.isEmpty()) { subident = buffer.readUInt8(); ident <<= 7; ident |= subident & 0x7f; if ((subident & 0x80) === 0) { identifiers.push(ident); ident = 0; } } if (subident & 0x80) identifiers.push(ident); const first = (identifiers[0] / 40) | 0; const second = identifiers[0] % 40; if (relative) result = identifiers; else result = [first, second].concat(identifiers.slice(1)); if (values) { let tmp = values[result.join(' ')]; if (tmp === undefined) tmp = values[result.join('.')]; if (tmp !== undefined) result = tmp; } return result; }; DERNode.prototype._decodeTime = function decodeTime(buffer, tag) { const str = buffer.raw().toString(); let year; let mon; let day; let hour; let min; let sec; if (tag === 'gentime') { year = str.slice(0, 4) | 0; mon = str.slice(4, 6) | 0; day = str.slice(6, 8) | 0; hour = str.slice(8, 10) | 0; min = str.slice(10, 12) | 0; sec = str.slice(12, 14) | 0; } else if (tag === 'utctime') { year = str.slice(0, 2) | 0; mon = str.slice(2, 4) | 0; day = str.slice(4, 6) | 0; hour = str.slice(6, 8) | 0; min = str.slice(8, 10) | 0; sec = str.slice(10, 12) | 0; if (year < 70) year = 2000 + year; else year = 1900 + year; } else { return buffer.error('Decoding ' + tag + ' time is not supported yet'); } return Date.UTC(year, mon - 1, day, hour, min, sec, 0); }; DERNode.prototype._decodeNull = function decodeNull() { return null; }; DERNode.prototype._decodeBool = function decodeBool(buffer) { const res = buffer.readUInt8(); if (buffer.isError(res)) return res; else return res !== 0; }; DERNode.prototype._decodeInt = function decodeInt(buffer, values) { // Bigint, return as it is (assume big endian) const raw = buffer.raw(); let res = new bignum(raw); if (values) res = values[res.toString(10)] || res; return res; }; DERNode.prototype._use = function use(entity, obj) { if (typeof entity === 'function') entity = entity(obj); return entity._getDecoder('der').tree; }; // Utility methods function derDecodeTag(buf, fail) { let tag = buf.readUInt8(fail); if (buf.isError(tag)) return tag; const cls = der.tagClass[tag >> 6]; const primitive = (tag & 0x20) === 0; // Multi-octet tag - load if ((tag & 0x1f) === 0x1f) { let oct = tag; tag = 0; while ((oct & 0x80) === 0x80) { oct = buf.readUInt8(fail); if (buf.isError(oct)) return oct; tag <<= 7; tag |= oct & 0x7f; } } else { tag &= 0x1f; } const tagStr = der.tag[tag]; return { cls: cls, primitive: primitive, tag: tag, tagStr: tagStr }; } function derDecodeLen(buf, primitive, fail) { let len = buf.readUInt8(fail); if (buf.isError(len)) return len; // Indefinite form if (!primitive && len === 0x80) return null; // Definite form if ((len & 0x80) === 0) { // Short form return len; } // Long form const num = len & 0x7f; if (num > 4) return buf.error('length octect is too long'); len = 0; for (let i = 0; i < num; i++) { len <<= 8; const j = buf.readUInt8(fail); if (buf.isError(j)) return j; len |= j; } return len; } /***/ }), /***/ 94952: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; const decoders = exports; decoders.der = __nccwpck_require__(3332); decoders.pem = __nccwpck_require__(8361); /***/ }), /***/ 8361: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const inherits = __nccwpck_require__(44124); const Buffer = (__nccwpck_require__(15118).Buffer); const DERDecoder = __nccwpck_require__(3332); function PEMDecoder(entity) { DERDecoder.call(this, entity); this.enc = 'pem'; } inherits(PEMDecoder, DERDecoder); module.exports = PEMDecoder; PEMDecoder.prototype.decode = function decode(data, options) { const lines = data.toString().split(/[\r\n]+/g); const label = options.label.toUpperCase(); const re = /^-----(BEGIN|END) ([^-]+)-----$/; let start = -1; let end = -1; for (let i = 0; i < lines.length; i++) { const match = lines[i].match(re); if (match === null) continue; if (match[2] !== label) continue; if (start === -1) { if (match[1] !== 'BEGIN') break; start = i; } else { if (match[1] !== 'END') break; end = i; break; } } if (start === -1 || end === -1) throw new Error('PEM section not found for: ' + label); const base64 = lines.slice(start + 1, end).join(''); // Remove excessive symbols base64.replace(/[^a-z0-9+/=]+/gi, ''); const input = Buffer.from(base64, 'base64'); return DERDecoder.prototype.decode.call(this, input, options); }; /***/ }), /***/ 45769: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const inherits = __nccwpck_require__(44124); const Buffer = (__nccwpck_require__(15118).Buffer); const Node = __nccwpck_require__(80842); // Import DER constants const der = __nccwpck_require__(64293); function DEREncoder(entity) { this.enc = 'der'; this.name = entity.name; this.entity = entity; // Construct base tree this.tree = new DERNode(); this.tree._init(entity.body); } module.exports = DEREncoder; DEREncoder.prototype.encode = function encode(data, reporter) { return this.tree._encode(data, reporter).join(); }; // Tree methods function DERNode(parent) { Node.call(this, 'der', parent); } inherits(DERNode, Node); DERNode.prototype._encodeComposite = function encodeComposite(tag, primitive, cls, content) { const encodedTag = encodeTag(tag, primitive, cls, this.reporter); // Short form if (content.length < 0x80) { const header = Buffer.alloc(2); header[0] = encodedTag; header[1] = content.length; return this._createEncoderBuffer([ header, content ]); } // Long form // Count octets required to store length let lenOctets = 1; for (let i = content.length; i >= 0x100; i >>= 8) lenOctets++; const header = Buffer.alloc(1 + 1 + lenOctets); header[0] = encodedTag; header[1] = 0x80 | lenOctets; for (let i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) header[i] = j & 0xff; return this._createEncoderBuffer([ header, content ]); }; DERNode.prototype._encodeStr = function encodeStr(str, tag) { if (tag === 'bitstr') { return this._createEncoderBuffer([ str.unused | 0, str.data ]); } else if (tag === 'bmpstr') { const buf = Buffer.alloc(str.length * 2); for (let i = 0; i < str.length; i++) { buf.writeUInt16BE(str.charCodeAt(i), i * 2); } return this._createEncoderBuffer(buf); } else if (tag === 'numstr') { if (!this._isNumstr(str)) { return this.reporter.error('Encoding of string type: numstr supports ' + 'only digits and space'); } return this._createEncoderBuffer(str); } else if (tag === 'printstr') { if (!this._isPrintstr(str)) { return this.reporter.error('Encoding of string type: printstr supports ' + 'only latin upper and lower case letters, ' + 'digits, space, apostrophe, left and rigth ' + 'parenthesis, plus sign, comma, hyphen, ' + 'dot, slash, colon, equal sign, ' + 'question mark'); } return this._createEncoderBuffer(str); } else if (/str$/.test(tag)) { return this._createEncoderBuffer(str); } else if (tag === 'objDesc') { return this._createEncoderBuffer(str); } else { return this.reporter.error('Encoding of string type: ' + tag + ' unsupported'); } }; DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { if (typeof id === 'string') { if (!values) return this.reporter.error('string objid given, but no values map found'); if (!values.hasOwnProperty(id)) return this.reporter.error('objid not found in values map'); id = values[id].split(/[\s.]+/g); for (let i = 0; i < id.length; i++) id[i] |= 0; } else if (Array.isArray(id)) { id = id.slice(); for (let i = 0; i < id.length; i++) id[i] |= 0; } if (!Array.isArray(id)) { return this.reporter.error('objid() should be either array or string, ' + 'got: ' + JSON.stringify(id)); } if (!relative) { if (id[1] >= 40) return this.reporter.error('Second objid identifier OOB'); id.splice(0, 2, id[0] * 40 + id[1]); } // Count number of octets let size = 0; for (let i = 0; i < id.length; i++) { let ident = id[i]; for (size++; ident >= 0x80; ident >>= 7) size++; } const objid = Buffer.alloc(size); let offset = objid.length - 1; for (let i = id.length - 1; i >= 0; i--) { let ident = id[i]; objid[offset--] = ident & 0x7f; while ((ident >>= 7) > 0) objid[offset--] = 0x80 | (ident & 0x7f); } return this._createEncoderBuffer(objid); }; function two(num) { if (num < 10) return '0' + num; else return num; } DERNode.prototype._encodeTime = function encodeTime(time, tag) { let str; const date = new Date(time); if (tag === 'gentime') { str = [ two(date.getUTCFullYear()), two(date.getUTCMonth() + 1), two(date.getUTCDate()), two(date.getUTCHours()), two(date.getUTCMinutes()), two(date.getUTCSeconds()), 'Z' ].join(''); } else if (tag === 'utctime') { str = [ two(date.getUTCFullYear() % 100), two(date.getUTCMonth() + 1), two(date.getUTCDate()), two(date.getUTCHours()), two(date.getUTCMinutes()), two(date.getUTCSeconds()), 'Z' ].join(''); } else { this.reporter.error('Encoding ' + tag + ' time is not supported yet'); } return this._encodeStr(str, 'octstr'); }; DERNode.prototype._encodeNull = function encodeNull() { return this._createEncoderBuffer(''); }; DERNode.prototype._encodeInt = function encodeInt(num, values) { if (typeof num === 'string') { if (!values) return this.reporter.error('String int or enum given, but no values map'); if (!values.hasOwnProperty(num)) { return this.reporter.error('Values map doesn\'t contain: ' + JSON.stringify(num)); } num = values[num]; } // Bignum, assume big endian if (typeof num !== 'number' && !Buffer.isBuffer(num)) { const numArray = num.toArray(); if (!num.sign && numArray[0] & 0x80) { numArray.unshift(0); } num = Buffer.from(numArray); } if (Buffer.isBuffer(num)) { let size = num.length; if (num.length === 0) size++; const out = Buffer.alloc(size); num.copy(out); if (num.length === 0) out[0] = 0; return this._createEncoderBuffer(out); } if (num < 0x80) return this._createEncoderBuffer(num); if (num < 0x100) return this._createEncoderBuffer([0, num]); let size = 1; for (let i = num; i >= 0x100; i >>= 8) size++; const out = new Array(size); for (let i = out.length - 1; i >= 0; i--) { out[i] = num & 0xff; num >>= 8; } if(out[0] & 0x80) { out.unshift(0); } return this._createEncoderBuffer(Buffer.from(out)); }; DERNode.prototype._encodeBool = function encodeBool(value) { return this._createEncoderBuffer(value ? 0xff : 0); }; DERNode.prototype._use = function use(entity, obj) { if (typeof entity === 'function') entity = entity(obj); return entity._getEncoder('der').tree; }; DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) { const state = this._baseState; let i; if (state['default'] === null) return false; const data = dataBuffer.join(); if (state.defaultBuffer === undefined) state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join(); if (data.length !== state.defaultBuffer.length) return false; for (i=0; i < data.length; i++) if (data[i] !== state.defaultBuffer[i]) return false; return true; }; // Utility methods function encodeTag(tag, primitive, cls, reporter) { let res; if (tag === 'seqof') tag = 'seq'; else if (tag === 'setof') tag = 'set'; if (der.tagByName.hasOwnProperty(tag)) res = der.tagByName[tag]; else if (typeof tag === 'number' && (tag | 0) === tag) res = tag; else return reporter.error('Unknown tag: ' + tag); if (res >= 0x1f) return reporter.error('Multi-octet tag encoding unsupported'); if (!primitive) res |= 0x20; res |= (der.tagClassByName[cls || 'universal'] << 6); return res; } /***/ }), /***/ 79083: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; const encoders = exports; encoders.der = __nccwpck_require__(45769); encoders.pem = __nccwpck_require__(40279); /***/ }), /***/ 40279: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const inherits = __nccwpck_require__(44124); const DEREncoder = __nccwpck_require__(45769); function PEMEncoder(entity) { DEREncoder.call(this, entity); this.enc = 'pem'; } inherits(PEMEncoder, DEREncoder); module.exports = PEMEncoder; PEMEncoder.prototype.encode = function encode(data, options) { const buf = DEREncoder.prototype.encode.call(this, data); const p = buf.toString('base64'); const out = [ '-----BEGIN ' + options.label + '-----' ]; for (let i = 0; i < p.length; i += 64) out.push(p.slice(i, i + 64)); out.push('-----END ' + options.label + '-----'); return out.join('\n'); }; /***/ }), /***/ 32664: /***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { /* module decorator */ module = __nccwpck_require__.nmd(module); (function (module, exports) { 'use strict'; // Utils function assert (val, msg) { if (!val) throw new Error(msg || 'Assertion failed'); } // Could use `inherits` module, but don't want to move from single file // architecture yet. function inherits (ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; } // BN function BN (number, base, endian) { if (BN.isBN(number)) { return number; } this.negative = 0; this.words = null; this.length = 0; // Reduction context this.red = null; if (number !== null) { if (base === 'le' || base === 'be') { endian = base; base = 10; } this._init(number || 0, base || 10, endian || 'be'); } } if (typeof module === 'object') { module.exports = BN; } else { exports.BN = BN; } BN.BN = BN; BN.wordSize = 26; var Buffer; try { if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { Buffer = window.Buffer; } else { Buffer = (__nccwpck_require__(14300).Buffer); } } catch (e) { } BN.isBN = function isBN (num) { if (num instanceof BN) { return true; } return num !== null && typeof num === 'object' && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); }; BN.max = function max (left, right) { if (left.cmp(right) > 0) return left; return right; }; BN.min = function min (left, right) { if (left.cmp(right) < 0) return left; return right; }; BN.prototype._init = function init (number, base, endian) { if (typeof number === 'number') { return this._initNumber(number, base, endian); } if (typeof number === 'object') { return this._initArray(number, base, endian); } if (base === 'hex') { base = 16; } assert(base === (base | 0) && base >= 2 && base <= 36); number = number.toString().replace(/\s+/g, ''); var start = 0; if (number[0] === '-') { start++; this.negative = 1; } if (start < number.length) { if (base === 16) { this._parseHex(number, start, endian); } else { this._parseBase(number, base, start); if (endian === 'le') { this._initArray(this.toArray(), base, endian); } } } }; BN.prototype._initNumber = function _initNumber (number, base, endian) { if (number < 0) { this.negative = 1; number = -number; } if (number < 0x4000000) { this.words = [ number & 0x3ffffff ]; this.length = 1; } else if (number < 0x10000000000000) { this.words = [ number & 0x3ffffff, (number / 0x4000000) & 0x3ffffff ]; this.length = 2; } else { assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) this.words = [ number & 0x3ffffff, (number / 0x4000000) & 0x3ffffff, 1 ]; this.length = 3; } if (endian !== 'le') return; // Reverse the bytes this._initArray(this.toArray(), base, endian); }; BN.prototype._initArray = function _initArray (number, base, endian) { // Perhaps a Uint8Array assert(typeof number.length === 'number'); if (number.length <= 0) { this.words = [ 0 ]; this.length = 1; return this; } this.length = Math.ceil(number.length / 3); this.words = new Array(this.length); for (var i = 0; i < this.length; i++) { this.words[i] = 0; } var j, w; var off = 0; if (endian === 'be') { for (i = number.length - 1, j = 0; i >= 0; i -= 3) { w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; off += 24; if (off >= 26) { off -= 26; j++; } } } else if (endian === 'le') { for (i = 0, j = 0; i < number.length; i += 3) { w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; off += 24; if (off >= 26) { off -= 26; j++; } } } return this.strip(); }; function parseHex4Bits (string, index) { var c = string.charCodeAt(index); // 'A' - 'F' if (c >= 65 && c <= 70) { return c - 55; // 'a' - 'f' } else if (c >= 97 && c <= 102) { return c - 87; // '0' - '9' } else { return (c - 48) & 0xf; } } function parseHexByte (string, lowerBound, index) { var r = parseHex4Bits(string, index); if (index - 1 >= lowerBound) { r |= parseHex4Bits(string, index - 1) << 4; } return r; } BN.prototype._parseHex = function _parseHex (number, start, endian) { // Create possibly bigger array to ensure that it fits the number this.length = Math.ceil((number.length - start) / 6); this.words = new Array(this.length); for (var i = 0; i < this.length; i++) { this.words[i] = 0; } // 24-bits chunks var off = 0; var j = 0; var w; if (endian === 'be') { for (i = number.length - 1; i >= start; i -= 2) { w = parseHexByte(number, start, i) << off; this.words[j] |= w & 0x3ffffff; if (off >= 18) { off -= 18; j += 1; this.words[j] |= w >>> 26; } else { off += 8; } } } else { var parseLength = number.length - start; for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { w = parseHexByte(number, start, i) << off; this.words[j] |= w & 0x3ffffff; if (off >= 18) { off -= 18; j += 1; this.words[j] |= w >>> 26; } else { off += 8; } } } this.strip(); }; function parseBase (str, start, end, mul) { var r = 0; var len = Math.min(str.length, end); for (var i = start; i < len; i++) { var c = str.charCodeAt(i) - 48; r *= mul; // 'a' if (c >= 49) { r += c - 49 + 0xa; // 'A' } else if (c >= 17) { r += c - 17 + 0xa; // '0' - '9' } else { r += c; } } return r; } BN.prototype._parseBase = function _parseBase (number, base, start) { // Initialize as zero this.words = [ 0 ]; this.length = 1; // Find length of limb in base for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { limbLen++; } limbLen--; limbPow = (limbPow / base) | 0; var total = number.length - start; var mod = total % limbLen; var end = Math.min(total, total - mod) + start; var word = 0; for (var i = start; i < end; i += limbLen) { word = parseBase(number, i, i + limbLen, base); this.imuln(limbPow); if (this.words[0] + word < 0x4000000) { this.words[0] += word; } else { this._iaddn(word); } } if (mod !== 0) { var pow = 1; word = parseBase(number, i, number.length, base); for (i = 0; i < mod; i++) { pow *= base; } this.imuln(pow); if (this.words[0] + word < 0x4000000) { this.words[0] += word; } else { this._iaddn(word); } } this.strip(); }; BN.prototype.copy = function copy (dest) { dest.words = new Array(this.length); for (var i = 0; i < this.length; i++) { dest.words[i] = this.words[i]; } dest.length = this.length; dest.negative = this.negative; dest.red = this.red; }; BN.prototype.clone = function clone () { var r = new BN(null); this.copy(r); return r; }; BN.prototype._expand = function _expand (size) { while (this.length < size) { this.words[this.length++] = 0; } return this; }; // Remove leading `0` from `this` BN.prototype.strip = function strip () { while (this.length > 1 && this.words[this.length - 1] === 0) { this.length--; } return this._normSign(); }; BN.prototype._normSign = function _normSign () { // -0 = 0 if (this.length === 1 && this.words[0] === 0) { this.negative = 0; } return this; }; BN.prototype.inspect = function inspect () { return (this.red ? ''; }; /* var zeros = []; var groupSizes = []; var groupBases = []; var s = ''; var i = -1; while (++i < BN.wordSize) { zeros[i] = s; s += '0'; } groupSizes[0] = 0; groupSizes[1] = 0; groupBases[0] = 0; groupBases[1] = 0; var base = 2 - 1; while (++base < 36 + 1) { var groupSize = 0; var groupBase = 1; while (groupBase < (1 << BN.wordSize) / base) { groupBase *= base; groupSize += 1; } groupSizes[base] = groupSize; groupBases[base] = groupBase; } */ var zeros = [ '', '0', '00', '000', '0000', '00000', '000000', '0000000', '00000000', '000000000', '0000000000', '00000000000', '000000000000', '0000000000000', '00000000000000', '000000000000000', '0000000000000000', '00000000000000000', '000000000000000000', '0000000000000000000', '00000000000000000000', '000000000000000000000', '0000000000000000000000', '00000000000000000000000', '000000000000000000000000', '0000000000000000000000000' ]; var groupSizes = [ 0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 ]; var groupBases = [ 0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 ]; BN.prototype.toString = function toString (base, padding) { base = base || 10; padding = padding | 0 || 1; var out; if (base === 16 || base === 'hex') { out = ''; var off = 0; var carry = 0; for (var i = 0; i < this.length; i++) { var w = this.words[i]; var word = (((w << off) | carry) & 0xffffff).toString(16); carry = (w >>> (24 - off)) & 0xffffff; if (carry !== 0 || i !== this.length - 1) { out = zeros[6 - word.length] + word + out; } else { out = word + out; } off += 2; if (off >= 26) { off -= 26; i--; } } if (carry !== 0) { out = carry.toString(16) + out; } while (out.length % padding !== 0) { out = '0' + out; } if (this.negative !== 0) { out = '-' + out; } return out; } if (base === (base | 0) && base >= 2 && base <= 36) { // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); var groupSize = groupSizes[base]; // var groupBase = Math.pow(base, groupSize); var groupBase = groupBases[base]; out = ''; var c = this.clone(); c.negative = 0; while (!c.isZero()) { var r = c.modn(groupBase).toString(base); c = c.idivn(groupBase); if (!c.isZero()) { out = zeros[groupSize - r.length] + r + out; } else { out = r + out; } } if (this.isZero()) { out = '0' + out; } while (out.length % padding !== 0) { out = '0' + out; } if (this.negative !== 0) { out = '-' + out; } return out; } assert(false, 'Base should be between 2 and 36'); }; BN.prototype.toNumber = function toNumber () { var ret = this.words[0]; if (this.length === 2) { ret += this.words[1] * 0x4000000; } else if (this.length === 3 && this.words[2] === 0x01) { // NOTE: at this stage it is known that the top bit is set ret += 0x10000000000000 + (this.words[1] * 0x4000000); } else if (this.length > 2) { assert(false, 'Number can only safely store up to 53 bits'); } return (this.negative !== 0) ? -ret : ret; }; BN.prototype.toJSON = function toJSON () { return this.toString(16); }; BN.prototype.toBuffer = function toBuffer (endian, length) { assert(typeof Buffer !== 'undefined'); return this.toArrayLike(Buffer, endian, length); }; BN.prototype.toArray = function toArray (endian, length) { return this.toArrayLike(Array, endian, length); }; BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { var byteLength = this.byteLength(); var reqLength = length || Math.max(1, byteLength); assert(byteLength <= reqLength, 'byte array longer than desired length'); assert(reqLength > 0, 'Requested array length <= 0'); this.strip(); var littleEndian = endian === 'le'; var res = new ArrayType(reqLength); var b, i; var q = this.clone(); if (!littleEndian) { // Assume big-endian for (i = 0; i < reqLength - byteLength; i++) { res[i] = 0; } for (i = 0; !q.isZero(); i++) { b = q.andln(0xff); q.iushrn(8); res[reqLength - i - 1] = b; } } else { for (i = 0; !q.isZero(); i++) { b = q.andln(0xff); q.iushrn(8); res[i] = b; } for (; i < reqLength; i++) { res[i] = 0; } } return res; }; if (Math.clz32) { BN.prototype._countBits = function _countBits (w) { return 32 - Math.clz32(w); }; } else { BN.prototype._countBits = function _countBits (w) { var t = w; var r = 0; if (t >= 0x1000) { r += 13; t >>>= 13; } if (t >= 0x40) { r += 7; t >>>= 7; } if (t >= 0x8) { r += 4; t >>>= 4; } if (t >= 0x02) { r += 2; t >>>= 2; } return r + t; }; } BN.prototype._zeroBits = function _zeroBits (w) { // Short-cut if (w === 0) return 26; var t = w; var r = 0; if ((t & 0x1fff) === 0) { r += 13; t >>>= 13; } if ((t & 0x7f) === 0) { r += 7; t >>>= 7; } if ((t & 0xf) === 0) { r += 4; t >>>= 4; } if ((t & 0x3) === 0) { r += 2; t >>>= 2; } if ((t & 0x1) === 0) { r++; } return r; }; // Return number of used bits in a BN BN.prototype.bitLength = function bitLength () { var w = this.words[this.length - 1]; var hi = this._countBits(w); return (this.length - 1) * 26 + hi; }; function toBitArray (num) { var w = new Array(num.bitLength()); for (var bit = 0; bit < w.length; bit++) { var off = (bit / 26) | 0; var wbit = bit % 26; w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; } return w; } // Number of trailing zero bits BN.prototype.zeroBits = function zeroBits () { if (this.isZero()) return 0; var r = 0; for (var i = 0; i < this.length; i++) { var b = this._zeroBits(this.words[i]); r += b; if (b !== 26) break; } return r; }; BN.prototype.byteLength = function byteLength () { return Math.ceil(this.bitLength() / 8); }; BN.prototype.toTwos = function toTwos (width) { if (this.negative !== 0) { return this.abs().inotn(width).iaddn(1); } return this.clone(); }; BN.prototype.fromTwos = function fromTwos (width) { if (this.testn(width - 1)) { return this.notn(width).iaddn(1).ineg(); } return this.clone(); }; BN.prototype.isNeg = function isNeg () { return this.negative !== 0; }; // Return negative clone of `this` BN.prototype.neg = function neg () { return this.clone().ineg(); }; BN.prototype.ineg = function ineg () { if (!this.isZero()) { this.negative ^= 1; } return this; }; // Or `num` with `this` in-place BN.prototype.iuor = function iuor (num) { while (this.length < num.length) { this.words[this.length++] = 0; } for (var i = 0; i < num.length; i++) { this.words[i] = this.words[i] | num.words[i]; } return this.strip(); }; BN.prototype.ior = function ior (num) { assert((this.negative | num.negative) === 0); return this.iuor(num); }; // Or `num` with `this` BN.prototype.or = function or (num) { if (this.length > num.length) return this.clone().ior(num); return num.clone().ior(this); }; BN.prototype.uor = function uor (num) { if (this.length > num.length) return this.clone().iuor(num); return num.clone().iuor(this); }; // And `num` with `this` in-place BN.prototype.iuand = function iuand (num) { // b = min-length(num, this) var b; if (this.length > num.length) { b = num; } else { b = this; } for (var i = 0; i < b.length; i++) { this.words[i] = this.words[i] & num.words[i]; } this.length = b.length; return this.strip(); }; BN.prototype.iand = function iand (num) { assert((this.negative | num.negative) === 0); return this.iuand(num); }; // And `num` with `this` BN.prototype.and = function and (num) { if (this.length > num.length) return this.clone().iand(num); return num.clone().iand(this); }; BN.prototype.uand = function uand (num) { if (this.length > num.length) return this.clone().iuand(num); return num.clone().iuand(this); }; // Xor `num` with `this` in-place BN.prototype.iuxor = function iuxor (num) { // a.length > b.length var a; var b; if (this.length > num.length) { a = this; b = num; } else { a = num; b = this; } for (var i = 0; i < b.length; i++) { this.words[i] = a.words[i] ^ b.words[i]; } if (this !== a) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } this.length = a.length; return this.strip(); }; BN.prototype.ixor = function ixor (num) { assert((this.negative | num.negative) === 0); return this.iuxor(num); }; // Xor `num` with `this` BN.prototype.xor = function xor (num) { if (this.length > num.length) return this.clone().ixor(num); return num.clone().ixor(this); }; BN.prototype.uxor = function uxor (num) { if (this.length > num.length) return this.clone().iuxor(num); return num.clone().iuxor(this); }; // Not ``this`` with ``width`` bitwidth BN.prototype.inotn = function inotn (width) { assert(typeof width === 'number' && width >= 0); var bytesNeeded = Math.ceil(width / 26) | 0; var bitsLeft = width % 26; // Extend the buffer with leading zeroes this._expand(bytesNeeded); if (bitsLeft > 0) { bytesNeeded--; } // Handle complete words for (var i = 0; i < bytesNeeded; i++) { this.words[i] = ~this.words[i] & 0x3ffffff; } // Handle the residue if (bitsLeft > 0) { this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); } // And remove leading zeroes return this.strip(); }; BN.prototype.notn = function notn (width) { return this.clone().inotn(width); }; // Set `bit` of `this` BN.prototype.setn = function setn (bit, val) { assert(typeof bit === 'number' && bit >= 0); var off = (bit / 26) | 0; var wbit = bit % 26; this._expand(off + 1); if (val) { this.words[off] = this.words[off] | (1 << wbit); } else { this.words[off] = this.words[off] & ~(1 << wbit); } return this.strip(); }; // Add `num` to `this` in-place BN.prototype.iadd = function iadd (num) { var r; // negative + positive if (this.negative !== 0 && num.negative === 0) { this.negative = 0; r = this.isub(num); this.negative ^= 1; return this._normSign(); // positive + negative } else if (this.negative === 0 && num.negative !== 0) { num.negative = 0; r = this.isub(num); num.negative = 1; return r._normSign(); } // a.length > b.length var a, b; if (this.length > num.length) { a = this; b = num; } else { a = num; b = this; } var carry = 0; for (var i = 0; i < b.length; i++) { r = (a.words[i] | 0) + (b.words[i] | 0) + carry; this.words[i] = r & 0x3ffffff; carry = r >>> 26; } for (; carry !== 0 && i < a.length; i++) { r = (a.words[i] | 0) + carry; this.words[i] = r & 0x3ffffff; carry = r >>> 26; } this.length = a.length; if (carry !== 0) { this.words[this.length] = carry; this.length++; // Copy the rest of the words } else if (a !== this) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } return this; }; // Add `num` to `this` BN.prototype.add = function add (num) { var res; if (num.negative !== 0 && this.negative === 0) { num.negative = 0; res = this.sub(num); num.negative ^= 1; return res; } else if (num.negative === 0 && this.negative !== 0) { this.negative = 0; res = num.sub(this); this.negative = 1; return res; } if (this.length > num.length) return this.clone().iadd(num); return num.clone().iadd(this); }; // Subtract `num` from `this` in-place BN.prototype.isub = function isub (num) { // this - (-num) = this + num if (num.negative !== 0) { num.negative = 0; var r = this.iadd(num); num.negative = 1; return r._normSign(); // -this - num = -(this + num) } else if (this.negative !== 0) { this.negative = 0; this.iadd(num); this.negative = 1; return this._normSign(); } // At this point both numbers are positive var cmp = this.cmp(num); // Optimization - zeroify if (cmp === 0) { this.negative = 0; this.length = 1; this.words[0] = 0; return this; } // a > b var a, b; if (cmp > 0) { a = this; b = num; } else { a = num; b = this; } var carry = 0; for (var i = 0; i < b.length; i++) { r = (a.words[i] | 0) - (b.words[i] | 0) + carry; carry = r >> 26; this.words[i] = r & 0x3ffffff; } for (; carry !== 0 && i < a.length; i++) { r = (a.words[i] | 0) + carry; carry = r >> 26; this.words[i] = r & 0x3ffffff; } // Copy rest of the words if (carry === 0 && i < a.length && a !== this) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } this.length = Math.max(this.length, i); if (a !== this) { this.negative = 1; } return this.strip(); }; // Subtract `num` from `this` BN.prototype.sub = function sub (num) { return this.clone().isub(num); }; function smallMulTo (self, num, out) { out.negative = num.negative ^ self.negative; var len = (self.length + num.length) | 0; out.length = len; len = (len - 1) | 0; // Peel one iteration (compiler can't do it, because of code complexity) var a = self.words[0] | 0; var b = num.words[0] | 0; var r = a * b; var lo = r & 0x3ffffff; var carry = (r / 0x4000000) | 0; out.words[0] = lo; for (var k = 1; k < len; k++) { // Sum all words with the same `i + j = k` and accumulate `ncarry`, // note that ncarry could be >= 0x3ffffff var ncarry = carry >>> 26; var rword = carry & 0x3ffffff; var maxJ = Math.min(k, num.length - 1); for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { var i = (k - j) | 0; a = self.words[i] | 0; b = num.words[j] | 0; r = a * b + rword; ncarry += (r / 0x4000000) | 0; rword = r & 0x3ffffff; } out.words[k] = rword | 0; carry = ncarry | 0; } if (carry !== 0) { out.words[k] = carry | 0; } else { out.length--; } return out.strip(); } // TODO(indutny): it may be reasonable to omit it for users who don't need // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit // multiplication (like elliptic secp256k1). var comb10MulTo = function comb10MulTo (self, num, out) { var a = self.words; var b = num.words; var o = out.words; var c = 0; var lo; var mid; var hi; var a0 = a[0] | 0; var al0 = a0 & 0x1fff; var ah0 = a0 >>> 13; var a1 = a[1] | 0; var al1 = a1 & 0x1fff; var ah1 = a1 >>> 13; var a2 = a[2] | 0; var al2 = a2 & 0x1fff; var ah2 = a2 >>> 13; var a3 = a[3] | 0; var al3 = a3 & 0x1fff; var ah3 = a3 >>> 13; var a4 = a[4] | 0; var al4 = a4 & 0x1fff; var ah4 = a4 >>> 13; var a5 = a[5] | 0; var al5 = a5 & 0x1fff; var ah5 = a5 >>> 13; var a6 = a[6] | 0; var al6 = a6 & 0x1fff; var ah6 = a6 >>> 13; var a7 = a[7] | 0; var al7 = a7 & 0x1fff; var ah7 = a7 >>> 13; var a8 = a[8] | 0; var al8 = a8 & 0x1fff; var ah8 = a8 >>> 13; var a9 = a[9] | 0; var al9 = a9 & 0x1fff; var ah9 = a9 >>> 13; var b0 = b[0] | 0; var bl0 = b0 & 0x1fff; var bh0 = b0 >>> 13; var b1 = b[1] | 0; var bl1 = b1 & 0x1fff; var bh1 = b1 >>> 13; var b2 = b[2] | 0; var bl2 = b2 & 0x1fff; var bh2 = b2 >>> 13; var b3 = b[3] | 0; var bl3 = b3 & 0x1fff; var bh3 = b3 >>> 13; var b4 = b[4] | 0; var bl4 = b4 & 0x1fff; var bh4 = b4 >>> 13; var b5 = b[5] | 0; var bl5 = b5 & 0x1fff; var bh5 = b5 >>> 13; var b6 = b[6] | 0; var bl6 = b6 & 0x1fff; var bh6 = b6 >>> 13; var b7 = b[7] | 0; var bl7 = b7 & 0x1fff; var bh7 = b7 >>> 13; var b8 = b[8] | 0; var bl8 = b8 & 0x1fff; var bh8 = b8 >>> 13; var b9 = b[9] | 0; var bl9 = b9 & 0x1fff; var bh9 = b9 >>> 13; out.negative = self.negative ^ num.negative; out.length = 19; /* k = 0 */ lo = Math.imul(al0, bl0); mid = Math.imul(al0, bh0); mid = (mid + Math.imul(ah0, bl0)) | 0; hi = Math.imul(ah0, bh0); var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; w0 &= 0x3ffffff; /* k = 1 */ lo = Math.imul(al1, bl0); mid = Math.imul(al1, bh0); mid = (mid + Math.imul(ah1, bl0)) | 0; hi = Math.imul(ah1, bh0); lo = (lo + Math.imul(al0, bl1)) | 0; mid = (mid + Math.imul(al0, bh1)) | 0; mid = (mid + Math.imul(ah0, bl1)) | 0; hi = (hi + Math.imul(ah0, bh1)) | 0; var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; w1 &= 0x3ffffff; /* k = 2 */ lo = Math.imul(al2, bl0); mid = Math.imul(al2, bh0); mid = (mid + Math.imul(ah2, bl0)) | 0; hi = Math.imul(ah2, bh0); lo = (lo + Math.imul(al1, bl1)) | 0; mid = (mid + Math.imul(al1, bh1)) | 0; mid = (mid + Math.imul(ah1, bl1)) | 0; hi = (hi + Math.imul(ah1, bh1)) | 0; lo = (lo + Math.imul(al0, bl2)) | 0; mid = (mid + Math.imul(al0, bh2)) | 0; mid = (mid + Math.imul(ah0, bl2)) | 0; hi = (hi + Math.imul(ah0, bh2)) | 0; var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; w2 &= 0x3ffffff; /* k = 3 */ lo = Math.imul(al3, bl0); mid = Math.imul(al3, bh0); mid = (mid + Math.imul(ah3, bl0)) | 0; hi = Math.imul(ah3, bh0); lo = (lo + Math.imul(al2, bl1)) | 0; mid = (mid + Math.imul(al2, bh1)) | 0; mid = (mid + Math.imul(ah2, bl1)) | 0; hi = (hi + Math.imul(ah2, bh1)) | 0; lo = (lo + Math.imul(al1, bl2)) | 0; mid = (mid + Math.imul(al1, bh2)) | 0; mid = (mid + Math.imul(ah1, bl2)) | 0; hi = (hi + Math.imul(ah1, bh2)) | 0; lo = (lo + Math.imul(al0, bl3)) | 0; mid = (mid + Math.imul(al0, bh3)) | 0; mid = (mid + Math.imul(ah0, bl3)) | 0; hi = (hi + Math.imul(ah0, bh3)) | 0; var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; w3 &= 0x3ffffff; /* k = 4 */ lo = Math.imul(al4, bl0); mid = Math.imul(al4, bh0); mid = (mid + Math.imul(ah4, bl0)) | 0; hi = Math.imul(ah4, bh0); lo = (lo + Math.imul(al3, bl1)) | 0; mid = (mid + Math.imul(al3, bh1)) | 0; mid = (mid + Math.imul(ah3, bl1)) | 0; hi = (hi + Math.imul(ah3, bh1)) | 0; lo = (lo + Math.imul(al2, bl2)) | 0; mid = (mid + Math.imul(al2, bh2)) | 0; mid = (mid + Math.imul(ah2, bl2)) | 0; hi = (hi + Math.imul(ah2, bh2)) | 0; lo = (lo + Math.imul(al1, bl3)) | 0; mid = (mid + Math.imul(al1, bh3)) | 0; mid = (mid + Math.imul(ah1, bl3)) | 0; hi = (hi + Math.imul(ah1, bh3)) | 0; lo = (lo + Math.imul(al0, bl4)) | 0; mid = (mid + Math.imul(al0, bh4)) | 0; mid = (mid + Math.imul(ah0, bl4)) | 0; hi = (hi + Math.imul(ah0, bh4)) | 0; var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; w4 &= 0x3ffffff; /* k = 5 */ lo = Math.imul(al5, bl0); mid = Math.imul(al5, bh0); mid = (mid + Math.imul(ah5, bl0)) | 0; hi = Math.imul(ah5, bh0); lo = (lo + Math.imul(al4, bl1)) | 0; mid = (mid + Math.imul(al4, bh1)) | 0; mid = (mid + Math.imul(ah4, bl1)) | 0; hi = (hi + Math.imul(ah4, bh1)) | 0; lo = (lo + Math.imul(al3, bl2)) | 0; mid = (mid + Math.imul(al3, bh2)) | 0; mid = (mid + Math.imul(ah3, bl2)) | 0; hi = (hi + Math.imul(ah3, bh2)) | 0; lo = (lo + Math.imul(al2, bl3)) | 0; mid = (mid + Math.imul(al2, bh3)) | 0; mid = (mid + Math.imul(ah2, bl3)) | 0; hi = (hi + Math.imul(ah2, bh3)) | 0; lo = (lo + Math.imul(al1, bl4)) | 0; mid = (mid + Math.imul(al1, bh4)) | 0; mid = (mid + Math.imul(ah1, bl4)) | 0; hi = (hi + Math.imul(ah1, bh4)) | 0; lo = (lo + Math.imul(al0, bl5)) | 0; mid = (mid + Math.imul(al0, bh5)) | 0; mid = (mid + Math.imul(ah0, bl5)) | 0; hi = (hi + Math.imul(ah0, bh5)) | 0; var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; w5 &= 0x3ffffff; /* k = 6 */ lo = Math.imul(al6, bl0); mid = Math.imul(al6, bh0); mid = (mid + Math.imul(ah6, bl0)) | 0; hi = Math.imul(ah6, bh0); lo = (lo + Math.imul(al5, bl1)) | 0; mid = (mid + Math.imul(al5, bh1)) | 0; mid = (mid + Math.imul(ah5, bl1)) | 0; hi = (hi + Math.imul(ah5, bh1)) | 0; lo = (lo + Math.imul(al4, bl2)) | 0; mid = (mid + Math.imul(al4, bh2)) | 0; mid = (mid + Math.imul(ah4, bl2)) | 0; hi = (hi + Math.imul(ah4, bh2)) | 0; lo = (lo + Math.imul(al3, bl3)) | 0; mid = (mid + Math.imul(al3, bh3)) | 0; mid = (mid + Math.imul(ah3, bl3)) | 0; hi = (hi + Math.imul(ah3, bh3)) | 0; lo = (lo + Math.imul(al2, bl4)) | 0; mid = (mid + Math.imul(al2, bh4)) | 0; mid = (mid + Math.imul(ah2, bl4)) | 0; hi = (hi + Math.imul(ah2, bh4)) | 0; lo = (lo + Math.imul(al1, bl5)) | 0; mid = (mid + Math.imul(al1, bh5)) | 0; mid = (mid + Math.imul(ah1, bl5)) | 0; hi = (hi + Math.imul(ah1, bh5)) | 0; lo = (lo + Math.imul(al0, bl6)) | 0; mid = (mid + Math.imul(al0, bh6)) | 0; mid = (mid + Math.imul(ah0, bl6)) | 0; hi = (hi + Math.imul(ah0, bh6)) | 0; var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; w6 &= 0x3ffffff; /* k = 7 */ lo = Math.imul(al7, bl0); mid = Math.imul(al7, bh0); mid = (mid + Math.imul(ah7, bl0)) | 0; hi = Math.imul(ah7, bh0); lo = (lo + Math.imul(al6, bl1)) | 0; mid = (mid + Math.imul(al6, bh1)) | 0; mid = (mid + Math.imul(ah6, bl1)) | 0; hi = (hi + Math.imul(ah6, bh1)) | 0; lo = (lo + Math.imul(al5, bl2)) | 0; mid = (mid + Math.imul(al5, bh2)) | 0; mid = (mid + Math.imul(ah5, bl2)) | 0; hi = (hi + Math.imul(ah5, bh2)) | 0; lo = (lo + Math.imul(al4, bl3)) | 0; mid = (mid + Math.imul(al4, bh3)) | 0; mid = (mid + Math.imul(ah4, bl3)) | 0; hi = (hi + Math.imul(ah4, bh3)) | 0; lo = (lo + Math.imul(al3, bl4)) | 0; mid = (mid + Math.imul(al3, bh4)) | 0; mid = (mid + Math.imul(ah3, bl4)) | 0; hi = (hi + Math.imul(ah3, bh4)) | 0; lo = (lo + Math.imul(al2, bl5)) | 0; mid = (mid + Math.imul(al2, bh5)) | 0; mid = (mid + Math.imul(ah2, bl5)) | 0; hi = (hi + Math.imul(ah2, bh5)) | 0; lo = (lo + Math.imul(al1, bl6)) | 0; mid = (mid + Math.imul(al1, bh6)) | 0; mid = (mid + Math.imul(ah1, bl6)) | 0; hi = (hi + Math.imul(ah1, bh6)) | 0; lo = (lo + Math.imul(al0, bl7)) | 0; mid = (mid + Math.imul(al0, bh7)) | 0; mid = (mid + Math.imul(ah0, bl7)) | 0; hi = (hi + Math.imul(ah0, bh7)) | 0; var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; w7 &= 0x3ffffff; /* k = 8 */ lo = Math.imul(al8, bl0); mid = Math.imul(al8, bh0); mid = (mid + Math.imul(ah8, bl0)) | 0; hi = Math.imul(ah8, bh0); lo = (lo + Math.imul(al7, bl1)) | 0; mid = (mid + Math.imul(al7, bh1)) | 0; mid = (mid + Math.imul(ah7, bl1)) | 0; hi = (hi + Math.imul(ah7, bh1)) | 0; lo = (lo + Math.imul(al6, bl2)) | 0; mid = (mid + Math.imul(al6, bh2)) | 0; mid = (mid + Math.imul(ah6, bl2)) | 0; hi = (hi + Math.imul(ah6, bh2)) | 0; lo = (lo + Math.imul(al5, bl3)) | 0; mid = (mid + Math.imul(al5, bh3)) | 0; mid = (mid + Math.imul(ah5, bl3)) | 0; hi = (hi + Math.imul(ah5, bh3)) | 0; lo = (lo + Math.imul(al4, bl4)) | 0; mid = (mid + Math.imul(al4, bh4)) | 0; mid = (mid + Math.imul(ah4, bl4)) | 0; hi = (hi + Math.imul(ah4, bh4)) | 0; lo = (lo + Math.imul(al3, bl5)) | 0; mid = (mid + Math.imul(al3, bh5)) | 0; mid = (mid + Math.imul(ah3, bl5)) | 0; hi = (hi + Math.imul(ah3, bh5)) | 0; lo = (lo + Math.imul(al2, bl6)) | 0; mid = (mid + Math.imul(al2, bh6)) | 0; mid = (mid + Math.imul(ah2, bl6)) | 0; hi = (hi + Math.imul(ah2, bh6)) | 0; lo = (lo + Math.imul(al1, bl7)) | 0; mid = (mid + Math.imul(al1, bh7)) | 0; mid = (mid + Math.imul(ah1, bl7)) | 0; hi = (hi + Math.imul(ah1, bh7)) | 0; lo = (lo + Math.imul(al0, bl8)) | 0; mid = (mid + Math.imul(al0, bh8)) | 0; mid = (mid + Math.imul(ah0, bl8)) | 0; hi = (hi + Math.imul(ah0, bh8)) | 0; var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; w8 &= 0x3ffffff; /* k = 9 */ lo = Math.imul(al9, bl0); mid = Math.imul(al9, bh0); mid = (mid + Math.imul(ah9, bl0)) | 0; hi = Math.imul(ah9, bh0); lo = (lo + Math.imul(al8, bl1)) | 0; mid = (mid + Math.imul(al8, bh1)) | 0; mid = (mid + Math.imul(ah8, bl1)) | 0; hi = (hi + Math.imul(ah8, bh1)) | 0; lo = (lo + Math.imul(al7, bl2)) | 0; mid = (mid + Math.imul(al7, bh2)) | 0; mid = (mid + Math.imul(ah7, bl2)) | 0; hi = (hi + Math.imul(ah7, bh2)) | 0; lo = (lo + Math.imul(al6, bl3)) | 0; mid = (mid + Math.imul(al6, bh3)) | 0; mid = (mid + Math.imul(ah6, bl3)) | 0; hi = (hi + Math.imul(ah6, bh3)) | 0; lo = (lo + Math.imul(al5, bl4)) | 0; mid = (mid + Math.imul(al5, bh4)) | 0; mid = (mid + Math.imul(ah5, bl4)) | 0; hi = (hi + Math.imul(ah5, bh4)) | 0; lo = (lo + Math.imul(al4, bl5)) | 0; mid = (mid + Math.imul(al4, bh5)) | 0; mid = (mid + Math.imul(ah4, bl5)) | 0; hi = (hi + Math.imul(ah4, bh5)) | 0; lo = (lo + Math.imul(al3, bl6)) | 0; mid = (mid + Math.imul(al3, bh6)) | 0; mid = (mid + Math.imul(ah3, bl6)) | 0; hi = (hi + Math.imul(ah3, bh6)) | 0; lo = (lo + Math.imul(al2, bl7)) | 0; mid = (mid + Math.imul(al2, bh7)) | 0; mid = (mid + Math.imul(ah2, bl7)) | 0; hi = (hi + Math.imul(ah2, bh7)) | 0; lo = (lo + Math.imul(al1, bl8)) | 0; mid = (mid + Math.imul(al1, bh8)) | 0; mid = (mid + Math.imul(ah1, bl8)) | 0; hi = (hi + Math.imul(ah1, bh8)) | 0; lo = (lo + Math.imul(al0, bl9)) | 0; mid = (mid + Math.imul(al0, bh9)) | 0; mid = (mid + Math.imul(ah0, bl9)) | 0; hi = (hi + Math.imul(ah0, bh9)) | 0; var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; w9 &= 0x3ffffff; /* k = 10 */ lo = Math.imul(al9, bl1); mid = Math.imul(al9, bh1); mid = (mid + Math.imul(ah9, bl1)) | 0; hi = Math.imul(ah9, bh1); lo = (lo + Math.imul(al8, bl2)) | 0; mid = (mid + Math.imul(al8, bh2)) | 0; mid = (mid + Math.imul(ah8, bl2)) | 0; hi = (hi + Math.imul(ah8, bh2)) | 0; lo = (lo + Math.imul(al7, bl3)) | 0; mid = (mid + Math.imul(al7, bh3)) | 0; mid = (mid + Math.imul(ah7, bl3)) | 0; hi = (hi + Math.imul(ah7, bh3)) | 0; lo = (lo + Math.imul(al6, bl4)) | 0; mid = (mid + Math.imul(al6, bh4)) | 0; mid = (mid + Math.imul(ah6, bl4)) | 0; hi = (hi + Math.imul(ah6, bh4)) | 0; lo = (lo + Math.imul(al5, bl5)) | 0; mid = (mid + Math.imul(al5, bh5)) | 0; mid = (mid + Math.imul(ah5, bl5)) | 0; hi = (hi + Math.imul(ah5, bh5)) | 0; lo = (lo + Math.imul(al4, bl6)) | 0; mid = (mid + Math.imul(al4, bh6)) | 0; mid = (mid + Math.imul(ah4, bl6)) | 0; hi = (hi + Math.imul(ah4, bh6)) | 0; lo = (lo + Math.imul(al3, bl7)) | 0; mid = (mid + Math.imul(al3, bh7)) | 0; mid = (mid + Math.imul(ah3, bl7)) | 0; hi = (hi + Math.imul(ah3, bh7)) | 0; lo = (lo + Math.imul(al2, bl8)) | 0; mid = (mid + Math.imul(al2, bh8)) | 0; mid = (mid + Math.imul(ah2, bl8)) | 0; hi = (hi + Math.imul(ah2, bh8)) | 0; lo = (lo + Math.imul(al1, bl9)) | 0; mid = (mid + Math.imul(al1, bh9)) | 0; mid = (mid + Math.imul(ah1, bl9)) | 0; hi = (hi + Math.imul(ah1, bh9)) | 0; var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; w10 &= 0x3ffffff; /* k = 11 */ lo = Math.imul(al9, bl2); mid = Math.imul(al9, bh2); mid = (mid + Math.imul(ah9, bl2)) | 0; hi = Math.imul(ah9, bh2); lo = (lo + Math.imul(al8, bl3)) | 0; mid = (mid + Math.imul(al8, bh3)) | 0; mid = (mid + Math.imul(ah8, bl3)) | 0; hi = (hi + Math.imul(ah8, bh3)) | 0; lo = (lo + Math.imul(al7, bl4)) | 0; mid = (mid + Math.imul(al7, bh4)) | 0; mid = (mid + Math.imul(ah7, bl4)) | 0; hi = (hi + Math.imul(ah7, bh4)) | 0; lo = (lo + Math.imul(al6, bl5)) | 0; mid = (mid + Math.imul(al6, bh5)) | 0; mid = (mid + Math.imul(ah6, bl5)) | 0; hi = (hi + Math.imul(ah6, bh5)) | 0; lo = (lo + Math.imul(al5, bl6)) | 0; mid = (mid + Math.imul(al5, bh6)) | 0; mid = (mid + Math.imul(ah5, bl6)) | 0; hi = (hi + Math.imul(ah5, bh6)) | 0; lo = (lo + Math.imul(al4, bl7)) | 0; mid = (mid + Math.imul(al4, bh7)) | 0; mid = (mid + Math.imul(ah4, bl7)) | 0; hi = (hi + Math.imul(ah4, bh7)) | 0; lo = (lo + Math.imul(al3, bl8)) | 0; mid = (mid + Math.imul(al3, bh8)) | 0; mid = (mid + Math.imul(ah3, bl8)) | 0; hi = (hi + Math.imul(ah3, bh8)) | 0; lo = (lo + Math.imul(al2, bl9)) | 0; mid = (mid + Math.imul(al2, bh9)) | 0; mid = (mid + Math.imul(ah2, bl9)) | 0; hi = (hi + Math.imul(ah2, bh9)) | 0; var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; w11 &= 0x3ffffff; /* k = 12 */ lo = Math.imul(al9, bl3); mid = Math.imul(al9, bh3); mid = (mid + Math.imul(ah9, bl3)) | 0; hi = Math.imul(ah9, bh3); lo = (lo + Math.imul(al8, bl4)) | 0; mid = (mid + Math.imul(al8, bh4)) | 0; mid = (mid + Math.imul(ah8, bl4)) | 0; hi = (hi + Math.imul(ah8, bh4)) | 0; lo = (lo + Math.imul(al7, bl5)) | 0; mid = (mid + Math.imul(al7, bh5)) | 0; mid = (mid + Math.imul(ah7, bl5)) | 0; hi = (hi + Math.imul(ah7, bh5)) | 0; lo = (lo + Math.imul(al6, bl6)) | 0; mid = (mid + Math.imul(al6, bh6)) | 0; mid = (mid + Math.imul(ah6, bl6)) | 0; hi = (hi + Math.imul(ah6, bh6)) | 0; lo = (lo + Math.imul(al5, bl7)) | 0; mid = (mid + Math.imul(al5, bh7)) | 0; mid = (mid + Math.imul(ah5, bl7)) | 0; hi = (hi + Math.imul(ah5, bh7)) | 0; lo = (lo + Math.imul(al4, bl8)) | 0; mid = (mid + Math.imul(al4, bh8)) | 0; mid = (mid + Math.imul(ah4, bl8)) | 0; hi = (hi + Math.imul(ah4, bh8)) | 0; lo = (lo + Math.imul(al3, bl9)) | 0; mid = (mid + Math.imul(al3, bh9)) | 0; mid = (mid + Math.imul(ah3, bl9)) | 0; hi = (hi + Math.imul(ah3, bh9)) | 0; var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; w12 &= 0x3ffffff; /* k = 13 */ lo = Math.imul(al9, bl4); mid = Math.imul(al9, bh4); mid = (mid + Math.imul(ah9, bl4)) | 0; hi = Math.imul(ah9, bh4); lo = (lo + Math.imul(al8, bl5)) | 0; mid = (mid + Math.imul(al8, bh5)) | 0; mid = (mid + Math.imul(ah8, bl5)) | 0; hi = (hi + Math.imul(ah8, bh5)) | 0; lo = (lo + Math.imul(al7, bl6)) | 0; mid = (mid + Math.imul(al7, bh6)) | 0; mid = (mid + Math.imul(ah7, bl6)) | 0; hi = (hi + Math.imul(ah7, bh6)) | 0; lo = (lo + Math.imul(al6, bl7)) | 0; mid = (mid + Math.imul(al6, bh7)) | 0; mid = (mid + Math.imul(ah6, bl7)) | 0; hi = (hi + Math.imul(ah6, bh7)) | 0; lo = (lo + Math.imul(al5, bl8)) | 0; mid = (mid + Math.imul(al5, bh8)) | 0; mid = (mid + Math.imul(ah5, bl8)) | 0; hi = (hi + Math.imul(ah5, bh8)) | 0; lo = (lo + Math.imul(al4, bl9)) | 0; mid = (mid + Math.imul(al4, bh9)) | 0; mid = (mid + Math.imul(ah4, bl9)) | 0; hi = (hi + Math.imul(ah4, bh9)) | 0; var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; w13 &= 0x3ffffff; /* k = 14 */ lo = Math.imul(al9, bl5); mid = Math.imul(al9, bh5); mid = (mid + Math.imul(ah9, bl5)) | 0; hi = Math.imul(ah9, bh5); lo = (lo + Math.imul(al8, bl6)) | 0; mid = (mid + Math.imul(al8, bh6)) | 0; mid = (mid + Math.imul(ah8, bl6)) | 0; hi = (hi + Math.imul(ah8, bh6)) | 0; lo = (lo + Math.imul(al7, bl7)) | 0; mid = (mid + Math.imul(al7, bh7)) | 0; mid = (mid + Math.imul(ah7, bl7)) | 0; hi = (hi + Math.imul(ah7, bh7)) | 0; lo = (lo + Math.imul(al6, bl8)) | 0; mid = (mid + Math.imul(al6, bh8)) | 0; mid = (mid + Math.imul(ah6, bl8)) | 0; hi = (hi + Math.imul(ah6, bh8)) | 0; lo = (lo + Math.imul(al5, bl9)) | 0; mid = (mid + Math.imul(al5, bh9)) | 0; mid = (mid + Math.imul(ah5, bl9)) | 0; hi = (hi + Math.imul(ah5, bh9)) | 0; var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; w14 &= 0x3ffffff; /* k = 15 */ lo = Math.imul(al9, bl6); mid = Math.imul(al9, bh6); mid = (mid + Math.imul(ah9, bl6)) | 0; hi = Math.imul(ah9, bh6); lo = (lo + Math.imul(al8, bl7)) | 0; mid = (mid + Math.imul(al8, bh7)) | 0; mid = (mid + Math.imul(ah8, bl7)) | 0; hi = (hi + Math.imul(ah8, bh7)) | 0; lo = (lo + Math.imul(al7, bl8)) | 0; mid = (mid + Math.imul(al7, bh8)) | 0; mid = (mid + Math.imul(ah7, bl8)) | 0; hi = (hi + Math.imul(ah7, bh8)) | 0; lo = (lo + Math.imul(al6, bl9)) | 0; mid = (mid + Math.imul(al6, bh9)) | 0; mid = (mid + Math.imul(ah6, bl9)) | 0; hi = (hi + Math.imul(ah6, bh9)) | 0; var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; w15 &= 0x3ffffff; /* k = 16 */ lo = Math.imul(al9, bl7); mid = Math.imul(al9, bh7); mid = (mid + Math.imul(ah9, bl7)) | 0; hi = Math.imul(ah9, bh7); lo = (lo + Math.imul(al8, bl8)) | 0; mid = (mid + Math.imul(al8, bh8)) | 0; mid = (mid + Math.imul(ah8, bl8)) | 0; hi = (hi + Math.imul(ah8, bh8)) | 0; lo = (lo + Math.imul(al7, bl9)) | 0; mid = (mid + Math.imul(al7, bh9)) | 0; mid = (mid + Math.imul(ah7, bl9)) | 0; hi = (hi + Math.imul(ah7, bh9)) | 0; var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; w16 &= 0x3ffffff; /* k = 17 */ lo = Math.imul(al9, bl8); mid = Math.imul(al9, bh8); mid = (mid + Math.imul(ah9, bl8)) | 0; hi = Math.imul(ah9, bh8); lo = (lo + Math.imul(al8, bl9)) | 0; mid = (mid + Math.imul(al8, bh9)) | 0; mid = (mid + Math.imul(ah8, bl9)) | 0; hi = (hi + Math.imul(ah8, bh9)) | 0; var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; w17 &= 0x3ffffff; /* k = 18 */ lo = Math.imul(al9, bl9); mid = Math.imul(al9, bh9); mid = (mid + Math.imul(ah9, bl9)) | 0; hi = Math.imul(ah9, bh9); var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; w18 &= 0x3ffffff; o[0] = w0; o[1] = w1; o[2] = w2; o[3] = w3; o[4] = w4; o[5] = w5; o[6] = w6; o[7] = w7; o[8] = w8; o[9] = w9; o[10] = w10; o[11] = w11; o[12] = w12; o[13] = w13; o[14] = w14; o[15] = w15; o[16] = w16; o[17] = w17; o[18] = w18; if (c !== 0) { o[19] = c; out.length++; } return out; }; // Polyfill comb if (!Math.imul) { comb10MulTo = smallMulTo; } function bigMulTo (self, num, out) { out.negative = num.negative ^ self.negative; out.length = self.length + num.length; var carry = 0; var hncarry = 0; for (var k = 0; k < out.length - 1; k++) { // Sum all words with the same `i + j = k` and accumulate `ncarry`, // note that ncarry could be >= 0x3ffffff var ncarry = hncarry; hncarry = 0; var rword = carry & 0x3ffffff; var maxJ = Math.min(k, num.length - 1); for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { var i = k - j; var a = self.words[i] | 0; var b = num.words[j] | 0; var r = a * b; var lo = r & 0x3ffffff; ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; lo = (lo + rword) | 0; rword = lo & 0x3ffffff; ncarry = (ncarry + (lo >>> 26)) | 0; hncarry += ncarry >>> 26; ncarry &= 0x3ffffff; } out.words[k] = rword; carry = ncarry; ncarry = hncarry; } if (carry !== 0) { out.words[k] = carry; } else { out.length--; } return out.strip(); } function jumboMulTo (self, num, out) { var fftm = new FFTM(); return fftm.mulp(self, num, out); } BN.prototype.mulTo = function mulTo (num, out) { var res; var len = this.length + num.length; if (this.length === 10 && num.length === 10) { res = comb10MulTo(this, num, out); } else if (len < 63) { res = smallMulTo(this, num, out); } else if (len < 1024) { res = bigMulTo(this, num, out); } else { res = jumboMulTo(this, num, out); } return res; }; // Cooley-Tukey algorithm for FFT // slightly revisited to rely on looping instead of recursion function FFTM (x, y) { this.x = x; this.y = y; } FFTM.prototype.makeRBT = function makeRBT (N) { var t = new Array(N); var l = BN.prototype._countBits(N) - 1; for (var i = 0; i < N; i++) { t[i] = this.revBin(i, l, N); } return t; }; // Returns binary-reversed representation of `x` FFTM.prototype.revBin = function revBin (x, l, N) { if (x === 0 || x === N - 1) return x; var rb = 0; for (var i = 0; i < l; i++) { rb |= (x & 1) << (l - i - 1); x >>= 1; } return rb; }; // Performs "tweedling" phase, therefore 'emulating' // behaviour of the recursive algorithm FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { for (var i = 0; i < N; i++) { rtws[i] = rws[rbt[i]]; itws[i] = iws[rbt[i]]; } }; FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { this.permute(rbt, rws, iws, rtws, itws, N); for (var s = 1; s < N; s <<= 1) { var l = s << 1; var rtwdf = Math.cos(2 * Math.PI / l); var itwdf = Math.sin(2 * Math.PI / l); for (var p = 0; p < N; p += l) { var rtwdf_ = rtwdf; var itwdf_ = itwdf; for (var j = 0; j < s; j++) { var re = rtws[p + j]; var ie = itws[p + j]; var ro = rtws[p + j + s]; var io = itws[p + j + s]; var rx = rtwdf_ * ro - itwdf_ * io; io = rtwdf_ * io + itwdf_ * ro; ro = rx; rtws[p + j] = re + ro; itws[p + j] = ie + io; rtws[p + j + s] = re - ro; itws[p + j + s] = ie - io; /* jshint maxdepth : false */ if (j !== l) { rx = rtwdf * rtwdf_ - itwdf * itwdf_; itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; rtwdf_ = rx; } } } } }; FFTM.prototype.guessLen13b = function guessLen13b (n, m) { var N = Math.max(m, n) | 1; var odd = N & 1; var i = 0; for (N = N / 2 | 0; N; N = N >>> 1) { i++; } return 1 << i + 1 + odd; }; FFTM.prototype.conjugate = function conjugate (rws, iws, N) { if (N <= 1) return; for (var i = 0; i < N / 2; i++) { var t = rws[i]; rws[i] = rws[N - i - 1]; rws[N - i - 1] = t; t = iws[i]; iws[i] = -iws[N - i - 1]; iws[N - i - 1] = -t; } }; FFTM.prototype.normalize13b = function normalize13b (ws, N) { var carry = 0; for (var i = 0; i < N / 2; i++) { var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + Math.round(ws[2 * i] / N) + carry; ws[i] = w & 0x3ffffff; if (w < 0x4000000) { carry = 0; } else { carry = w / 0x4000000 | 0; } } return ws; }; FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { var carry = 0; for (var i = 0; i < len; i++) { carry = carry + (ws[i] | 0); rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; } // Pad with zeroes for (i = 2 * len; i < N; ++i) { rws[i] = 0; } assert(carry === 0); assert((carry & ~0x1fff) === 0); }; FFTM.prototype.stub = function stub (N) { var ph = new Array(N); for (var i = 0; i < N; i++) { ph[i] = 0; } return ph; }; FFTM.prototype.mulp = function mulp (x, y, out) { var N = 2 * this.guessLen13b(x.length, y.length); var rbt = this.makeRBT(N); var _ = this.stub(N); var rws = new Array(N); var rwst = new Array(N); var iwst = new Array(N); var nrws = new Array(N); var nrwst = new Array(N); var niwst = new Array(N); var rmws = out.words; rmws.length = N; this.convert13b(x.words, x.length, rws, N); this.convert13b(y.words, y.length, nrws, N); this.transform(rws, _, rwst, iwst, N, rbt); this.transform(nrws, _, nrwst, niwst, N, rbt); for (var i = 0; i < N; i++) { var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; rwst[i] = rx; } this.conjugate(rwst, iwst, N); this.transform(rwst, iwst, rmws, _, N, rbt); this.conjugate(rmws, _, N); this.normalize13b(rmws, N); out.negative = x.negative ^ y.negative; out.length = x.length + y.length; return out.strip(); }; // Multiply `this` by `num` BN.prototype.mul = function mul (num) { var out = new BN(null); out.words = new Array(this.length + num.length); return this.mulTo(num, out); }; // Multiply employing FFT BN.prototype.mulf = function mulf (num) { var out = new BN(null); out.words = new Array(this.length + num.length); return jumboMulTo(this, num, out); }; // In-place Multiplication BN.prototype.imul = function imul (num) { return this.clone().mulTo(num, this); }; BN.prototype.imuln = function imuln (num) { assert(typeof num === 'number'); assert(num < 0x4000000); // Carry var carry = 0; for (var i = 0; i < this.length; i++) { var w = (this.words[i] | 0) * num; var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); carry >>= 26; carry += (w / 0x4000000) | 0; // NOTE: lo is 27bit maximum carry += lo >>> 26; this.words[i] = lo & 0x3ffffff; } if (carry !== 0) { this.words[i] = carry; this.length++; } return this; }; BN.prototype.muln = function muln (num) { return this.clone().imuln(num); }; // `this` * `this` BN.prototype.sqr = function sqr () { return this.mul(this); }; // `this` * `this` in-place BN.prototype.isqr = function isqr () { return this.imul(this.clone()); }; // Math.pow(`this`, `num`) BN.prototype.pow = function pow (num) { var w = toBitArray(num); if (w.length === 0) return new BN(1); // Skip leading zeroes var res = this; for (var i = 0; i < w.length; i++, res = res.sqr()) { if (w[i] !== 0) break; } if (++i < w.length) { for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { if (w[i] === 0) continue; res = res.mul(q); } } return res; }; // Shift-left in-place BN.prototype.iushln = function iushln (bits) { assert(typeof bits === 'number' && bits >= 0); var r = bits % 26; var s = (bits - r) / 26; var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); var i; if (r !== 0) { var carry = 0; for (i = 0; i < this.length; i++) { var newCarry = this.words[i] & carryMask; var c = ((this.words[i] | 0) - newCarry) << r; this.words[i] = c | carry; carry = newCarry >>> (26 - r); } if (carry) { this.words[i] = carry; this.length++; } } if (s !== 0) { for (i = this.length - 1; i >= 0; i--) { this.words[i + s] = this.words[i]; } for (i = 0; i < s; i++) { this.words[i] = 0; } this.length += s; } return this.strip(); }; BN.prototype.ishln = function ishln (bits) { // TODO(indutny): implement me assert(this.negative === 0); return this.iushln(bits); }; // Shift-right in-place // NOTE: `hint` is a lowest bit before trailing zeroes // NOTE: if `extended` is present - it will be filled with destroyed bits BN.prototype.iushrn = function iushrn (bits, hint, extended) { assert(typeof bits === 'number' && bits >= 0); var h; if (hint) { h = (hint - (hint % 26)) / 26; } else { h = 0; } var r = bits % 26; var s = Math.min((bits - r) / 26, this.length); var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); var maskedWords = extended; h -= s; h = Math.max(0, h); // Extended mode, copy masked part if (maskedWords) { for (var i = 0; i < s; i++) { maskedWords.words[i] = this.words[i]; } maskedWords.length = s; } if (s === 0) { // No-op, we should not move anything at all } else if (this.length > s) { this.length -= s; for (i = 0; i < this.length; i++) { this.words[i] = this.words[i + s]; } } else { this.words[0] = 0; this.length = 1; } var carry = 0; for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { var word = this.words[i] | 0; this.words[i] = (carry << (26 - r)) | (word >>> r); carry = word & mask; } // Push carried bits as a mask if (maskedWords && carry !== 0) { maskedWords.words[maskedWords.length++] = carry; } if (this.length === 0) { this.words[0] = 0; this.length = 1; } return this.strip(); }; BN.prototype.ishrn = function ishrn (bits, hint, extended) { // TODO(indutny): implement me assert(this.negative === 0); return this.iushrn(bits, hint, extended); }; // Shift-left BN.prototype.shln = function shln (bits) { return this.clone().ishln(bits); }; BN.prototype.ushln = function ushln (bits) { return this.clone().iushln(bits); }; // Shift-right BN.prototype.shrn = function shrn (bits) { return this.clone().ishrn(bits); }; BN.prototype.ushrn = function ushrn (bits) { return this.clone().iushrn(bits); }; // Test if n bit is set BN.prototype.testn = function testn (bit) { assert(typeof bit === 'number' && bit >= 0); var r = bit % 26; var s = (bit - r) / 26; var q = 1 << r; // Fast case: bit is much higher than all existing words if (this.length <= s) return false; // Check bit and return var w = this.words[s]; return !!(w & q); }; // Return only lowers bits of number (in-place) BN.prototype.imaskn = function imaskn (bits) { assert(typeof bits === 'number' && bits >= 0); var r = bits % 26; var s = (bits - r) / 26; assert(this.negative === 0, 'imaskn works only with positive numbers'); if (this.length <= s) { return this; } if (r !== 0) { s++; } this.length = Math.min(s, this.length); if (r !== 0) { var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); this.words[this.length - 1] &= mask; } return this.strip(); }; // Return only lowers bits of number BN.prototype.maskn = function maskn (bits) { return this.clone().imaskn(bits); }; // Add plain number `num` to `this` BN.prototype.iaddn = function iaddn (num) { assert(typeof num === 'number'); assert(num < 0x4000000); if (num < 0) return this.isubn(-num); // Possible sign change if (this.negative !== 0) { if (this.length === 1 && (this.words[0] | 0) < num) { this.words[0] = num - (this.words[0] | 0); this.negative = 0; return this; } this.negative = 0; this.isubn(num); this.negative = 1; return this; } // Add without checks return this._iaddn(num); }; BN.prototype._iaddn = function _iaddn (num) { this.words[0] += num; // Carry for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { this.words[i] -= 0x4000000; if (i === this.length - 1) { this.words[i + 1] = 1; } else { this.words[i + 1]++; } } this.length = Math.max(this.length, i + 1); return this; }; // Subtract plain number `num` from `this` BN.prototype.isubn = function isubn (num) { assert(typeof num === 'number'); assert(num < 0x4000000); if (num < 0) return this.iaddn(-num); if (this.negative !== 0) { this.negative = 0; this.iaddn(num); this.negative = 1; return this; } this.words[0] -= num; if (this.length === 1 && this.words[0] < 0) { this.words[0] = -this.words[0]; this.negative = 1; } else { // Carry for (var i = 0; i < this.length && this.words[i] < 0; i++) { this.words[i] += 0x4000000; this.words[i + 1] -= 1; } } return this.strip(); }; BN.prototype.addn = function addn (num) { return this.clone().iaddn(num); }; BN.prototype.subn = function subn (num) { return this.clone().isubn(num); }; BN.prototype.iabs = function iabs () { this.negative = 0; return this; }; BN.prototype.abs = function abs () { return this.clone().iabs(); }; BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { var len = num.length + shift; var i; this._expand(len); var w; var carry = 0; for (i = 0; i < num.length; i++) { w = (this.words[i + shift] | 0) + carry; var right = (num.words[i] | 0) * mul; w -= right & 0x3ffffff; carry = (w >> 26) - ((right / 0x4000000) | 0); this.words[i + shift] = w & 0x3ffffff; } for (; i < this.length - shift; i++) { w = (this.words[i + shift] | 0) + carry; carry = w >> 26; this.words[i + shift] = w & 0x3ffffff; } if (carry === 0) return this.strip(); // Subtraction overflow assert(carry === -1); carry = 0; for (i = 0; i < this.length; i++) { w = -(this.words[i] | 0) + carry; carry = w >> 26; this.words[i] = w & 0x3ffffff; } this.negative = 1; return this.strip(); }; BN.prototype._wordDiv = function _wordDiv (num, mode) { var shift = this.length - num.length; var a = this.clone(); var b = num; // Normalize var bhi = b.words[b.length - 1] | 0; var bhiBits = this._countBits(bhi); shift = 26 - bhiBits; if (shift !== 0) { b = b.ushln(shift); a.iushln(shift); bhi = b.words[b.length - 1] | 0; } // Initialize quotient var m = a.length - b.length; var q; if (mode !== 'mod') { q = new BN(null); q.length = m + 1; q.words = new Array(q.length); for (var i = 0; i < q.length; i++) { q.words[i] = 0; } } var diff = a.clone()._ishlnsubmul(b, 1, m); if (diff.negative === 0) { a = diff; if (q) { q.words[m] = 1; } } for (var j = m - 1; j >= 0; j--) { var qj = (a.words[b.length + j] | 0) * 0x4000000 + (a.words[b.length + j - 1] | 0); // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max // (0x7ffffff) qj = Math.min((qj / bhi) | 0, 0x3ffffff); a._ishlnsubmul(b, qj, j); while (a.negative !== 0) { qj--; a.negative = 0; a._ishlnsubmul(b, 1, j); if (!a.isZero()) { a.negative ^= 1; } } if (q) { q.words[j] = qj; } } if (q) { q.strip(); } a.strip(); // Denormalize if (mode !== 'div' && shift !== 0) { a.iushrn(shift); } return { div: q || null, mod: a }; }; // NOTE: 1) `mode` can be set to `mod` to request mod only, // to `div` to request div only, or be absent to // request both div & mod // 2) `positive` is true if unsigned mod is requested BN.prototype.divmod = function divmod (num, mode, positive) { assert(!num.isZero()); if (this.isZero()) { return { div: new BN(0), mod: new BN(0) }; } var div, mod, res; if (this.negative !== 0 && num.negative === 0) { res = this.neg().divmod(num, mode); if (mode !== 'mod') { div = res.div.neg(); } if (mode !== 'div') { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.iadd(num); } } return { div: div, mod: mod }; } if (this.negative === 0 && num.negative !== 0) { res = this.divmod(num.neg(), mode); if (mode !== 'mod') { div = res.div.neg(); } return { div: div, mod: res.mod }; } if ((this.negative & num.negative) !== 0) { res = this.neg().divmod(num.neg(), mode); if (mode !== 'div') { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.isub(num); } } return { div: res.div, mod: mod }; } // Both numbers are positive at this point // Strip both numbers to approximate shift value if (num.length > this.length || this.cmp(num) < 0) { return { div: new BN(0), mod: this }; } // Very short reduction if (num.length === 1) { if (mode === 'div') { return { div: this.divn(num.words[0]), mod: null }; } if (mode === 'mod') { return { div: null, mod: new BN(this.modn(num.words[0])) }; } return { div: this.divn(num.words[0]), mod: new BN(this.modn(num.words[0])) }; } return this._wordDiv(num, mode); }; // Find `this` / `num` BN.prototype.div = function div (num) { return this.divmod(num, 'div', false).div; }; // Find `this` % `num` BN.prototype.mod = function mod (num) { return this.divmod(num, 'mod', false).mod; }; BN.prototype.umod = function umod (num) { return this.divmod(num, 'mod', true).mod; }; // Find Round(`this` / `num`) BN.prototype.divRound = function divRound (num) { var dm = this.divmod(num); // Fast case - exact division if (dm.mod.isZero()) return dm.div; var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; var half = num.ushrn(1); var r2 = num.andln(1); var cmp = mod.cmp(half); // Round down if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; // Round up return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); }; BN.prototype.modn = function modn (num) { assert(num <= 0x3ffffff); var p = (1 << 26) % num; var acc = 0; for (var i = this.length - 1; i >= 0; i--) { acc = (p * acc + (this.words[i] | 0)) % num; } return acc; }; // In-place division by number BN.prototype.idivn = function idivn (num) { assert(num <= 0x3ffffff); var carry = 0; for (var i = this.length - 1; i >= 0; i--) { var w = (this.words[i] | 0) + carry * 0x4000000; this.words[i] = (w / num) | 0; carry = w % num; } return this.strip(); }; BN.prototype.divn = function divn (num) { return this.clone().idivn(num); }; BN.prototype.egcd = function egcd (p) { assert(p.negative === 0); assert(!p.isZero()); var x = this; var y = p.clone(); if (x.negative !== 0) { x = x.umod(p); } else { x = x.clone(); } // A * x + B * y = x var A = new BN(1); var B = new BN(0); // C * x + D * y = y var C = new BN(0); var D = new BN(1); var g = 0; while (x.isEven() && y.isEven()) { x.iushrn(1); y.iushrn(1); ++g; } var yp = y.clone(); var xp = x.clone(); while (!x.isZero()) { for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); if (i > 0) { x.iushrn(i); while (i-- > 0) { if (A.isOdd() || B.isOdd()) { A.iadd(yp); B.isub(xp); } A.iushrn(1); B.iushrn(1); } } for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); if (j > 0) { y.iushrn(j); while (j-- > 0) { if (C.isOdd() || D.isOdd()) { C.iadd(yp); D.isub(xp); } C.iushrn(1); D.iushrn(1); } } if (x.cmp(y) >= 0) { x.isub(y); A.isub(C); B.isub(D); } else { y.isub(x); C.isub(A); D.isub(B); } } return { a: C, b: D, gcd: y.iushln(g) }; }; // This is reduced incarnation of the binary EEA // above, designated to invert members of the // _prime_ fields F(p) at a maximal speed BN.prototype._invmp = function _invmp (p) { assert(p.negative === 0); assert(!p.isZero()); var a = this; var b = p.clone(); if (a.negative !== 0) { a = a.umod(p); } else { a = a.clone(); } var x1 = new BN(1); var x2 = new BN(0); var delta = b.clone(); while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); if (i > 0) { a.iushrn(i); while (i-- > 0) { if (x1.isOdd()) { x1.iadd(delta); } x1.iushrn(1); } } for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); if (j > 0) { b.iushrn(j); while (j-- > 0) { if (x2.isOdd()) { x2.iadd(delta); } x2.iushrn(1); } } if (a.cmp(b) >= 0) { a.isub(b); x1.isub(x2); } else { b.isub(a); x2.isub(x1); } } var res; if (a.cmpn(1) === 0) { res = x1; } else { res = x2; } if (res.cmpn(0) < 0) { res.iadd(p); } return res; }; BN.prototype.gcd = function gcd (num) { if (this.isZero()) return num.abs(); if (num.isZero()) return this.abs(); var a = this.clone(); var b = num.clone(); a.negative = 0; b.negative = 0; // Remove common factor of two for (var shift = 0; a.isEven() && b.isEven(); shift++) { a.iushrn(1); b.iushrn(1); } do { while (a.isEven()) { a.iushrn(1); } while (b.isEven()) { b.iushrn(1); } var r = a.cmp(b); if (r < 0) { // Swap `a` and `b` to make `a` always bigger than `b` var t = a; a = b; b = t; } else if (r === 0 || b.cmpn(1) === 0) { break; } a.isub(b); } while (true); return b.iushln(shift); }; // Invert number in the field F(num) BN.prototype.invm = function invm (num) { return this.egcd(num).a.umod(num); }; BN.prototype.isEven = function isEven () { return (this.words[0] & 1) === 0; }; BN.prototype.isOdd = function isOdd () { return (this.words[0] & 1) === 1; }; // And first word and num BN.prototype.andln = function andln (num) { return this.words[0] & num; }; // Increment at the bit position in-line BN.prototype.bincn = function bincn (bit) { assert(typeof bit === 'number'); var r = bit % 26; var s = (bit - r) / 26; var q = 1 << r; // Fast case: bit is much higher than all existing words if (this.length <= s) { this._expand(s + 1); this.words[s] |= q; return this; } // Add bit and propagate, if needed var carry = q; for (var i = s; carry !== 0 && i < this.length; i++) { var w = this.words[i] | 0; w += carry; carry = w >>> 26; w &= 0x3ffffff; this.words[i] = w; } if (carry !== 0) { this.words[i] = carry; this.length++; } return this; }; BN.prototype.isZero = function isZero () { return this.length === 1 && this.words[0] === 0; }; BN.prototype.cmpn = function cmpn (num) { var negative = num < 0; if (this.negative !== 0 && !negative) return -1; if (this.negative === 0 && negative) return 1; this.strip(); var res; if (this.length > 1) { res = 1; } else { if (negative) { num = -num; } assert(num <= 0x3ffffff, 'Number is too big'); var w = this.words[0] | 0; res = w === num ? 0 : w < num ? -1 : 1; } if (this.negative !== 0) return -res | 0; return res; }; // Compare two numbers and return: // 1 - if `this` > `num` // 0 - if `this` == `num` // -1 - if `this` < `num` BN.prototype.cmp = function cmp (num) { if (this.negative !== 0 && num.negative === 0) return -1; if (this.negative === 0 && num.negative !== 0) return 1; var res = this.ucmp(num); if (this.negative !== 0) return -res | 0; return res; }; // Unsigned comparison BN.prototype.ucmp = function ucmp (num) { // At this point both numbers have the same sign if (this.length > num.length) return 1; if (this.length < num.length) return -1; var res = 0; for (var i = this.length - 1; i >= 0; i--) { var a = this.words[i] | 0; var b = num.words[i] | 0; if (a === b) continue; if (a < b) { res = -1; } else if (a > b) { res = 1; } break; } return res; }; BN.prototype.gtn = function gtn (num) { return this.cmpn(num) === 1; }; BN.prototype.gt = function gt (num) { return this.cmp(num) === 1; }; BN.prototype.gten = function gten (num) { return this.cmpn(num) >= 0; }; BN.prototype.gte = function gte (num) { return this.cmp(num) >= 0; }; BN.prototype.ltn = function ltn (num) { return this.cmpn(num) === -1; }; BN.prototype.lt = function lt (num) { return this.cmp(num) === -1; }; BN.prototype.lten = function lten (num) { return this.cmpn(num) <= 0; }; BN.prototype.lte = function lte (num) { return this.cmp(num) <= 0; }; BN.prototype.eqn = function eqn (num) { return this.cmpn(num) === 0; }; BN.prototype.eq = function eq (num) { return this.cmp(num) === 0; }; // // A reduce context, could be using montgomery or something better, depending // on the `m` itself. // BN.red = function red (num) { return new Red(num); }; BN.prototype.toRed = function toRed (ctx) { assert(!this.red, 'Already a number in reduction context'); assert(this.negative === 0, 'red works only with positives'); return ctx.convertTo(this)._forceRed(ctx); }; BN.prototype.fromRed = function fromRed () { assert(this.red, 'fromRed works only with numbers in reduction context'); return this.red.convertFrom(this); }; BN.prototype._forceRed = function _forceRed (ctx) { this.red = ctx; return this; }; BN.prototype.forceRed = function forceRed (ctx) { assert(!this.red, 'Already a number in reduction context'); return this._forceRed(ctx); }; BN.prototype.redAdd = function redAdd (num) { assert(this.red, 'redAdd works only with red numbers'); return this.red.add(this, num); }; BN.prototype.redIAdd = function redIAdd (num) { assert(this.red, 'redIAdd works only with red numbers'); return this.red.iadd(this, num); }; BN.prototype.redSub = function redSub (num) { assert(this.red, 'redSub works only with red numbers'); return this.red.sub(this, num); }; BN.prototype.redISub = function redISub (num) { assert(this.red, 'redISub works only with red numbers'); return this.red.isub(this, num); }; BN.prototype.redShl = function redShl (num) { assert(this.red, 'redShl works only with red numbers'); return this.red.shl(this, num); }; BN.prototype.redMul = function redMul (num) { assert(this.red, 'redMul works only with red numbers'); this.red._verify2(this, num); return this.red.mul(this, num); }; BN.prototype.redIMul = function redIMul (num) { assert(this.red, 'redMul works only with red numbers'); this.red._verify2(this, num); return this.red.imul(this, num); }; BN.prototype.redSqr = function redSqr () { assert(this.red, 'redSqr works only with red numbers'); this.red._verify1(this); return this.red.sqr(this); }; BN.prototype.redISqr = function redISqr () { assert(this.red, 'redISqr works only with red numbers'); this.red._verify1(this); return this.red.isqr(this); }; // Square root over p BN.prototype.redSqrt = function redSqrt () { assert(this.red, 'redSqrt works only with red numbers'); this.red._verify1(this); return this.red.sqrt(this); }; BN.prototype.redInvm = function redInvm () { assert(this.red, 'redInvm works only with red numbers'); this.red._verify1(this); return this.red.invm(this); }; // Return negative clone of `this` % `red modulo` BN.prototype.redNeg = function redNeg () { assert(this.red, 'redNeg works only with red numbers'); this.red._verify1(this); return this.red.neg(this); }; BN.prototype.redPow = function redPow (num) { assert(this.red && !num.red, 'redPow(normalNum)'); this.red._verify1(this); return this.red.pow(this, num); }; // Prime numbers with efficient reduction var primes = { k256: null, p224: null, p192: null, p25519: null }; // Pseudo-Mersenne prime function MPrime (name, p) { // P = 2 ^ N - K this.name = name; this.p = new BN(p, 16); this.n = this.p.bitLength(); this.k = new BN(1).iushln(this.n).isub(this.p); this.tmp = this._tmp(); } MPrime.prototype._tmp = function _tmp () { var tmp = new BN(null); tmp.words = new Array(Math.ceil(this.n / 13)); return tmp; }; MPrime.prototype.ireduce = function ireduce (num) { // Assumes that `num` is less than `P^2` // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) var r = num; var rlen; do { this.split(r, this.tmp); r = this.imulK(r); r = r.iadd(this.tmp); rlen = r.bitLength(); } while (rlen > this.n); var cmp = rlen < this.n ? -1 : r.ucmp(this.p); if (cmp === 0) { r.words[0] = 0; r.length = 1; } else if (cmp > 0) { r.isub(this.p); } else { if (r.strip !== undefined) { // r is BN v4 instance r.strip(); } else { // r is BN v5 instance r._strip(); } } return r; }; MPrime.prototype.split = function split (input, out) { input.iushrn(this.n, 0, out); }; MPrime.prototype.imulK = function imulK (num) { return num.imul(this.k); }; function K256 () { MPrime.call( this, 'k256', 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); } inherits(K256, MPrime); K256.prototype.split = function split (input, output) { // 256 = 9 * 26 + 22 var mask = 0x3fffff; var outLen = Math.min(input.length, 9); for (var i = 0; i < outLen; i++) { output.words[i] = input.words[i]; } output.length = outLen; if (input.length <= 9) { input.words[0] = 0; input.length = 1; return; } // Shift by 9 limbs var prev = input.words[9]; output.words[output.length++] = prev & mask; for (i = 10; i < input.length; i++) { var next = input.words[i] | 0; input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); prev = next; } prev >>>= 22; input.words[i - 10] = prev; if (prev === 0 && input.length > 10) { input.length -= 10; } else { input.length -= 9; } }; K256.prototype.imulK = function imulK (num) { // K = 0x1000003d1 = [ 0x40, 0x3d1 ] num.words[num.length] = 0; num.words[num.length + 1] = 0; num.length += 2; // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 var lo = 0; for (var i = 0; i < num.length; i++) { var w = num.words[i] | 0; lo += w * 0x3d1; num.words[i] = lo & 0x3ffffff; lo = w * 0x40 + ((lo / 0x4000000) | 0); } // Fast length reduction if (num.words[num.length - 1] === 0) { num.length--; if (num.words[num.length - 1] === 0) { num.length--; } } return num; }; function P224 () { MPrime.call( this, 'p224', 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); } inherits(P224, MPrime); function P192 () { MPrime.call( this, 'p192', 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); } inherits(P192, MPrime); function P25519 () { // 2 ^ 255 - 19 MPrime.call( this, '25519', '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); } inherits(P25519, MPrime); P25519.prototype.imulK = function imulK (num) { // K = 0x13 var carry = 0; for (var i = 0; i < num.length; i++) { var hi = (num.words[i] | 0) * 0x13 + carry; var lo = hi & 0x3ffffff; hi >>>= 26; num.words[i] = lo; carry = hi; } if (carry !== 0) { num.words[num.length++] = carry; } return num; }; // Exported mostly for testing purposes, use plain name instead BN._prime = function prime (name) { // Cached version of prime if (primes[name]) return primes[name]; var prime; if (name === 'k256') { prime = new K256(); } else if (name === 'p224') { prime = new P224(); } else if (name === 'p192') { prime = new P192(); } else if (name === 'p25519') { prime = new P25519(); } else { throw new Error('Unknown prime ' + name); } primes[name] = prime; return prime; }; // // Base reduction engine // function Red (m) { if (typeof m === 'string') { var prime = BN._prime(m); this.m = prime.p; this.prime = prime; } else { assert(m.gtn(1), 'modulus must be greater than 1'); this.m = m; this.prime = null; } } Red.prototype._verify1 = function _verify1 (a) { assert(a.negative === 0, 'red works only with positives'); assert(a.red, 'red works only with red numbers'); }; Red.prototype._verify2 = function _verify2 (a, b) { assert((a.negative | b.negative) === 0, 'red works only with positives'); assert(a.red && a.red === b.red, 'red works only with red numbers'); }; Red.prototype.imod = function imod (a) { if (this.prime) return this.prime.ireduce(a)._forceRed(this); return a.umod(this.m)._forceRed(this); }; Red.prototype.neg = function neg (a) { if (a.isZero()) { return a.clone(); } return this.m.sub(a)._forceRed(this); }; Red.prototype.add = function add (a, b) { this._verify2(a, b); var res = a.add(b); if (res.cmp(this.m) >= 0) { res.isub(this.m); } return res._forceRed(this); }; Red.prototype.iadd = function iadd (a, b) { this._verify2(a, b); var res = a.iadd(b); if (res.cmp(this.m) >= 0) { res.isub(this.m); } return res; }; Red.prototype.sub = function sub (a, b) { this._verify2(a, b); var res = a.sub(b); if (res.cmpn(0) < 0) { res.iadd(this.m); } return res._forceRed(this); }; Red.prototype.isub = function isub (a, b) { this._verify2(a, b); var res = a.isub(b); if (res.cmpn(0) < 0) { res.iadd(this.m); } return res; }; Red.prototype.shl = function shl (a, num) { this._verify1(a); return this.imod(a.ushln(num)); }; Red.prototype.imul = function imul (a, b) { this._verify2(a, b); return this.imod(a.imul(b)); }; Red.prototype.mul = function mul (a, b) { this._verify2(a, b); return this.imod(a.mul(b)); }; Red.prototype.isqr = function isqr (a) { return this.imul(a, a.clone()); }; Red.prototype.sqr = function sqr (a) { return this.mul(a, a); }; Red.prototype.sqrt = function sqrt (a) { if (a.isZero()) return a.clone(); var mod3 = this.m.andln(3); assert(mod3 % 2 === 1); // Fast case if (mod3 === 3) { var pow = this.m.add(new BN(1)).iushrn(2); return this.pow(a, pow); } // Tonelli-Shanks algorithm (Totally unoptimized and slow) // // Find Q and S, that Q * 2 ^ S = (P - 1) var q = this.m.subn(1); var s = 0; while (!q.isZero() && q.andln(1) === 0) { s++; q.iushrn(1); } assert(!q.isZero()); var one = new BN(1).toRed(this); var nOne = one.redNeg(); // Find quadratic non-residue // NOTE: Max is such because of generalized Riemann hypothesis. var lpow = this.m.subn(1).iushrn(1); var z = this.m.bitLength(); z = new BN(2 * z * z).toRed(this); while (this.pow(z, lpow).cmp(nOne) !== 0) { z.redIAdd(nOne); } var c = this.pow(z, q); var r = this.pow(a, q.addn(1).iushrn(1)); var t = this.pow(a, q); var m = s; while (t.cmp(one) !== 0) { var tmp = t; for (var i = 0; tmp.cmp(one) !== 0; i++) { tmp = tmp.redSqr(); } assert(i < m); var b = this.pow(c, new BN(1).iushln(m - i - 1)); r = r.redMul(b); c = b.redSqr(); t = t.redMul(c); m = i; } return r; }; Red.prototype.invm = function invm (a) { var inv = a._invmp(this.m); if (inv.negative !== 0) { inv.negative = 0; return this.imod(inv).redNeg(); } else { return this.imod(inv); } }; Red.prototype.pow = function pow (a, num) { if (num.isZero()) return new BN(1).toRed(this); if (num.cmpn(1) === 0) return a.clone(); var windowSize = 4; var wnd = new Array(1 << windowSize); wnd[0] = new BN(1).toRed(this); wnd[1] = a; for (var i = 2; i < wnd.length; i++) { wnd[i] = this.mul(wnd[i - 1], a); } var res = wnd[0]; var current = 0; var currentLen = 0; var start = num.bitLength() % 26; if (start === 0) { start = 26; } for (i = num.length - 1; i >= 0; i--) { var word = num.words[i]; for (var j = start - 1; j >= 0; j--) { var bit = (word >> j) & 1; if (res !== wnd[0]) { res = this.sqr(res); } if (bit === 0 && current === 0) { currentLen = 0; continue; } current <<= 1; current |= bit; currentLen++; if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; res = this.mul(res, wnd[current]); currentLen = 0; current = 0; } start = 26; } return res; }; Red.prototype.convertTo = function convertTo (num) { var r = num.umod(this.m); return r === num ? r.clone() : r; }; Red.prototype.convertFrom = function convertFrom (num) { var res = num.clone(); res.red = null; return res; }; // // Montgomery method engine // BN.mont = function mont (num) { return new Mont(num); }; function Mont (m) { Red.call(this, m); this.shift = this.m.bitLength(); if (this.shift % 26 !== 0) { this.shift += 26 - (this.shift % 26); } this.r = new BN(1).iushln(this.shift); this.r2 = this.imod(this.r.sqr()); this.rinv = this.r._invmp(this.m); this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); this.minv = this.minv.umod(this.r); this.minv = this.r.sub(this.minv); } inherits(Mont, Red); Mont.prototype.convertTo = function convertTo (num) { return this.imod(num.ushln(this.shift)); }; Mont.prototype.convertFrom = function convertFrom (num) { var r = this.imod(num.mul(this.rinv)); r.red = null; return r; }; Mont.prototype.imul = function imul (a, b) { if (a.isZero() || b.isZero()) { a.words[0] = 0; a.length = 1; return a; } var t = a.imul(b); var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); var u = t.isub(c).iushrn(this.shift); var res = u; if (u.cmp(this.m) >= 0) { res = u.isub(this.m); } else if (u.cmpn(0) < 0) { res = u.iadd(this.m); } return res._forceRed(this); }; Mont.prototype.mul = function mul (a, b) { if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); var t = a.mul(b); var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); var u = t.isub(c).iushrn(this.shift); var res = u; if (u.cmp(this.m) >= 0) { res = u.isub(this.m); } else if (u.cmpn(0) < 0) { res = u.iadd(this.m); } return res._forceRed(this); }; Mont.prototype.invm = function invm (a) { // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R var res = this.imod(a._invmp(this.m).mul(this.r2)); return res._forceRed(this); }; })( false || module, this); /***/ }), /***/ 9417: /***/ ((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) { 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; } /***/ }), /***/ 6641: /***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { /* module decorator */ module = __nccwpck_require__.nmd(module); (function (module, exports) { 'use strict'; // Utils function assert (val, msg) { if (!val) throw new Error(msg || 'Assertion failed'); } // Could use `inherits` module, but don't want to move from single file // architecture yet. function inherits (ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; } // BN function BN (number, base, endian) { if (BN.isBN(number)) { return number; } this.negative = 0; this.words = null; this.length = 0; // Reduction context this.red = null; if (number !== null) { if (base === 'le' || base === 'be') { endian = base; base = 10; } this._init(number || 0, base || 10, endian || 'be'); } } if (typeof module === 'object') { module.exports = BN; } else { exports.BN = BN; } BN.BN = BN; BN.wordSize = 26; var Buffer; try { if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { Buffer = window.Buffer; } else { Buffer = (__nccwpck_require__(14300).Buffer); } } catch (e) { } BN.isBN = function isBN (num) { if (num instanceof BN) { return true; } return num !== null && typeof num === 'object' && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); }; BN.max = function max (left, right) { if (left.cmp(right) > 0) return left; return right; }; BN.min = function min (left, right) { if (left.cmp(right) < 0) return left; return right; }; BN.prototype._init = function init (number, base, endian) { if (typeof number === 'number') { return this._initNumber(number, base, endian); } if (typeof number === 'object') { return this._initArray(number, base, endian); } if (base === 'hex') { base = 16; } assert(base === (base | 0) && base >= 2 && base <= 36); number = number.toString().replace(/\s+/g, ''); var start = 0; if (number[0] === '-') { start++; this.negative = 1; } if (start < number.length) { if (base === 16) { this._parseHex(number, start, endian); } else { this._parseBase(number, base, start); if (endian === 'le') { this._initArray(this.toArray(), base, endian); } } } }; BN.prototype._initNumber = function _initNumber (number, base, endian) { if (number < 0) { this.negative = 1; number = -number; } if (number < 0x4000000) { this.words = [number & 0x3ffffff]; this.length = 1; } else if (number < 0x10000000000000) { this.words = [ number & 0x3ffffff, (number / 0x4000000) & 0x3ffffff ]; this.length = 2; } else { assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) this.words = [ number & 0x3ffffff, (number / 0x4000000) & 0x3ffffff, 1 ]; this.length = 3; } if (endian !== 'le') return; // Reverse the bytes this._initArray(this.toArray(), base, endian); }; BN.prototype._initArray = function _initArray (number, base, endian) { // Perhaps a Uint8Array assert(typeof number.length === 'number'); if (number.length <= 0) { this.words = [0]; this.length = 1; return this; } this.length = Math.ceil(number.length / 3); this.words = new Array(this.length); for (var i = 0; i < this.length; i++) { this.words[i] = 0; } var j, w; var off = 0; if (endian === 'be') { for (i = number.length - 1, j = 0; i >= 0; i -= 3) { w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; off += 24; if (off >= 26) { off -= 26; j++; } } } else if (endian === 'le') { for (i = 0, j = 0; i < number.length; i += 3) { w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; off += 24; if (off >= 26) { off -= 26; j++; } } } return this._strip(); }; function parseHex4Bits (string, index) { var c = string.charCodeAt(index); // '0' - '9' if (c >= 48 && c <= 57) { return c - 48; // 'A' - 'F' } else if (c >= 65 && c <= 70) { return c - 55; // 'a' - 'f' } else if (c >= 97 && c <= 102) { return c - 87; } else { assert(false, 'Invalid character in ' + string); } } function parseHexByte (string, lowerBound, index) { var r = parseHex4Bits(string, index); if (index - 1 >= lowerBound) { r |= parseHex4Bits(string, index - 1) << 4; } return r; } BN.prototype._parseHex = function _parseHex (number, start, endian) { // Create possibly bigger array to ensure that it fits the number this.length = Math.ceil((number.length - start) / 6); this.words = new Array(this.length); for (var i = 0; i < this.length; i++) { this.words[i] = 0; } // 24-bits chunks var off = 0; var j = 0; var w; if (endian === 'be') { for (i = number.length - 1; i >= start; i -= 2) { w = parseHexByte(number, start, i) << off; this.words[j] |= w & 0x3ffffff; if (off >= 18) { off -= 18; j += 1; this.words[j] |= w >>> 26; } else { off += 8; } } } else { var parseLength = number.length - start; for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { w = parseHexByte(number, start, i) << off; this.words[j] |= w & 0x3ffffff; if (off >= 18) { off -= 18; j += 1; this.words[j] |= w >>> 26; } else { off += 8; } } } this._strip(); }; function parseBase (str, start, end, mul) { var r = 0; var b = 0; var len = Math.min(str.length, end); for (var i = start; i < len; i++) { var c = str.charCodeAt(i) - 48; r *= mul; // 'a' if (c >= 49) { b = c - 49 + 0xa; // 'A' } else if (c >= 17) { b = c - 17 + 0xa; // '0' - '9' } else { b = c; } assert(c >= 0 && b < mul, 'Invalid character'); r += b; } return r; } BN.prototype._parseBase = function _parseBase (number, base, start) { // Initialize as zero this.words = [0]; this.length = 1; // Find length of limb in base for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { limbLen++; } limbLen--; limbPow = (limbPow / base) | 0; var total = number.length - start; var mod = total % limbLen; var end = Math.min(total, total - mod) + start; var word = 0; for (var i = start; i < end; i += limbLen) { word = parseBase(number, i, i + limbLen, base); this.imuln(limbPow); if (this.words[0] + word < 0x4000000) { this.words[0] += word; } else { this._iaddn(word); } } if (mod !== 0) { var pow = 1; word = parseBase(number, i, number.length, base); for (i = 0; i < mod; i++) { pow *= base; } this.imuln(pow); if (this.words[0] + word < 0x4000000) { this.words[0] += word; } else { this._iaddn(word); } } this._strip(); }; BN.prototype.copy = function copy (dest) { dest.words = new Array(this.length); for (var i = 0; i < this.length; i++) { dest.words[i] = this.words[i]; } dest.length = this.length; dest.negative = this.negative; dest.red = this.red; }; function move (dest, src) { dest.words = src.words; dest.length = src.length; dest.negative = src.negative; dest.red = src.red; } BN.prototype._move = function _move (dest) { move(dest, this); }; BN.prototype.clone = function clone () { var r = new BN(null); this.copy(r); return r; }; BN.prototype._expand = function _expand (size) { while (this.length < size) { this.words[this.length++] = 0; } return this; }; // Remove leading `0` from `this` BN.prototype._strip = function strip () { while (this.length > 1 && this.words[this.length - 1] === 0) { this.length--; } return this._normSign(); }; BN.prototype._normSign = function _normSign () { // -0 = 0 if (this.length === 1 && this.words[0] === 0) { this.negative = 0; } return this; }; // Check Symbol.for because not everywhere where Symbol defined // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility if (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function') { try { BN.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspect; } catch (e) { BN.prototype.inspect = inspect; } } else { BN.prototype.inspect = inspect; } function inspect () { return (this.red ? ''; } /* var zeros = []; var groupSizes = []; var groupBases = []; var s = ''; var i = -1; while (++i < BN.wordSize) { zeros[i] = s; s += '0'; } groupSizes[0] = 0; groupSizes[1] = 0; groupBases[0] = 0; groupBases[1] = 0; var base = 2 - 1; while (++base < 36 + 1) { var groupSize = 0; var groupBase = 1; while (groupBase < (1 << BN.wordSize) / base) { groupBase *= base; groupSize += 1; } groupSizes[base] = groupSize; groupBases[base] = groupBase; } */ var zeros = [ '', '0', '00', '000', '0000', '00000', '000000', '0000000', '00000000', '000000000', '0000000000', '00000000000', '000000000000', '0000000000000', '00000000000000', '000000000000000', '0000000000000000', '00000000000000000', '000000000000000000', '0000000000000000000', '00000000000000000000', '000000000000000000000', '0000000000000000000000', '00000000000000000000000', '000000000000000000000000', '0000000000000000000000000' ]; var groupSizes = [ 0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 ]; var groupBases = [ 0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 ]; BN.prototype.toString = function toString (base, padding) { base = base || 10; padding = padding | 0 || 1; var out; if (base === 16 || base === 'hex') { out = ''; var off = 0; var carry = 0; for (var i = 0; i < this.length; i++) { var w = this.words[i]; var word = (((w << off) | carry) & 0xffffff).toString(16); carry = (w >>> (24 - off)) & 0xffffff; off += 2; if (off >= 26) { off -= 26; i--; } if (carry !== 0 || i !== this.length - 1) { out = zeros[6 - word.length] + word + out; } else { out = word + out; } } if (carry !== 0) { out = carry.toString(16) + out; } while (out.length % padding !== 0) { out = '0' + out; } if (this.negative !== 0) { out = '-' + out; } return out; } if (base === (base | 0) && base >= 2 && base <= 36) { // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); var groupSize = groupSizes[base]; // var groupBase = Math.pow(base, groupSize); var groupBase = groupBases[base]; out = ''; var c = this.clone(); c.negative = 0; while (!c.isZero()) { var r = c.modrn(groupBase).toString(base); c = c.idivn(groupBase); if (!c.isZero()) { out = zeros[groupSize - r.length] + r + out; } else { out = r + out; } } if (this.isZero()) { out = '0' + out; } while (out.length % padding !== 0) { out = '0' + out; } if (this.negative !== 0) { out = '-' + out; } return out; } assert(false, 'Base should be between 2 and 36'); }; BN.prototype.toNumber = function toNumber () { var ret = this.words[0]; if (this.length === 2) { ret += this.words[1] * 0x4000000; } else if (this.length === 3 && this.words[2] === 0x01) { // NOTE: at this stage it is known that the top bit is set ret += 0x10000000000000 + (this.words[1] * 0x4000000); } else if (this.length > 2) { assert(false, 'Number can only safely store up to 53 bits'); } return (this.negative !== 0) ? -ret : ret; }; BN.prototype.toJSON = function toJSON () { return this.toString(16, 2); }; if (Buffer) { BN.prototype.toBuffer = function toBuffer (endian, length) { return this.toArrayLike(Buffer, endian, length); }; } BN.prototype.toArray = function toArray (endian, length) { return this.toArrayLike(Array, endian, length); }; var allocate = function allocate (ArrayType, size) { if (ArrayType.allocUnsafe) { return ArrayType.allocUnsafe(size); } return new ArrayType(size); }; BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { this._strip(); var byteLength = this.byteLength(); var reqLength = length || Math.max(1, byteLength); assert(byteLength <= reqLength, 'byte array longer than desired length'); assert(reqLength > 0, 'Requested array length <= 0'); var res = allocate(ArrayType, reqLength); var postfix = endian === 'le' ? 'LE' : 'BE'; this['_toArrayLike' + postfix](res, byteLength); return res; }; BN.prototype._toArrayLikeLE = function _toArrayLikeLE (res, byteLength) { var position = 0; var carry = 0; for (var i = 0, shift = 0; i < this.length; i++) { var word = (this.words[i] << shift) | carry; res[position++] = word & 0xff; if (position < res.length) { res[position++] = (word >> 8) & 0xff; } if (position < res.length) { res[position++] = (word >> 16) & 0xff; } if (shift === 6) { if (position < res.length) { res[position++] = (word >> 24) & 0xff; } carry = 0; shift = 0; } else { carry = word >>> 24; shift += 2; } } if (position < res.length) { res[position++] = carry; while (position < res.length) { res[position++] = 0; } } }; BN.prototype._toArrayLikeBE = function _toArrayLikeBE (res, byteLength) { var position = res.length - 1; var carry = 0; for (var i = 0, shift = 0; i < this.length; i++) { var word = (this.words[i] << shift) | carry; res[position--] = word & 0xff; if (position >= 0) { res[position--] = (word >> 8) & 0xff; } if (position >= 0) { res[position--] = (word >> 16) & 0xff; } if (shift === 6) { if (position >= 0) { res[position--] = (word >> 24) & 0xff; } carry = 0; shift = 0; } else { carry = word >>> 24; shift += 2; } } if (position >= 0) { res[position--] = carry; while (position >= 0) { res[position--] = 0; } } }; if (Math.clz32) { BN.prototype._countBits = function _countBits (w) { return 32 - Math.clz32(w); }; } else { BN.prototype._countBits = function _countBits (w) { var t = w; var r = 0; if (t >= 0x1000) { r += 13; t >>>= 13; } if (t >= 0x40) { r += 7; t >>>= 7; } if (t >= 0x8) { r += 4; t >>>= 4; } if (t >= 0x02) { r += 2; t >>>= 2; } return r + t; }; } BN.prototype._zeroBits = function _zeroBits (w) { // Short-cut if (w === 0) return 26; var t = w; var r = 0; if ((t & 0x1fff) === 0) { r += 13; t >>>= 13; } if ((t & 0x7f) === 0) { r += 7; t >>>= 7; } if ((t & 0xf) === 0) { r += 4; t >>>= 4; } if ((t & 0x3) === 0) { r += 2; t >>>= 2; } if ((t & 0x1) === 0) { r++; } return r; }; // Return number of used bits in a BN BN.prototype.bitLength = function bitLength () { var w = this.words[this.length - 1]; var hi = this._countBits(w); return (this.length - 1) * 26 + hi; }; function toBitArray (num) { var w = new Array(num.bitLength()); for (var bit = 0; bit < w.length; bit++) { var off = (bit / 26) | 0; var wbit = bit % 26; w[bit] = (num.words[off] >>> wbit) & 0x01; } return w; } // Number of trailing zero bits BN.prototype.zeroBits = function zeroBits () { if (this.isZero()) return 0; var r = 0; for (var i = 0; i < this.length; i++) { var b = this._zeroBits(this.words[i]); r += b; if (b !== 26) break; } return r; }; BN.prototype.byteLength = function byteLength () { return Math.ceil(this.bitLength() / 8); }; BN.prototype.toTwos = function toTwos (width) { if (this.negative !== 0) { return this.abs().inotn(width).iaddn(1); } return this.clone(); }; BN.prototype.fromTwos = function fromTwos (width) { if (this.testn(width - 1)) { return this.notn(width).iaddn(1).ineg(); } return this.clone(); }; BN.prototype.isNeg = function isNeg () { return this.negative !== 0; }; // Return negative clone of `this` BN.prototype.neg = function neg () { return this.clone().ineg(); }; BN.prototype.ineg = function ineg () { if (!this.isZero()) { this.negative ^= 1; } return this; }; // Or `num` with `this` in-place BN.prototype.iuor = function iuor (num) { while (this.length < num.length) { this.words[this.length++] = 0; } for (var i = 0; i < num.length; i++) { this.words[i] = this.words[i] | num.words[i]; } return this._strip(); }; BN.prototype.ior = function ior (num) { assert((this.negative | num.negative) === 0); return this.iuor(num); }; // Or `num` with `this` BN.prototype.or = function or (num) { if (this.length > num.length) return this.clone().ior(num); return num.clone().ior(this); }; BN.prototype.uor = function uor (num) { if (this.length > num.length) return this.clone().iuor(num); return num.clone().iuor(this); }; // And `num` with `this` in-place BN.prototype.iuand = function iuand (num) { // b = min-length(num, this) var b; if (this.length > num.length) { b = num; } else { b = this; } for (var i = 0; i < b.length; i++) { this.words[i] = this.words[i] & num.words[i]; } this.length = b.length; return this._strip(); }; BN.prototype.iand = function iand (num) { assert((this.negative | num.negative) === 0); return this.iuand(num); }; // And `num` with `this` BN.prototype.and = function and (num) { if (this.length > num.length) return this.clone().iand(num); return num.clone().iand(this); }; BN.prototype.uand = function uand (num) { if (this.length > num.length) return this.clone().iuand(num); return num.clone().iuand(this); }; // Xor `num` with `this` in-place BN.prototype.iuxor = function iuxor (num) { // a.length > b.length var a; var b; if (this.length > num.length) { a = this; b = num; } else { a = num; b = this; } for (var i = 0; i < b.length; i++) { this.words[i] = a.words[i] ^ b.words[i]; } if (this !== a) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } this.length = a.length; return this._strip(); }; BN.prototype.ixor = function ixor (num) { assert((this.negative | num.negative) === 0); return this.iuxor(num); }; // Xor `num` with `this` BN.prototype.xor = function xor (num) { if (this.length > num.length) return this.clone().ixor(num); return num.clone().ixor(this); }; BN.prototype.uxor = function uxor (num) { if (this.length > num.length) return this.clone().iuxor(num); return num.clone().iuxor(this); }; // Not ``this`` with ``width`` bitwidth BN.prototype.inotn = function inotn (width) { assert(typeof width === 'number' && width >= 0); var bytesNeeded = Math.ceil(width / 26) | 0; var bitsLeft = width % 26; // Extend the buffer with leading zeroes this._expand(bytesNeeded); if (bitsLeft > 0) { bytesNeeded--; } // Handle complete words for (var i = 0; i < bytesNeeded; i++) { this.words[i] = ~this.words[i] & 0x3ffffff; } // Handle the residue if (bitsLeft > 0) { this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); } // And remove leading zeroes return this._strip(); }; BN.prototype.notn = function notn (width) { return this.clone().inotn(width); }; // Set `bit` of `this` BN.prototype.setn = function setn (bit, val) { assert(typeof bit === 'number' && bit >= 0); var off = (bit / 26) | 0; var wbit = bit % 26; this._expand(off + 1); if (val) { this.words[off] = this.words[off] | (1 << wbit); } else { this.words[off] = this.words[off] & ~(1 << wbit); } return this._strip(); }; // Add `num` to `this` in-place BN.prototype.iadd = function iadd (num) { var r; // negative + positive if (this.negative !== 0 && num.negative === 0) { this.negative = 0; r = this.isub(num); this.negative ^= 1; return this._normSign(); // positive + negative } else if (this.negative === 0 && num.negative !== 0) { num.negative = 0; r = this.isub(num); num.negative = 1; return r._normSign(); } // a.length > b.length var a, b; if (this.length > num.length) { a = this; b = num; } else { a = num; b = this; } var carry = 0; for (var i = 0; i < b.length; i++) { r = (a.words[i] | 0) + (b.words[i] | 0) + carry; this.words[i] = r & 0x3ffffff; carry = r >>> 26; } for (; carry !== 0 && i < a.length; i++) { r = (a.words[i] | 0) + carry; this.words[i] = r & 0x3ffffff; carry = r >>> 26; } this.length = a.length; if (carry !== 0) { this.words[this.length] = carry; this.length++; // Copy the rest of the words } else if (a !== this) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } return this; }; // Add `num` to `this` BN.prototype.add = function add (num) { var res; if (num.negative !== 0 && this.negative === 0) { num.negative = 0; res = this.sub(num); num.negative ^= 1; return res; } else if (num.negative === 0 && this.negative !== 0) { this.negative = 0; res = num.sub(this); this.negative = 1; return res; } if (this.length > num.length) return this.clone().iadd(num); return num.clone().iadd(this); }; // Subtract `num` from `this` in-place BN.prototype.isub = function isub (num) { // this - (-num) = this + num if (num.negative !== 0) { num.negative = 0; var r = this.iadd(num); num.negative = 1; return r._normSign(); // -this - num = -(this + num) } else if (this.negative !== 0) { this.negative = 0; this.iadd(num); this.negative = 1; return this._normSign(); } // At this point both numbers are positive var cmp = this.cmp(num); // Optimization - zeroify if (cmp === 0) { this.negative = 0; this.length = 1; this.words[0] = 0; return this; } // a > b var a, b; if (cmp > 0) { a = this; b = num; } else { a = num; b = this; } var carry = 0; for (var i = 0; i < b.length; i++) { r = (a.words[i] | 0) - (b.words[i] | 0) + carry; carry = r >> 26; this.words[i] = r & 0x3ffffff; } for (; carry !== 0 && i < a.length; i++) { r = (a.words[i] | 0) + carry; carry = r >> 26; this.words[i] = r & 0x3ffffff; } // Copy rest of the words if (carry === 0 && i < a.length && a !== this) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } this.length = Math.max(this.length, i); if (a !== this) { this.negative = 1; } return this._strip(); }; // Subtract `num` from `this` BN.prototype.sub = function sub (num) { return this.clone().isub(num); }; function smallMulTo (self, num, out) { out.negative = num.negative ^ self.negative; var len = (self.length + num.length) | 0; out.length = len; len = (len - 1) | 0; // Peel one iteration (compiler can't do it, because of code complexity) var a = self.words[0] | 0; var b = num.words[0] | 0; var r = a * b; var lo = r & 0x3ffffff; var carry = (r / 0x4000000) | 0; out.words[0] = lo; for (var k = 1; k < len; k++) { // Sum all words with the same `i + j = k` and accumulate `ncarry`, // note that ncarry could be >= 0x3ffffff var ncarry = carry >>> 26; var rword = carry & 0x3ffffff; var maxJ = Math.min(k, num.length - 1); for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { var i = (k - j) | 0; a = self.words[i] | 0; b = num.words[j] | 0; r = a * b + rword; ncarry += (r / 0x4000000) | 0; rword = r & 0x3ffffff; } out.words[k] = rword | 0; carry = ncarry | 0; } if (carry !== 0) { out.words[k] = carry | 0; } else { out.length--; } return out._strip(); } // TODO(indutny): it may be reasonable to omit it for users who don't need // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit // multiplication (like elliptic secp256k1). var comb10MulTo = function comb10MulTo (self, num, out) { var a = self.words; var b = num.words; var o = out.words; var c = 0; var lo; var mid; var hi; var a0 = a[0] | 0; var al0 = a0 & 0x1fff; var ah0 = a0 >>> 13; var a1 = a[1] | 0; var al1 = a1 & 0x1fff; var ah1 = a1 >>> 13; var a2 = a[2] | 0; var al2 = a2 & 0x1fff; var ah2 = a2 >>> 13; var a3 = a[3] | 0; var al3 = a3 & 0x1fff; var ah3 = a3 >>> 13; var a4 = a[4] | 0; var al4 = a4 & 0x1fff; var ah4 = a4 >>> 13; var a5 = a[5] | 0; var al5 = a5 & 0x1fff; var ah5 = a5 >>> 13; var a6 = a[6] | 0; var al6 = a6 & 0x1fff; var ah6 = a6 >>> 13; var a7 = a[7] | 0; var al7 = a7 & 0x1fff; var ah7 = a7 >>> 13; var a8 = a[8] | 0; var al8 = a8 & 0x1fff; var ah8 = a8 >>> 13; var a9 = a[9] | 0; var al9 = a9 & 0x1fff; var ah9 = a9 >>> 13; var b0 = b[0] | 0; var bl0 = b0 & 0x1fff; var bh0 = b0 >>> 13; var b1 = b[1] | 0; var bl1 = b1 & 0x1fff; var bh1 = b1 >>> 13; var b2 = b[2] | 0; var bl2 = b2 & 0x1fff; var bh2 = b2 >>> 13; var b3 = b[3] | 0; var bl3 = b3 & 0x1fff; var bh3 = b3 >>> 13; var b4 = b[4] | 0; var bl4 = b4 & 0x1fff; var bh4 = b4 >>> 13; var b5 = b[5] | 0; var bl5 = b5 & 0x1fff; var bh5 = b5 >>> 13; var b6 = b[6] | 0; var bl6 = b6 & 0x1fff; var bh6 = b6 >>> 13; var b7 = b[7] | 0; var bl7 = b7 & 0x1fff; var bh7 = b7 >>> 13; var b8 = b[8] | 0; var bl8 = b8 & 0x1fff; var bh8 = b8 >>> 13; var b9 = b[9] | 0; var bl9 = b9 & 0x1fff; var bh9 = b9 >>> 13; out.negative = self.negative ^ num.negative; out.length = 19; /* k = 0 */ lo = Math.imul(al0, bl0); mid = Math.imul(al0, bh0); mid = (mid + Math.imul(ah0, bl0)) | 0; hi = Math.imul(ah0, bh0); var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; w0 &= 0x3ffffff; /* k = 1 */ lo = Math.imul(al1, bl0); mid = Math.imul(al1, bh0); mid = (mid + Math.imul(ah1, bl0)) | 0; hi = Math.imul(ah1, bh0); lo = (lo + Math.imul(al0, bl1)) | 0; mid = (mid + Math.imul(al0, bh1)) | 0; mid = (mid + Math.imul(ah0, bl1)) | 0; hi = (hi + Math.imul(ah0, bh1)) | 0; var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; w1 &= 0x3ffffff; /* k = 2 */ lo = Math.imul(al2, bl0); mid = Math.imul(al2, bh0); mid = (mid + Math.imul(ah2, bl0)) | 0; hi = Math.imul(ah2, bh0); lo = (lo + Math.imul(al1, bl1)) | 0; mid = (mid + Math.imul(al1, bh1)) | 0; mid = (mid + Math.imul(ah1, bl1)) | 0; hi = (hi + Math.imul(ah1, bh1)) | 0; lo = (lo + Math.imul(al0, bl2)) | 0; mid = (mid + Math.imul(al0, bh2)) | 0; mid = (mid + Math.imul(ah0, bl2)) | 0; hi = (hi + Math.imul(ah0, bh2)) | 0; var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; w2 &= 0x3ffffff; /* k = 3 */ lo = Math.imul(al3, bl0); mid = Math.imul(al3, bh0); mid = (mid + Math.imul(ah3, bl0)) | 0; hi = Math.imul(ah3, bh0); lo = (lo + Math.imul(al2, bl1)) | 0; mid = (mid + Math.imul(al2, bh1)) | 0; mid = (mid + Math.imul(ah2, bl1)) | 0; hi = (hi + Math.imul(ah2, bh1)) | 0; lo = (lo + Math.imul(al1, bl2)) | 0; mid = (mid + Math.imul(al1, bh2)) | 0; mid = (mid + Math.imul(ah1, bl2)) | 0; hi = (hi + Math.imul(ah1, bh2)) | 0; lo = (lo + Math.imul(al0, bl3)) | 0; mid = (mid + Math.imul(al0, bh3)) | 0; mid = (mid + Math.imul(ah0, bl3)) | 0; hi = (hi + Math.imul(ah0, bh3)) | 0; var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; w3 &= 0x3ffffff; /* k = 4 */ lo = Math.imul(al4, bl0); mid = Math.imul(al4, bh0); mid = (mid + Math.imul(ah4, bl0)) | 0; hi = Math.imul(ah4, bh0); lo = (lo + Math.imul(al3, bl1)) | 0; mid = (mid + Math.imul(al3, bh1)) | 0; mid = (mid + Math.imul(ah3, bl1)) | 0; hi = (hi + Math.imul(ah3, bh1)) | 0; lo = (lo + Math.imul(al2, bl2)) | 0; mid = (mid + Math.imul(al2, bh2)) | 0; mid = (mid + Math.imul(ah2, bl2)) | 0; hi = (hi + Math.imul(ah2, bh2)) | 0; lo = (lo + Math.imul(al1, bl3)) | 0; mid = (mid + Math.imul(al1, bh3)) | 0; mid = (mid + Math.imul(ah1, bl3)) | 0; hi = (hi + Math.imul(ah1, bh3)) | 0; lo = (lo + Math.imul(al0, bl4)) | 0; mid = (mid + Math.imul(al0, bh4)) | 0; mid = (mid + Math.imul(ah0, bl4)) | 0; hi = (hi + Math.imul(ah0, bh4)) | 0; var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; w4 &= 0x3ffffff; /* k = 5 */ lo = Math.imul(al5, bl0); mid = Math.imul(al5, bh0); mid = (mid + Math.imul(ah5, bl0)) | 0; hi = Math.imul(ah5, bh0); lo = (lo + Math.imul(al4, bl1)) | 0; mid = (mid + Math.imul(al4, bh1)) | 0; mid = (mid + Math.imul(ah4, bl1)) | 0; hi = (hi + Math.imul(ah4, bh1)) | 0; lo = (lo + Math.imul(al3, bl2)) | 0; mid = (mid + Math.imul(al3, bh2)) | 0; mid = (mid + Math.imul(ah3, bl2)) | 0; hi = (hi + Math.imul(ah3, bh2)) | 0; lo = (lo + Math.imul(al2, bl3)) | 0; mid = (mid + Math.imul(al2, bh3)) | 0; mid = (mid + Math.imul(ah2, bl3)) | 0; hi = (hi + Math.imul(ah2, bh3)) | 0; lo = (lo + Math.imul(al1, bl4)) | 0; mid = (mid + Math.imul(al1, bh4)) | 0; mid = (mid + Math.imul(ah1, bl4)) | 0; hi = (hi + Math.imul(ah1, bh4)) | 0; lo = (lo + Math.imul(al0, bl5)) | 0; mid = (mid + Math.imul(al0, bh5)) | 0; mid = (mid + Math.imul(ah0, bl5)) | 0; hi = (hi + Math.imul(ah0, bh5)) | 0; var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; w5 &= 0x3ffffff; /* k = 6 */ lo = Math.imul(al6, bl0); mid = Math.imul(al6, bh0); mid = (mid + Math.imul(ah6, bl0)) | 0; hi = Math.imul(ah6, bh0); lo = (lo + Math.imul(al5, bl1)) | 0; mid = (mid + Math.imul(al5, bh1)) | 0; mid = (mid + Math.imul(ah5, bl1)) | 0; hi = (hi + Math.imul(ah5, bh1)) | 0; lo = (lo + Math.imul(al4, bl2)) | 0; mid = (mid + Math.imul(al4, bh2)) | 0; mid = (mid + Math.imul(ah4, bl2)) | 0; hi = (hi + Math.imul(ah4, bh2)) | 0; lo = (lo + Math.imul(al3, bl3)) | 0; mid = (mid + Math.imul(al3, bh3)) | 0; mid = (mid + Math.imul(ah3, bl3)) | 0; hi = (hi + Math.imul(ah3, bh3)) | 0; lo = (lo + Math.imul(al2, bl4)) | 0; mid = (mid + Math.imul(al2, bh4)) | 0; mid = (mid + Math.imul(ah2, bl4)) | 0; hi = (hi + Math.imul(ah2, bh4)) | 0; lo = (lo + Math.imul(al1, bl5)) | 0; mid = (mid + Math.imul(al1, bh5)) | 0; mid = (mid + Math.imul(ah1, bl5)) | 0; hi = (hi + Math.imul(ah1, bh5)) | 0; lo = (lo + Math.imul(al0, bl6)) | 0; mid = (mid + Math.imul(al0, bh6)) | 0; mid = (mid + Math.imul(ah0, bl6)) | 0; hi = (hi + Math.imul(ah0, bh6)) | 0; var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; w6 &= 0x3ffffff; /* k = 7 */ lo = Math.imul(al7, bl0); mid = Math.imul(al7, bh0); mid = (mid + Math.imul(ah7, bl0)) | 0; hi = Math.imul(ah7, bh0); lo = (lo + Math.imul(al6, bl1)) | 0; mid = (mid + Math.imul(al6, bh1)) | 0; mid = (mid + Math.imul(ah6, bl1)) | 0; hi = (hi + Math.imul(ah6, bh1)) | 0; lo = (lo + Math.imul(al5, bl2)) | 0; mid = (mid + Math.imul(al5, bh2)) | 0; mid = (mid + Math.imul(ah5, bl2)) | 0; hi = (hi + Math.imul(ah5, bh2)) | 0; lo = (lo + Math.imul(al4, bl3)) | 0; mid = (mid + Math.imul(al4, bh3)) | 0; mid = (mid + Math.imul(ah4, bl3)) | 0; hi = (hi + Math.imul(ah4, bh3)) | 0; lo = (lo + Math.imul(al3, bl4)) | 0; mid = (mid + Math.imul(al3, bh4)) | 0; mid = (mid + Math.imul(ah3, bl4)) | 0; hi = (hi + Math.imul(ah3, bh4)) | 0; lo = (lo + Math.imul(al2, bl5)) | 0; mid = (mid + Math.imul(al2, bh5)) | 0; mid = (mid + Math.imul(ah2, bl5)) | 0; hi = (hi + Math.imul(ah2, bh5)) | 0; lo = (lo + Math.imul(al1, bl6)) | 0; mid = (mid + Math.imul(al1, bh6)) | 0; mid = (mid + Math.imul(ah1, bl6)) | 0; hi = (hi + Math.imul(ah1, bh6)) | 0; lo = (lo + Math.imul(al0, bl7)) | 0; mid = (mid + Math.imul(al0, bh7)) | 0; mid = (mid + Math.imul(ah0, bl7)) | 0; hi = (hi + Math.imul(ah0, bh7)) | 0; var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; w7 &= 0x3ffffff; /* k = 8 */ lo = Math.imul(al8, bl0); mid = Math.imul(al8, bh0); mid = (mid + Math.imul(ah8, bl0)) | 0; hi = Math.imul(ah8, bh0); lo = (lo + Math.imul(al7, bl1)) | 0; mid = (mid + Math.imul(al7, bh1)) | 0; mid = (mid + Math.imul(ah7, bl1)) | 0; hi = (hi + Math.imul(ah7, bh1)) | 0; lo = (lo + Math.imul(al6, bl2)) | 0; mid = (mid + Math.imul(al6, bh2)) | 0; mid = (mid + Math.imul(ah6, bl2)) | 0; hi = (hi + Math.imul(ah6, bh2)) | 0; lo = (lo + Math.imul(al5, bl3)) | 0; mid = (mid + Math.imul(al5, bh3)) | 0; mid = (mid + Math.imul(ah5, bl3)) | 0; hi = (hi + Math.imul(ah5, bh3)) | 0; lo = (lo + Math.imul(al4, bl4)) | 0; mid = (mid + Math.imul(al4, bh4)) | 0; mid = (mid + Math.imul(ah4, bl4)) | 0; hi = (hi + Math.imul(ah4, bh4)) | 0; lo = (lo + Math.imul(al3, bl5)) | 0; mid = (mid + Math.imul(al3, bh5)) | 0; mid = (mid + Math.imul(ah3, bl5)) | 0; hi = (hi + Math.imul(ah3, bh5)) | 0; lo = (lo + Math.imul(al2, bl6)) | 0; mid = (mid + Math.imul(al2, bh6)) | 0; mid = (mid + Math.imul(ah2, bl6)) | 0; hi = (hi + Math.imul(ah2, bh6)) | 0; lo = (lo + Math.imul(al1, bl7)) | 0; mid = (mid + Math.imul(al1, bh7)) | 0; mid = (mid + Math.imul(ah1, bl7)) | 0; hi = (hi + Math.imul(ah1, bh7)) | 0; lo = (lo + Math.imul(al0, bl8)) | 0; mid = (mid + Math.imul(al0, bh8)) | 0; mid = (mid + Math.imul(ah0, bl8)) | 0; hi = (hi + Math.imul(ah0, bh8)) | 0; var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; w8 &= 0x3ffffff; /* k = 9 */ lo = Math.imul(al9, bl0); mid = Math.imul(al9, bh0); mid = (mid + Math.imul(ah9, bl0)) | 0; hi = Math.imul(ah9, bh0); lo = (lo + Math.imul(al8, bl1)) | 0; mid = (mid + Math.imul(al8, bh1)) | 0; mid = (mid + Math.imul(ah8, bl1)) | 0; hi = (hi + Math.imul(ah8, bh1)) | 0; lo = (lo + Math.imul(al7, bl2)) | 0; mid = (mid + Math.imul(al7, bh2)) | 0; mid = (mid + Math.imul(ah7, bl2)) | 0; hi = (hi + Math.imul(ah7, bh2)) | 0; lo = (lo + Math.imul(al6, bl3)) | 0; mid = (mid + Math.imul(al6, bh3)) | 0; mid = (mid + Math.imul(ah6, bl3)) | 0; hi = (hi + Math.imul(ah6, bh3)) | 0; lo = (lo + Math.imul(al5, bl4)) | 0; mid = (mid + Math.imul(al5, bh4)) | 0; mid = (mid + Math.imul(ah5, bl4)) | 0; hi = (hi + Math.imul(ah5, bh4)) | 0; lo = (lo + Math.imul(al4, bl5)) | 0; mid = (mid + Math.imul(al4, bh5)) | 0; mid = (mid + Math.imul(ah4, bl5)) | 0; hi = (hi + Math.imul(ah4, bh5)) | 0; lo = (lo + Math.imul(al3, bl6)) | 0; mid = (mid + Math.imul(al3, bh6)) | 0; mid = (mid + Math.imul(ah3, bl6)) | 0; hi = (hi + Math.imul(ah3, bh6)) | 0; lo = (lo + Math.imul(al2, bl7)) | 0; mid = (mid + Math.imul(al2, bh7)) | 0; mid = (mid + Math.imul(ah2, bl7)) | 0; hi = (hi + Math.imul(ah2, bh7)) | 0; lo = (lo + Math.imul(al1, bl8)) | 0; mid = (mid + Math.imul(al1, bh8)) | 0; mid = (mid + Math.imul(ah1, bl8)) | 0; hi = (hi + Math.imul(ah1, bh8)) | 0; lo = (lo + Math.imul(al0, bl9)) | 0; mid = (mid + Math.imul(al0, bh9)) | 0; mid = (mid + Math.imul(ah0, bl9)) | 0; hi = (hi + Math.imul(ah0, bh9)) | 0; var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; w9 &= 0x3ffffff; /* k = 10 */ lo = Math.imul(al9, bl1); mid = Math.imul(al9, bh1); mid = (mid + Math.imul(ah9, bl1)) | 0; hi = Math.imul(ah9, bh1); lo = (lo + Math.imul(al8, bl2)) | 0; mid = (mid + Math.imul(al8, bh2)) | 0; mid = (mid + Math.imul(ah8, bl2)) | 0; hi = (hi + Math.imul(ah8, bh2)) | 0; lo = (lo + Math.imul(al7, bl3)) | 0; mid = (mid + Math.imul(al7, bh3)) | 0; mid = (mid + Math.imul(ah7, bl3)) | 0; hi = (hi + Math.imul(ah7, bh3)) | 0; lo = (lo + Math.imul(al6, bl4)) | 0; mid = (mid + Math.imul(al6, bh4)) | 0; mid = (mid + Math.imul(ah6, bl4)) | 0; hi = (hi + Math.imul(ah6, bh4)) | 0; lo = (lo + Math.imul(al5, bl5)) | 0; mid = (mid + Math.imul(al5, bh5)) | 0; mid = (mid + Math.imul(ah5, bl5)) | 0; hi = (hi + Math.imul(ah5, bh5)) | 0; lo = (lo + Math.imul(al4, bl6)) | 0; mid = (mid + Math.imul(al4, bh6)) | 0; mid = (mid + Math.imul(ah4, bl6)) | 0; hi = (hi + Math.imul(ah4, bh6)) | 0; lo = (lo + Math.imul(al3, bl7)) | 0; mid = (mid + Math.imul(al3, bh7)) | 0; mid = (mid + Math.imul(ah3, bl7)) | 0; hi = (hi + Math.imul(ah3, bh7)) | 0; lo = (lo + Math.imul(al2, bl8)) | 0; mid = (mid + Math.imul(al2, bh8)) | 0; mid = (mid + Math.imul(ah2, bl8)) | 0; hi = (hi + Math.imul(ah2, bh8)) | 0; lo = (lo + Math.imul(al1, bl9)) | 0; mid = (mid + Math.imul(al1, bh9)) | 0; mid = (mid + Math.imul(ah1, bl9)) | 0; hi = (hi + Math.imul(ah1, bh9)) | 0; var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; w10 &= 0x3ffffff; /* k = 11 */ lo = Math.imul(al9, bl2); mid = Math.imul(al9, bh2); mid = (mid + Math.imul(ah9, bl2)) | 0; hi = Math.imul(ah9, bh2); lo = (lo + Math.imul(al8, bl3)) | 0; mid = (mid + Math.imul(al8, bh3)) | 0; mid = (mid + Math.imul(ah8, bl3)) | 0; hi = (hi + Math.imul(ah8, bh3)) | 0; lo = (lo + Math.imul(al7, bl4)) | 0; mid = (mid + Math.imul(al7, bh4)) | 0; mid = (mid + Math.imul(ah7, bl4)) | 0; hi = (hi + Math.imul(ah7, bh4)) | 0; lo = (lo + Math.imul(al6, bl5)) | 0; mid = (mid + Math.imul(al6, bh5)) | 0; mid = (mid + Math.imul(ah6, bl5)) | 0; hi = (hi + Math.imul(ah6, bh5)) | 0; lo = (lo + Math.imul(al5, bl6)) | 0; mid = (mid + Math.imul(al5, bh6)) | 0; mid = (mid + Math.imul(ah5, bl6)) | 0; hi = (hi + Math.imul(ah5, bh6)) | 0; lo = (lo + Math.imul(al4, bl7)) | 0; mid = (mid + Math.imul(al4, bh7)) | 0; mid = (mid + Math.imul(ah4, bl7)) | 0; hi = (hi + Math.imul(ah4, bh7)) | 0; lo = (lo + Math.imul(al3, bl8)) | 0; mid = (mid + Math.imul(al3, bh8)) | 0; mid = (mid + Math.imul(ah3, bl8)) | 0; hi = (hi + Math.imul(ah3, bh8)) | 0; lo = (lo + Math.imul(al2, bl9)) | 0; mid = (mid + Math.imul(al2, bh9)) | 0; mid = (mid + Math.imul(ah2, bl9)) | 0; hi = (hi + Math.imul(ah2, bh9)) | 0; var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; w11 &= 0x3ffffff; /* k = 12 */ lo = Math.imul(al9, bl3); mid = Math.imul(al9, bh3); mid = (mid + Math.imul(ah9, bl3)) | 0; hi = Math.imul(ah9, bh3); lo = (lo + Math.imul(al8, bl4)) | 0; mid = (mid + Math.imul(al8, bh4)) | 0; mid = (mid + Math.imul(ah8, bl4)) | 0; hi = (hi + Math.imul(ah8, bh4)) | 0; lo = (lo + Math.imul(al7, bl5)) | 0; mid = (mid + Math.imul(al7, bh5)) | 0; mid = (mid + Math.imul(ah7, bl5)) | 0; hi = (hi + Math.imul(ah7, bh5)) | 0; lo = (lo + Math.imul(al6, bl6)) | 0; mid = (mid + Math.imul(al6, bh6)) | 0; mid = (mid + Math.imul(ah6, bl6)) | 0; hi = (hi + Math.imul(ah6, bh6)) | 0; lo = (lo + Math.imul(al5, bl7)) | 0; mid = (mid + Math.imul(al5, bh7)) | 0; mid = (mid + Math.imul(ah5, bl7)) | 0; hi = (hi + Math.imul(ah5, bh7)) | 0; lo = (lo + Math.imul(al4, bl8)) | 0; mid = (mid + Math.imul(al4, bh8)) | 0; mid = (mid + Math.imul(ah4, bl8)) | 0; hi = (hi + Math.imul(ah4, bh8)) | 0; lo = (lo + Math.imul(al3, bl9)) | 0; mid = (mid + Math.imul(al3, bh9)) | 0; mid = (mid + Math.imul(ah3, bl9)) | 0; hi = (hi + Math.imul(ah3, bh9)) | 0; var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; w12 &= 0x3ffffff; /* k = 13 */ lo = Math.imul(al9, bl4); mid = Math.imul(al9, bh4); mid = (mid + Math.imul(ah9, bl4)) | 0; hi = Math.imul(ah9, bh4); lo = (lo + Math.imul(al8, bl5)) | 0; mid = (mid + Math.imul(al8, bh5)) | 0; mid = (mid + Math.imul(ah8, bl5)) | 0; hi = (hi + Math.imul(ah8, bh5)) | 0; lo = (lo + Math.imul(al7, bl6)) | 0; mid = (mid + Math.imul(al7, bh6)) | 0; mid = (mid + Math.imul(ah7, bl6)) | 0; hi = (hi + Math.imul(ah7, bh6)) | 0; lo = (lo + Math.imul(al6, bl7)) | 0; mid = (mid + Math.imul(al6, bh7)) | 0; mid = (mid + Math.imul(ah6, bl7)) | 0; hi = (hi + Math.imul(ah6, bh7)) | 0; lo = (lo + Math.imul(al5, bl8)) | 0; mid = (mid + Math.imul(al5, bh8)) | 0; mid = (mid + Math.imul(ah5, bl8)) | 0; hi = (hi + Math.imul(ah5, bh8)) | 0; lo = (lo + Math.imul(al4, bl9)) | 0; mid = (mid + Math.imul(al4, bh9)) | 0; mid = (mid + Math.imul(ah4, bl9)) | 0; hi = (hi + Math.imul(ah4, bh9)) | 0; var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; w13 &= 0x3ffffff; /* k = 14 */ lo = Math.imul(al9, bl5); mid = Math.imul(al9, bh5); mid = (mid + Math.imul(ah9, bl5)) | 0; hi = Math.imul(ah9, bh5); lo = (lo + Math.imul(al8, bl6)) | 0; mid = (mid + Math.imul(al8, bh6)) | 0; mid = (mid + Math.imul(ah8, bl6)) | 0; hi = (hi + Math.imul(ah8, bh6)) | 0; lo = (lo + Math.imul(al7, bl7)) | 0; mid = (mid + Math.imul(al7, bh7)) | 0; mid = (mid + Math.imul(ah7, bl7)) | 0; hi = (hi + Math.imul(ah7, bh7)) | 0; lo = (lo + Math.imul(al6, bl8)) | 0; mid = (mid + Math.imul(al6, bh8)) | 0; mid = (mid + Math.imul(ah6, bl8)) | 0; hi = (hi + Math.imul(ah6, bh8)) | 0; lo = (lo + Math.imul(al5, bl9)) | 0; mid = (mid + Math.imul(al5, bh9)) | 0; mid = (mid + Math.imul(ah5, bl9)) | 0; hi = (hi + Math.imul(ah5, bh9)) | 0; var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; w14 &= 0x3ffffff; /* k = 15 */ lo = Math.imul(al9, bl6); mid = Math.imul(al9, bh6); mid = (mid + Math.imul(ah9, bl6)) | 0; hi = Math.imul(ah9, bh6); lo = (lo + Math.imul(al8, bl7)) | 0; mid = (mid + Math.imul(al8, bh7)) | 0; mid = (mid + Math.imul(ah8, bl7)) | 0; hi = (hi + Math.imul(ah8, bh7)) | 0; lo = (lo + Math.imul(al7, bl8)) | 0; mid = (mid + Math.imul(al7, bh8)) | 0; mid = (mid + Math.imul(ah7, bl8)) | 0; hi = (hi + Math.imul(ah7, bh8)) | 0; lo = (lo + Math.imul(al6, bl9)) | 0; mid = (mid + Math.imul(al6, bh9)) | 0; mid = (mid + Math.imul(ah6, bl9)) | 0; hi = (hi + Math.imul(ah6, bh9)) | 0; var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; w15 &= 0x3ffffff; /* k = 16 */ lo = Math.imul(al9, bl7); mid = Math.imul(al9, bh7); mid = (mid + Math.imul(ah9, bl7)) | 0; hi = Math.imul(ah9, bh7); lo = (lo + Math.imul(al8, bl8)) | 0; mid = (mid + Math.imul(al8, bh8)) | 0; mid = (mid + Math.imul(ah8, bl8)) | 0; hi = (hi + Math.imul(ah8, bh8)) | 0; lo = (lo + Math.imul(al7, bl9)) | 0; mid = (mid + Math.imul(al7, bh9)) | 0; mid = (mid + Math.imul(ah7, bl9)) | 0; hi = (hi + Math.imul(ah7, bh9)) | 0; var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; w16 &= 0x3ffffff; /* k = 17 */ lo = Math.imul(al9, bl8); mid = Math.imul(al9, bh8); mid = (mid + Math.imul(ah9, bl8)) | 0; hi = Math.imul(ah9, bh8); lo = (lo + Math.imul(al8, bl9)) | 0; mid = (mid + Math.imul(al8, bh9)) | 0; mid = (mid + Math.imul(ah8, bl9)) | 0; hi = (hi + Math.imul(ah8, bh9)) | 0; var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; w17 &= 0x3ffffff; /* k = 18 */ lo = Math.imul(al9, bl9); mid = Math.imul(al9, bh9); mid = (mid + Math.imul(ah9, bl9)) | 0; hi = Math.imul(ah9, bh9); var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; w18 &= 0x3ffffff; o[0] = w0; o[1] = w1; o[2] = w2; o[3] = w3; o[4] = w4; o[5] = w5; o[6] = w6; o[7] = w7; o[8] = w8; o[9] = w9; o[10] = w10; o[11] = w11; o[12] = w12; o[13] = w13; o[14] = w14; o[15] = w15; o[16] = w16; o[17] = w17; o[18] = w18; if (c !== 0) { o[19] = c; out.length++; } return out; }; // Polyfill comb if (!Math.imul) { comb10MulTo = smallMulTo; } function bigMulTo (self, num, out) { out.negative = num.negative ^ self.negative; out.length = self.length + num.length; var carry = 0; var hncarry = 0; for (var k = 0; k < out.length - 1; k++) { // Sum all words with the same `i + j = k` and accumulate `ncarry`, // note that ncarry could be >= 0x3ffffff var ncarry = hncarry; hncarry = 0; var rword = carry & 0x3ffffff; var maxJ = Math.min(k, num.length - 1); for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { var i = k - j; var a = self.words[i] | 0; var b = num.words[j] | 0; var r = a * b; var lo = r & 0x3ffffff; ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; lo = (lo + rword) | 0; rword = lo & 0x3ffffff; ncarry = (ncarry + (lo >>> 26)) | 0; hncarry += ncarry >>> 26; ncarry &= 0x3ffffff; } out.words[k] = rword; carry = ncarry; ncarry = hncarry; } if (carry !== 0) { out.words[k] = carry; } else { out.length--; } return out._strip(); } function jumboMulTo (self, num, out) { // Temporary disable, see https://github.com/indutny/bn.js/issues/211 // var fftm = new FFTM(); // return fftm.mulp(self, num, out); return bigMulTo(self, num, out); } BN.prototype.mulTo = function mulTo (num, out) { var res; var len = this.length + num.length; if (this.length === 10 && num.length === 10) { res = comb10MulTo(this, num, out); } else if (len < 63) { res = smallMulTo(this, num, out); } else if (len < 1024) { res = bigMulTo(this, num, out); } else { res = jumboMulTo(this, num, out); } return res; }; // Cooley-Tukey algorithm for FFT // slightly revisited to rely on looping instead of recursion function FFTM (x, y) { this.x = x; this.y = y; } FFTM.prototype.makeRBT = function makeRBT (N) { var t = new Array(N); var l = BN.prototype._countBits(N) - 1; for (var i = 0; i < N; i++) { t[i] = this.revBin(i, l, N); } return t; }; // Returns binary-reversed representation of `x` FFTM.prototype.revBin = function revBin (x, l, N) { if (x === 0 || x === N - 1) return x; var rb = 0; for (var i = 0; i < l; i++) { rb |= (x & 1) << (l - i - 1); x >>= 1; } return rb; }; // Performs "tweedling" phase, therefore 'emulating' // behaviour of the recursive algorithm FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { for (var i = 0; i < N; i++) { rtws[i] = rws[rbt[i]]; itws[i] = iws[rbt[i]]; } }; FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { this.permute(rbt, rws, iws, rtws, itws, N); for (var s = 1; s < N; s <<= 1) { var l = s << 1; var rtwdf = Math.cos(2 * Math.PI / l); var itwdf = Math.sin(2 * Math.PI / l); for (var p = 0; p < N; p += l) { var rtwdf_ = rtwdf; var itwdf_ = itwdf; for (var j = 0; j < s; j++) { var re = rtws[p + j]; var ie = itws[p + j]; var ro = rtws[p + j + s]; var io = itws[p + j + s]; var rx = rtwdf_ * ro - itwdf_ * io; io = rtwdf_ * io + itwdf_ * ro; ro = rx; rtws[p + j] = re + ro; itws[p + j] = ie + io; rtws[p + j + s] = re - ro; itws[p + j + s] = ie - io; /* jshint maxdepth : false */ if (j !== l) { rx = rtwdf * rtwdf_ - itwdf * itwdf_; itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; rtwdf_ = rx; } } } } }; FFTM.prototype.guessLen13b = function guessLen13b (n, m) { var N = Math.max(m, n) | 1; var odd = N & 1; var i = 0; for (N = N / 2 | 0; N; N = N >>> 1) { i++; } return 1 << i + 1 + odd; }; FFTM.prototype.conjugate = function conjugate (rws, iws, N) { if (N <= 1) return; for (var i = 0; i < N / 2; i++) { var t = rws[i]; rws[i] = rws[N - i - 1]; rws[N - i - 1] = t; t = iws[i]; iws[i] = -iws[N - i - 1]; iws[N - i - 1] = -t; } }; FFTM.prototype.normalize13b = function normalize13b (ws, N) { var carry = 0; for (var i = 0; i < N / 2; i++) { var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + Math.round(ws[2 * i] / N) + carry; ws[i] = w & 0x3ffffff; if (w < 0x4000000) { carry = 0; } else { carry = w / 0x4000000 | 0; } } return ws; }; FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { var carry = 0; for (var i = 0; i < len; i++) { carry = carry + (ws[i] | 0); rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; } // Pad with zeroes for (i = 2 * len; i < N; ++i) { rws[i] = 0; } assert(carry === 0); assert((carry & ~0x1fff) === 0); }; FFTM.prototype.stub = function stub (N) { var ph = new Array(N); for (var i = 0; i < N; i++) { ph[i] = 0; } return ph; }; FFTM.prototype.mulp = function mulp (x, y, out) { var N = 2 * this.guessLen13b(x.length, y.length); var rbt = this.makeRBT(N); var _ = this.stub(N); var rws = new Array(N); var rwst = new Array(N); var iwst = new Array(N); var nrws = new Array(N); var nrwst = new Array(N); var niwst = new Array(N); var rmws = out.words; rmws.length = N; this.convert13b(x.words, x.length, rws, N); this.convert13b(y.words, y.length, nrws, N); this.transform(rws, _, rwst, iwst, N, rbt); this.transform(nrws, _, nrwst, niwst, N, rbt); for (var i = 0; i < N; i++) { var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; rwst[i] = rx; } this.conjugate(rwst, iwst, N); this.transform(rwst, iwst, rmws, _, N, rbt); this.conjugate(rmws, _, N); this.normalize13b(rmws, N); out.negative = x.negative ^ y.negative; out.length = x.length + y.length; return out._strip(); }; // Multiply `this` by `num` BN.prototype.mul = function mul (num) { var out = new BN(null); out.words = new Array(this.length + num.length); return this.mulTo(num, out); }; // Multiply employing FFT BN.prototype.mulf = function mulf (num) { var out = new BN(null); out.words = new Array(this.length + num.length); return jumboMulTo(this, num, out); }; // In-place Multiplication BN.prototype.imul = function imul (num) { return this.clone().mulTo(num, this); }; BN.prototype.imuln = function imuln (num) { var isNegNum = num < 0; if (isNegNum) num = -num; assert(typeof num === 'number'); assert(num < 0x4000000); // Carry var carry = 0; for (var i = 0; i < this.length; i++) { var w = (this.words[i] | 0) * num; var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); carry >>= 26; carry += (w / 0x4000000) | 0; // NOTE: lo is 27bit maximum carry += lo >>> 26; this.words[i] = lo & 0x3ffffff; } if (carry !== 0) { this.words[i] = carry; this.length++; } return isNegNum ? this.ineg() : this; }; BN.prototype.muln = function muln (num) { return this.clone().imuln(num); }; // `this` * `this` BN.prototype.sqr = function sqr () { return this.mul(this); }; // `this` * `this` in-place BN.prototype.isqr = function isqr () { return this.imul(this.clone()); }; // Math.pow(`this`, `num`) BN.prototype.pow = function pow (num) { var w = toBitArray(num); if (w.length === 0) return new BN(1); // Skip leading zeroes var res = this; for (var i = 0; i < w.length; i++, res = res.sqr()) { if (w[i] !== 0) break; } if (++i < w.length) { for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { if (w[i] === 0) continue; res = res.mul(q); } } return res; }; // Shift-left in-place BN.prototype.iushln = function iushln (bits) { assert(typeof bits === 'number' && bits >= 0); var r = bits % 26; var s = (bits - r) / 26; var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); var i; if (r !== 0) { var carry = 0; for (i = 0; i < this.length; i++) { var newCarry = this.words[i] & carryMask; var c = ((this.words[i] | 0) - newCarry) << r; this.words[i] = c | carry; carry = newCarry >>> (26 - r); } if (carry) { this.words[i] = carry; this.length++; } } if (s !== 0) { for (i = this.length - 1; i >= 0; i--) { this.words[i + s] = this.words[i]; } for (i = 0; i < s; i++) { this.words[i] = 0; } this.length += s; } return this._strip(); }; BN.prototype.ishln = function ishln (bits) { // TODO(indutny): implement me assert(this.negative === 0); return this.iushln(bits); }; // Shift-right in-place // NOTE: `hint` is a lowest bit before trailing zeroes // NOTE: if `extended` is present - it will be filled with destroyed bits BN.prototype.iushrn = function iushrn (bits, hint, extended) { assert(typeof bits === 'number' && bits >= 0); var h; if (hint) { h = (hint - (hint % 26)) / 26; } else { h = 0; } var r = bits % 26; var s = Math.min((bits - r) / 26, this.length); var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); var maskedWords = extended; h -= s; h = Math.max(0, h); // Extended mode, copy masked part if (maskedWords) { for (var i = 0; i < s; i++) { maskedWords.words[i] = this.words[i]; } maskedWords.length = s; } if (s === 0) { // No-op, we should not move anything at all } else if (this.length > s) { this.length -= s; for (i = 0; i < this.length; i++) { this.words[i] = this.words[i + s]; } } else { this.words[0] = 0; this.length = 1; } var carry = 0; for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { var word = this.words[i] | 0; this.words[i] = (carry << (26 - r)) | (word >>> r); carry = word & mask; } // Push carried bits as a mask if (maskedWords && carry !== 0) { maskedWords.words[maskedWords.length++] = carry; } if (this.length === 0) { this.words[0] = 0; this.length = 1; } return this._strip(); }; BN.prototype.ishrn = function ishrn (bits, hint, extended) { // TODO(indutny): implement me assert(this.negative === 0); return this.iushrn(bits, hint, extended); }; // Shift-left BN.prototype.shln = function shln (bits) { return this.clone().ishln(bits); }; BN.prototype.ushln = function ushln (bits) { return this.clone().iushln(bits); }; // Shift-right BN.prototype.shrn = function shrn (bits) { return this.clone().ishrn(bits); }; BN.prototype.ushrn = function ushrn (bits) { return this.clone().iushrn(bits); }; // Test if n bit is set BN.prototype.testn = function testn (bit) { assert(typeof bit === 'number' && bit >= 0); var r = bit % 26; var s = (bit - r) / 26; var q = 1 << r; // Fast case: bit is much higher than all existing words if (this.length <= s) return false; // Check bit and return var w = this.words[s]; return !!(w & q); }; // Return only lowers bits of number (in-place) BN.prototype.imaskn = function imaskn (bits) { assert(typeof bits === 'number' && bits >= 0); var r = bits % 26; var s = (bits - r) / 26; assert(this.negative === 0, 'imaskn works only with positive numbers'); if (this.length <= s) { return this; } if (r !== 0) { s++; } this.length = Math.min(s, this.length); if (r !== 0) { var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); this.words[this.length - 1] &= mask; } return this._strip(); }; // Return only lowers bits of number BN.prototype.maskn = function maskn (bits) { return this.clone().imaskn(bits); }; // Add plain number `num` to `this` BN.prototype.iaddn = function iaddn (num) { assert(typeof num === 'number'); assert(num < 0x4000000); if (num < 0) return this.isubn(-num); // Possible sign change if (this.negative !== 0) { if (this.length === 1 && (this.words[0] | 0) <= num) { this.words[0] = num - (this.words[0] | 0); this.negative = 0; return this; } this.negative = 0; this.isubn(num); this.negative = 1; return this; } // Add without checks return this._iaddn(num); }; BN.prototype._iaddn = function _iaddn (num) { this.words[0] += num; // Carry for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { this.words[i] -= 0x4000000; if (i === this.length - 1) { this.words[i + 1] = 1; } else { this.words[i + 1]++; } } this.length = Math.max(this.length, i + 1); return this; }; // Subtract plain number `num` from `this` BN.prototype.isubn = function isubn (num) { assert(typeof num === 'number'); assert(num < 0x4000000); if (num < 0) return this.iaddn(-num); if (this.negative !== 0) { this.negative = 0; this.iaddn(num); this.negative = 1; return this; } this.words[0] -= num; if (this.length === 1 && this.words[0] < 0) { this.words[0] = -this.words[0]; this.negative = 1; } else { // Carry for (var i = 0; i < this.length && this.words[i] < 0; i++) { this.words[i] += 0x4000000; this.words[i + 1] -= 1; } } return this._strip(); }; BN.prototype.addn = function addn (num) { return this.clone().iaddn(num); }; BN.prototype.subn = function subn (num) { return this.clone().isubn(num); }; BN.prototype.iabs = function iabs () { this.negative = 0; return this; }; BN.prototype.abs = function abs () { return this.clone().iabs(); }; BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { var len = num.length + shift; var i; this._expand(len); var w; var carry = 0; for (i = 0; i < num.length; i++) { w = (this.words[i + shift] | 0) + carry; var right = (num.words[i] | 0) * mul; w -= right & 0x3ffffff; carry = (w >> 26) - ((right / 0x4000000) | 0); this.words[i + shift] = w & 0x3ffffff; } for (; i < this.length - shift; i++) { w = (this.words[i + shift] | 0) + carry; carry = w >> 26; this.words[i + shift] = w & 0x3ffffff; } if (carry === 0) return this._strip(); // Subtraction overflow assert(carry === -1); carry = 0; for (i = 0; i < this.length; i++) { w = -(this.words[i] | 0) + carry; carry = w >> 26; this.words[i] = w & 0x3ffffff; } this.negative = 1; return this._strip(); }; BN.prototype._wordDiv = function _wordDiv (num, mode) { var shift = this.length - num.length; var a = this.clone(); var b = num; // Normalize var bhi = b.words[b.length - 1] | 0; var bhiBits = this._countBits(bhi); shift = 26 - bhiBits; if (shift !== 0) { b = b.ushln(shift); a.iushln(shift); bhi = b.words[b.length - 1] | 0; } // Initialize quotient var m = a.length - b.length; var q; if (mode !== 'mod') { q = new BN(null); q.length = m + 1; q.words = new Array(q.length); for (var i = 0; i < q.length; i++) { q.words[i] = 0; } } var diff = a.clone()._ishlnsubmul(b, 1, m); if (diff.negative === 0) { a = diff; if (q) { q.words[m] = 1; } } for (var j = m - 1; j >= 0; j--) { var qj = (a.words[b.length + j] | 0) * 0x4000000 + (a.words[b.length + j - 1] | 0); // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max // (0x7ffffff) qj = Math.min((qj / bhi) | 0, 0x3ffffff); a._ishlnsubmul(b, qj, j); while (a.negative !== 0) { qj--; a.negative = 0; a._ishlnsubmul(b, 1, j); if (!a.isZero()) { a.negative ^= 1; } } if (q) { q.words[j] = qj; } } if (q) { q._strip(); } a._strip(); // Denormalize if (mode !== 'div' && shift !== 0) { a.iushrn(shift); } return { div: q || null, mod: a }; }; // NOTE: 1) `mode` can be set to `mod` to request mod only, // to `div` to request div only, or be absent to // request both div & mod // 2) `positive` is true if unsigned mod is requested BN.prototype.divmod = function divmod (num, mode, positive) { assert(!num.isZero()); if (this.isZero()) { return { div: new BN(0), mod: new BN(0) }; } var div, mod, res; if (this.negative !== 0 && num.negative === 0) { res = this.neg().divmod(num, mode); if (mode !== 'mod') { div = res.div.neg(); } if (mode !== 'div') { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.iadd(num); } } return { div: div, mod: mod }; } if (this.negative === 0 && num.negative !== 0) { res = this.divmod(num.neg(), mode); if (mode !== 'mod') { div = res.div.neg(); } return { div: div, mod: res.mod }; } if ((this.negative & num.negative) !== 0) { res = this.neg().divmod(num.neg(), mode); if (mode !== 'div') { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.isub(num); } } return { div: res.div, mod: mod }; } // Both numbers are positive at this point // Strip both numbers to approximate shift value if (num.length > this.length || this.cmp(num) < 0) { return { div: new BN(0), mod: this }; } // Very short reduction if (num.length === 1) { if (mode === 'div') { return { div: this.divn(num.words[0]), mod: null }; } if (mode === 'mod') { return { div: null, mod: new BN(this.modrn(num.words[0])) }; } return { div: this.divn(num.words[0]), mod: new BN(this.modrn(num.words[0])) }; } return this._wordDiv(num, mode); }; // Find `this` / `num` BN.prototype.div = function div (num) { return this.divmod(num, 'div', false).div; }; // Find `this` % `num` BN.prototype.mod = function mod (num) { return this.divmod(num, 'mod', false).mod; }; BN.prototype.umod = function umod (num) { return this.divmod(num, 'mod', true).mod; }; // Find Round(`this` / `num`) BN.prototype.divRound = function divRound (num) { var dm = this.divmod(num); // Fast case - exact division if (dm.mod.isZero()) return dm.div; var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; var half = num.ushrn(1); var r2 = num.andln(1); var cmp = mod.cmp(half); // Round down if (cmp < 0 || (r2 === 1 && cmp === 0)) return dm.div; // Round up return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); }; BN.prototype.modrn = function modrn (num) { var isNegNum = num < 0; if (isNegNum) num = -num; assert(num <= 0x3ffffff); var p = (1 << 26) % num; var acc = 0; for (var i = this.length - 1; i >= 0; i--) { acc = (p * acc + (this.words[i] | 0)) % num; } return isNegNum ? -acc : acc; }; // WARNING: DEPRECATED BN.prototype.modn = function modn (num) { return this.modrn(num); }; // In-place division by number BN.prototype.idivn = function idivn (num) { var isNegNum = num < 0; if (isNegNum) num = -num; assert(num <= 0x3ffffff); var carry = 0; for (var i = this.length - 1; i >= 0; i--) { var w = (this.words[i] | 0) + carry * 0x4000000; this.words[i] = (w / num) | 0; carry = w % num; } this._strip(); return isNegNum ? this.ineg() : this; }; BN.prototype.divn = function divn (num) { return this.clone().idivn(num); }; BN.prototype.egcd = function egcd (p) { assert(p.negative === 0); assert(!p.isZero()); var x = this; var y = p.clone(); if (x.negative !== 0) { x = x.umod(p); } else { x = x.clone(); } // A * x + B * y = x var A = new BN(1); var B = new BN(0); // C * x + D * y = y var C = new BN(0); var D = new BN(1); var g = 0; while (x.isEven() && y.isEven()) { x.iushrn(1); y.iushrn(1); ++g; } var yp = y.clone(); var xp = x.clone(); while (!x.isZero()) { for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); if (i > 0) { x.iushrn(i); while (i-- > 0) { if (A.isOdd() || B.isOdd()) { A.iadd(yp); B.isub(xp); } A.iushrn(1); B.iushrn(1); } } for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); if (j > 0) { y.iushrn(j); while (j-- > 0) { if (C.isOdd() || D.isOdd()) { C.iadd(yp); D.isub(xp); } C.iushrn(1); D.iushrn(1); } } if (x.cmp(y) >= 0) { x.isub(y); A.isub(C); B.isub(D); } else { y.isub(x); C.isub(A); D.isub(B); } } return { a: C, b: D, gcd: y.iushln(g) }; }; // This is reduced incarnation of the binary EEA // above, designated to invert members of the // _prime_ fields F(p) at a maximal speed BN.prototype._invmp = function _invmp (p) { assert(p.negative === 0); assert(!p.isZero()); var a = this; var b = p.clone(); if (a.negative !== 0) { a = a.umod(p); } else { a = a.clone(); } var x1 = new BN(1); var x2 = new BN(0); var delta = b.clone(); while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); if (i > 0) { a.iushrn(i); while (i-- > 0) { if (x1.isOdd()) { x1.iadd(delta); } x1.iushrn(1); } } for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); if (j > 0) { b.iushrn(j); while (j-- > 0) { if (x2.isOdd()) { x2.iadd(delta); } x2.iushrn(1); } } if (a.cmp(b) >= 0) { a.isub(b); x1.isub(x2); } else { b.isub(a); x2.isub(x1); } } var res; if (a.cmpn(1) === 0) { res = x1; } else { res = x2; } if (res.cmpn(0) < 0) { res.iadd(p); } return res; }; BN.prototype.gcd = function gcd (num) { if (this.isZero()) return num.abs(); if (num.isZero()) return this.abs(); var a = this.clone(); var b = num.clone(); a.negative = 0; b.negative = 0; // Remove common factor of two for (var shift = 0; a.isEven() && b.isEven(); shift++) { a.iushrn(1); b.iushrn(1); } do { while (a.isEven()) { a.iushrn(1); } while (b.isEven()) { b.iushrn(1); } var r = a.cmp(b); if (r < 0) { // Swap `a` and `b` to make `a` always bigger than `b` var t = a; a = b; b = t; } else if (r === 0 || b.cmpn(1) === 0) { break; } a.isub(b); } while (true); return b.iushln(shift); }; // Invert number in the field F(num) BN.prototype.invm = function invm (num) { return this.egcd(num).a.umod(num); }; BN.prototype.isEven = function isEven () { return (this.words[0] & 1) === 0; }; BN.prototype.isOdd = function isOdd () { return (this.words[0] & 1) === 1; }; // And first word and num BN.prototype.andln = function andln (num) { return this.words[0] & num; }; // Increment at the bit position in-line BN.prototype.bincn = function bincn (bit) { assert(typeof bit === 'number'); var r = bit % 26; var s = (bit - r) / 26; var q = 1 << r; // Fast case: bit is much higher than all existing words if (this.length <= s) { this._expand(s + 1); this.words[s] |= q; return this; } // Add bit and propagate, if needed var carry = q; for (var i = s; carry !== 0 && i < this.length; i++) { var w = this.words[i] | 0; w += carry; carry = w >>> 26; w &= 0x3ffffff; this.words[i] = w; } if (carry !== 0) { this.words[i] = carry; this.length++; } return this; }; BN.prototype.isZero = function isZero () { return this.length === 1 && this.words[0] === 0; }; BN.prototype.cmpn = function cmpn (num) { var negative = num < 0; if (this.negative !== 0 && !negative) return -1; if (this.negative === 0 && negative) return 1; this._strip(); var res; if (this.length > 1) { res = 1; } else { if (negative) { num = -num; } assert(num <= 0x3ffffff, 'Number is too big'); var w = this.words[0] | 0; res = w === num ? 0 : w < num ? -1 : 1; } if (this.negative !== 0) return -res | 0; return res; }; // Compare two numbers and return: // 1 - if `this` > `num` // 0 - if `this` == `num` // -1 - if `this` < `num` BN.prototype.cmp = function cmp (num) { if (this.negative !== 0 && num.negative === 0) return -1; if (this.negative === 0 && num.negative !== 0) return 1; var res = this.ucmp(num); if (this.negative !== 0) return -res | 0; return res; }; // Unsigned comparison BN.prototype.ucmp = function ucmp (num) { // At this point both numbers have the same sign if (this.length > num.length) return 1; if (this.length < num.length) return -1; var res = 0; for (var i = this.length - 1; i >= 0; i--) { var a = this.words[i] | 0; var b = num.words[i] | 0; if (a === b) continue; if (a < b) { res = -1; } else if (a > b) { res = 1; } break; } return res; }; BN.prototype.gtn = function gtn (num) { return this.cmpn(num) === 1; }; BN.prototype.gt = function gt (num) { return this.cmp(num) === 1; }; BN.prototype.gten = function gten (num) { return this.cmpn(num) >= 0; }; BN.prototype.gte = function gte (num) { return this.cmp(num) >= 0; }; BN.prototype.ltn = function ltn (num) { return this.cmpn(num) === -1; }; BN.prototype.lt = function lt (num) { return this.cmp(num) === -1; }; BN.prototype.lten = function lten (num) { return this.cmpn(num) <= 0; }; BN.prototype.lte = function lte (num) { return this.cmp(num) <= 0; }; BN.prototype.eqn = function eqn (num) { return this.cmpn(num) === 0; }; BN.prototype.eq = function eq (num) { return this.cmp(num) === 0; }; // // A reduce context, could be using montgomery or something better, depending // on the `m` itself. // BN.red = function red (num) { return new Red(num); }; BN.prototype.toRed = function toRed (ctx) { assert(!this.red, 'Already a number in reduction context'); assert(this.negative === 0, 'red works only with positives'); return ctx.convertTo(this)._forceRed(ctx); }; BN.prototype.fromRed = function fromRed () { assert(this.red, 'fromRed works only with numbers in reduction context'); return this.red.convertFrom(this); }; BN.prototype._forceRed = function _forceRed (ctx) { this.red = ctx; return this; }; BN.prototype.forceRed = function forceRed (ctx) { assert(!this.red, 'Already a number in reduction context'); return this._forceRed(ctx); }; BN.prototype.redAdd = function redAdd (num) { assert(this.red, 'redAdd works only with red numbers'); return this.red.add(this, num); }; BN.prototype.redIAdd = function redIAdd (num) { assert(this.red, 'redIAdd works only with red numbers'); return this.red.iadd(this, num); }; BN.prototype.redSub = function redSub (num) { assert(this.red, 'redSub works only with red numbers'); return this.red.sub(this, num); }; BN.prototype.redISub = function redISub (num) { assert(this.red, 'redISub works only with red numbers'); return this.red.isub(this, num); }; BN.prototype.redShl = function redShl (num) { assert(this.red, 'redShl works only with red numbers'); return this.red.shl(this, num); }; BN.prototype.redMul = function redMul (num) { assert(this.red, 'redMul works only with red numbers'); this.red._verify2(this, num); return this.red.mul(this, num); }; BN.prototype.redIMul = function redIMul (num) { assert(this.red, 'redMul works only with red numbers'); this.red._verify2(this, num); return this.red.imul(this, num); }; BN.prototype.redSqr = function redSqr () { assert(this.red, 'redSqr works only with red numbers'); this.red._verify1(this); return this.red.sqr(this); }; BN.prototype.redISqr = function redISqr () { assert(this.red, 'redISqr works only with red numbers'); this.red._verify1(this); return this.red.isqr(this); }; // Square root over p BN.prototype.redSqrt = function redSqrt () { assert(this.red, 'redSqrt works only with red numbers'); this.red._verify1(this); return this.red.sqrt(this); }; BN.prototype.redInvm = function redInvm () { assert(this.red, 'redInvm works only with red numbers'); this.red._verify1(this); return this.red.invm(this); }; // Return negative clone of `this` % `red modulo` BN.prototype.redNeg = function redNeg () { assert(this.red, 'redNeg works only with red numbers'); this.red._verify1(this); return this.red.neg(this); }; BN.prototype.redPow = function redPow (num) { assert(this.red && !num.red, 'redPow(normalNum)'); this.red._verify1(this); return this.red.pow(this, num); }; // Prime numbers with efficient reduction var primes = { k256: null, p224: null, p192: null, p25519: null }; // Pseudo-Mersenne prime function MPrime (name, p) { // P = 2 ^ N - K this.name = name; this.p = new BN(p, 16); this.n = this.p.bitLength(); this.k = new BN(1).iushln(this.n).isub(this.p); this.tmp = this._tmp(); } MPrime.prototype._tmp = function _tmp () { var tmp = new BN(null); tmp.words = new Array(Math.ceil(this.n / 13)); return tmp; }; MPrime.prototype.ireduce = function ireduce (num) { // Assumes that `num` is less than `P^2` // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) var r = num; var rlen; do { this.split(r, this.tmp); r = this.imulK(r); r = r.iadd(this.tmp); rlen = r.bitLength(); } while (rlen > this.n); var cmp = rlen < this.n ? -1 : r.ucmp(this.p); if (cmp === 0) { r.words[0] = 0; r.length = 1; } else if (cmp > 0) { r.isub(this.p); } else { if (r.strip !== undefined) { // r is a BN v4 instance r.strip(); } else { // r is a BN v5 instance r._strip(); } } return r; }; MPrime.prototype.split = function split (input, out) { input.iushrn(this.n, 0, out); }; MPrime.prototype.imulK = function imulK (num) { return num.imul(this.k); }; function K256 () { MPrime.call( this, 'k256', 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); } inherits(K256, MPrime); K256.prototype.split = function split (input, output) { // 256 = 9 * 26 + 22 var mask = 0x3fffff; var outLen = Math.min(input.length, 9); for (var i = 0; i < outLen; i++) { output.words[i] = input.words[i]; } output.length = outLen; if (input.length <= 9) { input.words[0] = 0; input.length = 1; return; } // Shift by 9 limbs var prev = input.words[9]; output.words[output.length++] = prev & mask; for (i = 10; i < input.length; i++) { var next = input.words[i] | 0; input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); prev = next; } prev >>>= 22; input.words[i - 10] = prev; if (prev === 0 && input.length > 10) { input.length -= 10; } else { input.length -= 9; } }; K256.prototype.imulK = function imulK (num) { // K = 0x1000003d1 = [ 0x40, 0x3d1 ] num.words[num.length] = 0; num.words[num.length + 1] = 0; num.length += 2; // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 var lo = 0; for (var i = 0; i < num.length; i++) { var w = num.words[i] | 0; lo += w * 0x3d1; num.words[i] = lo & 0x3ffffff; lo = w * 0x40 + ((lo / 0x4000000) | 0); } // Fast length reduction if (num.words[num.length - 1] === 0) { num.length--; if (num.words[num.length - 1] === 0) { num.length--; } } return num; }; function P224 () { MPrime.call( this, 'p224', 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); } inherits(P224, MPrime); function P192 () { MPrime.call( this, 'p192', 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); } inherits(P192, MPrime); function P25519 () { // 2 ^ 255 - 19 MPrime.call( this, '25519', '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); } inherits(P25519, MPrime); P25519.prototype.imulK = function imulK (num) { // K = 0x13 var carry = 0; for (var i = 0; i < num.length; i++) { var hi = (num.words[i] | 0) * 0x13 + carry; var lo = hi & 0x3ffffff; hi >>>= 26; num.words[i] = lo; carry = hi; } if (carry !== 0) { num.words[num.length++] = carry; } return num; }; // Exported mostly for testing purposes, use plain name instead BN._prime = function prime (name) { // Cached version of prime if (primes[name]) return primes[name]; var prime; if (name === 'k256') { prime = new K256(); } else if (name === 'p224') { prime = new P224(); } else if (name === 'p192') { prime = new P192(); } else if (name === 'p25519') { prime = new P25519(); } else { throw new Error('Unknown prime ' + name); } primes[name] = prime; return prime; }; // // Base reduction engine // function Red (m) { if (typeof m === 'string') { var prime = BN._prime(m); this.m = prime.p; this.prime = prime; } else { assert(m.gtn(1), 'modulus must be greater than 1'); this.m = m; this.prime = null; } } Red.prototype._verify1 = function _verify1 (a) { assert(a.negative === 0, 'red works only with positives'); assert(a.red, 'red works only with red numbers'); }; Red.prototype._verify2 = function _verify2 (a, b) { assert((a.negative | b.negative) === 0, 'red works only with positives'); assert(a.red && a.red === b.red, 'red works only with red numbers'); }; Red.prototype.imod = function imod (a) { if (this.prime) return this.prime.ireduce(a)._forceRed(this); move(a, a.umod(this.m)._forceRed(this)); return a; }; Red.prototype.neg = function neg (a) { if (a.isZero()) { return a.clone(); } return this.m.sub(a)._forceRed(this); }; Red.prototype.add = function add (a, b) { this._verify2(a, b); var res = a.add(b); if (res.cmp(this.m) >= 0) { res.isub(this.m); } return res._forceRed(this); }; Red.prototype.iadd = function iadd (a, b) { this._verify2(a, b); var res = a.iadd(b); if (res.cmp(this.m) >= 0) { res.isub(this.m); } return res; }; Red.prototype.sub = function sub (a, b) { this._verify2(a, b); var res = a.sub(b); if (res.cmpn(0) < 0) { res.iadd(this.m); } return res._forceRed(this); }; Red.prototype.isub = function isub (a, b) { this._verify2(a, b); var res = a.isub(b); if (res.cmpn(0) < 0) { res.iadd(this.m); } return res; }; Red.prototype.shl = function shl (a, num) { this._verify1(a); return this.imod(a.ushln(num)); }; Red.prototype.imul = function imul (a, b) { this._verify2(a, b); return this.imod(a.imul(b)); }; Red.prototype.mul = function mul (a, b) { this._verify2(a, b); return this.imod(a.mul(b)); }; Red.prototype.isqr = function isqr (a) { return this.imul(a, a.clone()); }; Red.prototype.sqr = function sqr (a) { return this.mul(a, a); }; Red.prototype.sqrt = function sqrt (a) { if (a.isZero()) return a.clone(); var mod3 = this.m.andln(3); assert(mod3 % 2 === 1); // Fast case if (mod3 === 3) { var pow = this.m.add(new BN(1)).iushrn(2); return this.pow(a, pow); } // Tonelli-Shanks algorithm (Totally unoptimized and slow) // // Find Q and S, that Q * 2 ^ S = (P - 1) var q = this.m.subn(1); var s = 0; while (!q.isZero() && q.andln(1) === 0) { s++; q.iushrn(1); } assert(!q.isZero()); var one = new BN(1).toRed(this); var nOne = one.redNeg(); // Find quadratic non-residue // NOTE: Max is such because of generalized Riemann hypothesis. var lpow = this.m.subn(1).iushrn(1); var z = this.m.bitLength(); z = new BN(2 * z * z).toRed(this); while (this.pow(z, lpow).cmp(nOne) !== 0) { z.redIAdd(nOne); } var c = this.pow(z, q); var r = this.pow(a, q.addn(1).iushrn(1)); var t = this.pow(a, q); var m = s; while (t.cmp(one) !== 0) { var tmp = t; for (var i = 0; tmp.cmp(one) !== 0; i++) { tmp = tmp.redSqr(); } assert(i < m); var b = this.pow(c, new BN(1).iushln(m - i - 1)); r = r.redMul(b); c = b.redSqr(); t = t.redMul(c); m = i; } return r; }; Red.prototype.invm = function invm (a) { var inv = a._invmp(this.m); if (inv.negative !== 0) { inv.negative = 0; return this.imod(inv).redNeg(); } else { return this.imod(inv); } }; Red.prototype.pow = function pow (a, num) { if (num.isZero()) return new BN(1).toRed(this); if (num.cmpn(1) === 0) return a.clone(); var windowSize = 4; var wnd = new Array(1 << windowSize); wnd[0] = new BN(1).toRed(this); wnd[1] = a; for (var i = 2; i < wnd.length; i++) { wnd[i] = this.mul(wnd[i - 1], a); } var res = wnd[0]; var current = 0; var currentLen = 0; var start = num.bitLength() % 26; if (start === 0) { start = 26; } for (i = num.length - 1; i >= 0; i--) { var word = num.words[i]; for (var j = start - 1; j >= 0; j--) { var bit = (word >> j) & 1; if (res !== wnd[0]) { res = this.sqr(res); } if (bit === 0 && current === 0) { currentLen = 0; continue; } current <<= 1; current |= bit; currentLen++; if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; res = this.mul(res, wnd[current]); currentLen = 0; current = 0; } start = 26; } return res; }; Red.prototype.convertTo = function convertTo (num) { var r = num.umod(this.m); return r === num ? r.clone() : r; }; Red.prototype.convertFrom = function convertFrom (num) { var res = num.clone(); res.red = null; return res; }; // // Montgomery method engine // BN.mont = function mont (num) { return new Mont(num); }; function Mont (m) { Red.call(this, m); this.shift = this.m.bitLength(); if (this.shift % 26 !== 0) { this.shift += 26 - (this.shift % 26); } this.r = new BN(1).iushln(this.shift); this.r2 = this.imod(this.r.sqr()); this.rinv = this.r._invmp(this.m); this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); this.minv = this.minv.umod(this.r); this.minv = this.r.sub(this.minv); } inherits(Mont, Red); Mont.prototype.convertTo = function convertTo (num) { return this.imod(num.ushln(this.shift)); }; Mont.prototype.convertFrom = function convertFrom (num) { var r = this.imod(num.mul(this.rinv)); r.red = null; return r; }; Mont.prototype.imul = function imul (a, b) { if (a.isZero() || b.isZero()) { a.words[0] = 0; a.length = 1; return a; } var t = a.imul(b); var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); var u = t.isub(c).iushrn(this.shift); var res = u; if (u.cmp(this.m) >= 0) { res = u.isub(this.m); } else if (u.cmpn(0) < 0) { res = u.iadd(this.m); } return res._forceRed(this); }; Mont.prototype.mul = function mul (a, b) { if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); var t = a.mul(b); var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); var u = t.isub(c).iushrn(this.shift); var res = u; if (u.cmp(this.m) >= 0) { res = u.isub(this.m); } else if (u.cmpn(0) < 0) { res = u.iadd(this.m); } return res._forceRed(this); }; Mont.prototype.invm = function invm (a) { // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R var res = this.imod(a._invmp(this.m).mul(this.r2)); return res._forceRed(this); }; })( false || module, this); /***/ }), /***/ 33717: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var concatMap = __nccwpck_require__(86891); var balanced = __nccwpck_require__(9417); module.exports = expandTop; var escSlash = '\0SLASH'+Math.random()+'\0'; var escOpen = '\0OPEN'+Math.random()+'\0'; var escClose = '\0CLOSE'+Math.random()+'\0'; var escComma = '\0COMMA'+Math.random()+'\0'; var escPeriod = '\0PERIOD'+Math.random()+'\0'; function numeric(str) { return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0); } 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; } /***/ }), /***/ 86891: /***/ ((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]'; }; /***/ }), /***/ 76599: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var stream = __nccwpck_require__(51642) var eos = __nccwpck_require__(81205) var inherits = __nccwpck_require__(44124) var shift = __nccwpck_require__(66121) 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 /***/ }), /***/ 81205: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var once = __nccwpck_require__(1223); 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; /***/ }), /***/ 12603: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const validator = __nccwpck_require__(61739); const XMLParser = __nccwpck_require__(42380); const XMLBuilder = __nccwpck_require__(80660); module.exports = { XMLParser: XMLParser, XMLValidator: validator, XMLBuilder: XMLBuilder } /***/ }), /***/ 38280: /***/ ((__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; /***/ }), /***/ 61739: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; const util = __nccwpck_require__(38280); 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 { 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; } /***/ }), /***/ 80660: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; //parse Empty Node as self closing node const buildFromOrderedJs = __nccwpck_require__(72462); 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 || this.options.attributesGroupName) { this.isAttribute = function(/*a*/) { return false; }; } else { 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) { let attrStr = ''; let val = ''; for (let key in jObj) { if (typeof jObj[key] === 'undefined') { // supress undefined node } else if (jObj[key] === 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 (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) { attrStr += this.buildAttrPairStr(attr, '' + jObj[key]); }else { //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 = ""; 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 ){ listTagVal += this.j2x(item, level + 1).val; }else{ listTagVal += this.processTextOrObjNode(item, key, level) } } else { listTagVal += this.buildTextValNode(item, key, '', level); } } if(this.options.oneListGroup){ listTagVal = this.buildObjectNode(listTagVal, key, '', 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) } } } 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) { const result = this.j2x(object, level + 1); 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); 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 (key !== ":@") return key; } } function attr_to_str(attrMap, options) { let attrStr = ""; if (attrMap && !options.ignoreAttributes) { for (let attr in attrMap) { 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; /***/ }), /***/ 6072: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const util = __nccwpck_require__(38280); //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; /***/ }), /***/ 86993: /***/ ((__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; /***/ }), /***/ 25832: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; ///@ts-check const util = __nccwpck_require__(38280); const xmlNode = __nccwpck_require__(7462); const readDocType = __nccwpck_require__(6072); const toNumber = __nccwpck_require__(14526); 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: "₹" }, }; 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; } } 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 && 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]); 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); //cdata should be set even if it is 0 length string if(this.options.cdataPropName){ // let val = this.parseTextData(tagExp, this.options.cdataPropName, jPath + "." + this.options.cdataPropName, true, false, true); // if(!val) val = ""; currentNode.add(this.options.cdataPropName, [ { [this.options.textNodeName] : tagExp } ]); }else{ let val = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true); if(val == undefined) val = ""; currentNode.add(this.options.textNodeName, val); } i = closeIndex + 2; }else {//Opening tag let result = readTagExp(xmlData,i, this.options.removeNSPrefix); let tagName= result.tagName; 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)) { //TODO: namespace let tagContent = ""; //self-closing tag if(tagExp.length > 0 && tagExp.lastIndexOf("/") === 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, tagName, closeIndex + 1); if(!result) throw new Error(`Unexpected end of ${tagName}`); 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); 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 = Object.keys(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.substr(0, separatorIndex).replace(/\s\s*$/, ''); tagExp = tagExp.substr(separatorIndex + 1); } 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, } } /** * 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; /***/ }), /***/ 42380: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { buildOptions} = __nccwpck_require__(86993); const OrderedObjParser = __nccwpck_require__(25832); const { prettify} = __nccwpck_require__(42882); const validator = __nccwpck_require__(61739); 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; /***/ }), /***/ 42882: /***/ ((__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; /***/ }), /***/ 7462: /***/ ((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; /***/ }), /***/ 46863: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = realpath realpath.realpath = realpath realpath.sync = realpathSync realpath.realpathSync = realpathSync realpath.monkeypatch = monkeypatch realpath.unmonkeypatch = unmonkeypatch var fs = __nccwpck_require__(57147) var origRealpath = fs.realpath var origRealpathSync = fs.realpathSync var version = process.version var ok = /^v[0-5]\./.test(version) var old = __nccwpck_require__(71734) function newError (er) { return er && er.syscall === 'realpath' && ( er.code === 'ELOOP' || er.code === 'ENOMEM' || er.code === 'ENAMETOOLONG' ) } function realpath (p, cache, cb) { if (ok) { return origRealpath(p, cache, cb) } if (typeof cache === 'function') { cb = cache cache = null } origRealpath(p, cache, function (er, result) { if (newError(er)) { old.realpath(p, cache, cb) } else { cb(er, result) } }) } function realpathSync (p, cache) { if (ok) { return origRealpathSync(p, cache) } try { return origRealpathSync(p, cache) } catch (er) { if (newError(er)) { return old.realpathSync(p, cache) } else { throw er } } } function monkeypatch () { fs.realpath = realpath fs.realpathSync = realpathSync } function unmonkeypatch () { fs.realpath = origRealpath fs.realpathSync = origRealpathSync } /***/ }), /***/ 71734: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var pathModule = __nccwpck_require__(71017); var isWindows = process.platform === 'win32'; var fs = __nccwpck_require__(57147); // JavaScript implementation of realpath, ported from node pre-v6 var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); function rethrow() { // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and // is fairly slow to generate. var callback; if (DEBUG) { var backtrace = new Error; callback = debugCallback; } else callback = missingCallback; return callback; function debugCallback(err) { if (err) { backtrace.message = err.message; err = backtrace; missingCallback(err); } } function missingCallback(err) { if (err) { if (process.throwDeprecation) throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs else if (!process.noDeprecation) { var msg = 'fs: missing callback ' + (err.stack || err.message); if (process.traceDeprecation) console.trace(msg); else console.error(msg); } } } } function maybeCallback(cb) { return typeof cb === 'function' ? cb : rethrow(); } var normalize = pathModule.normalize; // Regexp that finds the next partion of a (partial) path // result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] if (isWindows) { var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; } else { var nextPartRe = /(.*?)(?:[\/]+|$)/g; } // Regex to find the device root, including trailing slash. E.g. 'c:\\'. if (isWindows) { var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; } else { var splitRootRe = /^[\/]*/; } exports.realpathSync = function realpathSync(p, cache) { // make p is absolute p = pathModule.resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return cache[p]; } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows && !knownHard[base]) { fs.lstatSync(base); knownHard[base] = true; } } // walk down the path, swapping out linked pathparts for their real // values // NB: p.length changes. while (pos < p.length) { // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { continue; } var resolvedLink; if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // some known symbolic link. no need to stat again. resolvedLink = cache[base]; } else { var stat = fs.lstatSync(base); if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; continue; } // read the link if it wasn't read before // dev/ino always return 0 on windows, so skip the check. var linkTarget = null; if (!isWindows) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { linkTarget = seenLinks[id]; } } if (linkTarget === null) { fs.statSync(base); linkTarget = fs.readlinkSync(base); } resolvedLink = pathModule.resolve(previous, linkTarget); // track this, if given a cache. if (cache) cache[base] = resolvedLink; if (!isWindows) seenLinks[id] = linkTarget; } // resolve the link, then start over p = pathModule.resolve(resolvedLink, p.slice(pos)); start(); } if (cache) cache[original] = p; return p; }; exports.realpath = function realpath(p, cache, cb) { if (typeof cb !== 'function') { cb = maybeCallback(cache); cache = null; } // make p is absolute p = pathModule.resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return process.nextTick(cb.bind(null, null, cache[p])); } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows && !knownHard[base]) { fs.lstat(base, function(err) { if (err) return cb(err); knownHard[base] = true; LOOP(); }); } else { process.nextTick(LOOP); } } // walk down the path, swapping out linked pathparts for their real // values function LOOP() { // stop if scanned past end of path if (pos >= p.length) { if (cache) cache[original] = p; return cb(null, p); } // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { return process.nextTick(LOOP); } if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // known symbolic link. no need to stat again. return gotResolvedLink(cache[base]); } return fs.lstat(base, gotStat); } function gotStat(err, stat) { if (err) return cb(err); // if not a symlink, skip to the next path part if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; return process.nextTick(LOOP); } // stat & read the link if not read before // call gotTarget as soon as the link target is known // dev/ino always return 0 on windows, so skip the check. if (!isWindows) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { return gotTarget(null, seenLinks[id], base); } } fs.stat(base, function(err) { if (err) return cb(err); fs.readlink(base, function(err, target) { if (!isWindows) seenLinks[id] = target; gotTarget(err, target); }); }); } function gotTarget(err, target, base) { if (err) return cb(err); var resolvedLink = pathModule.resolve(previous, target); if (cache) cache[base] = resolvedLink; gotResolvedLink(resolvedLink); } function gotResolvedLink(resolvedLink) { // resolve the link, then start over p = pathModule.resolve(resolvedLink, p.slice(pos)); start(); } }; /***/ }), /***/ 52492: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var wrappy = __nccwpck_require__(62940) var reqs = Object.create(null) var once = __nccwpck_require__(1223) module.exports = wrappy(inflight) function inflight (key, cb) { if (reqs[key]) { reqs[key].push(cb) return null } else { reqs[key] = [cb] return makeres(key) } } function makeres (key) { return once(function RES () { var cbs = reqs[key] var len = cbs.length var args = slice(arguments) // XXX It's somewhat ambiguous whether a new callback added in this // pass should be queued for later execution if something in the // list of callbacks throws, or if it should just be discarded. // However, it's such an edge case that it hardly matters, and either // choice is likely as surprising as the other. // As it happens, we do go ahead and schedule it for later execution. try { for (var i = 0; i < len; i++) { cbs[i].apply(null, args) } } finally { if (cbs.length > len) { // added more in the interim. // de-zalgo, just in case, but don't call again. cbs.splice(0, len) process.nextTick(function () { RES.apply(null, args) }) } else { delete reqs[key] } } }) } function slice (args) { var length = args.length var array = [] for (var i = 0; i < length; i++) array[i] = args[i] return array } /***/ }), /***/ 44124: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { try { var util = __nccwpck_require__(73837); /* istanbul ignore next */ if (typeof util.inherits !== 'function') throw ''; module.exports = util.inherits; } catch (e) { /* istanbul ignore next */ module.exports = __nccwpck_require__(8544); } /***/ }), /***/ 8544: /***/ ((module) => { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }) } }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } } /***/ }), /***/ 7129: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // A linked list to keep track of recently-used-ness const Yallist = __nccwpck_require__(40665) const MAX = Symbol('max') const LENGTH = Symbol('length') const LENGTH_CALCULATOR = Symbol('lengthCalculator') const ALLOW_STALE = Symbol('allowStale') const MAX_AGE = Symbol('maxAge') const DISPOSE = Symbol('dispose') const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') const LRU_LIST = Symbol('lruList') const CACHE = Symbol('cache') const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') const naiveLength = () => 1 // lruList is a yallist where the head is the youngest // item, and the tail is the oldest. the list contains the Hit // objects as the entries. // Each Hit object has a reference to its Yallist.Node. This // never changes. // // cache is a Map (or PseudoMap) that matches the keys to // the Yallist.Node object. class LRUCache { constructor (options) { if (typeof options === 'number') options = { max: options } if (!options) options = {} if (options.max && (typeof options.max !== 'number' || options.max < 0)) throw new TypeError('max must be a non-negative number') // Kind of weird to have a default max of Infinity, but oh well. const max = this[MAX] = options.max || Infinity const lc = options.length || naiveLength this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc this[ALLOW_STALE] = options.stale || false if (options.maxAge && typeof options.maxAge !== 'number') throw new TypeError('maxAge must be a number') this[MAX_AGE] = options.maxAge || 0 this[DISPOSE] = options.dispose this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false this.reset() } // resize the cache when the max changes. set max (mL) { if (typeof mL !== 'number' || mL < 0) throw new TypeError('max must be a non-negative number') this[MAX] = mL || Infinity trim(this) } get max () { return this[MAX] } set allowStale (allowStale) { this[ALLOW_STALE] = !!allowStale } get allowStale () { return this[ALLOW_STALE] } set maxAge (mA) { if (typeof mA !== 'number') throw new TypeError('maxAge must be a non-negative number') this[MAX_AGE] = mA trim(this) } get maxAge () { return this[MAX_AGE] } // resize the cache when the lengthCalculator changes. set lengthCalculator (lC) { if (typeof lC !== 'function') lC = naiveLength if (lC !== this[LENGTH_CALCULATOR]) { this[LENGTH_CALCULATOR] = lC this[LENGTH] = 0 this[LRU_LIST].forEach(hit => { hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) this[LENGTH] += hit.length }) } trim(this) } get lengthCalculator () { return this[LENGTH_CALCULATOR] } get length () { return this[LENGTH] } get itemCount () { return this[LRU_LIST].length } rforEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].tail; walker !== null;) { const prev = walker.prev forEachStep(this, fn, walker, thisp) walker = prev } } forEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].head; walker !== null;) { const next = walker.next forEachStep(this, fn, walker, thisp) walker = next } } keys () { return this[LRU_LIST].toArray().map(k => k.key) } values () { return this[LRU_LIST].toArray().map(k => k.value) } reset () { if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) { this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) } this[CACHE] = new Map() // hash of items by key this[LRU_LIST] = new Yallist() // list of items in order of use recency this[LENGTH] = 0 // length of items in the list } dump () { return this[LRU_LIST].map(hit => isStale(this, hit) ? false : { k: hit.key, v: hit.value, e: hit.now + (hit.maxAge || 0) }).toArray().filter(h => h) } dumpLru () { return this[LRU_LIST] } set (key, value, maxAge) { maxAge = maxAge || this[MAX_AGE] if (maxAge && typeof maxAge !== 'number') throw new TypeError('maxAge must be a number') const now = maxAge ? Date.now() : 0 const len = this[LENGTH_CALCULATOR](value, key) if (this[CACHE].has(key)) { if (len > this[MAX]) { del(this, this[CACHE].get(key)) return false } const node = this[CACHE].get(key) const item = node.value // dispose of the old one before overwriting // split out into 2 ifs for better coverage tracking if (this[DISPOSE]) { if (!this[NO_DISPOSE_ON_SET]) this[DISPOSE](key, item.value) } item.now = now item.maxAge = maxAge item.value = value this[LENGTH] += len - item.length item.length = len this.get(key) trim(this) return true } const hit = new Entry(key, value, len, now, maxAge) // oversized objects fall out of cache automatically. if (hit.length > this[MAX]) { if (this[DISPOSE]) this[DISPOSE](key, value) return false } this[LENGTH] += hit.length this[LRU_LIST].unshift(hit) this[CACHE].set(key, this[LRU_LIST].head) trim(this) return true } has (key) { if (!this[CACHE].has(key)) return false const hit = this[CACHE].get(key).value return !isStale(this, hit) } get (key) { return get(this, key, true) } peek (key) { return get(this, key, false) } pop () { const node = this[LRU_LIST].tail if (!node) return null del(this, node) return node.value } del (key) { del(this, this[CACHE].get(key)) } load (arr) { // reset the cache this.reset() const now = Date.now() // A previous serialized cache has the most recent items first for (let l = arr.length - 1; l >= 0; l--) { const hit = arr[l] const expiresAt = hit.e || 0 if (expiresAt === 0) // the item was created without expiration in a non aged cache this.set(hit.k, hit.v) else { const maxAge = expiresAt - now // dont add already expired items if (maxAge > 0) { this.set(hit.k, hit.v, maxAge) } } } } prune () { this[CACHE].forEach((value, key) => get(this, key, false)) } } const get = (self, key, doUse) => { const node = self[CACHE].get(key) if (node) { const hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) return undefined } else { if (doUse) { if (self[UPDATE_AGE_ON_GET]) node.value.now = Date.now() self[LRU_LIST].unshiftNode(node) } } return hit.value } } const isStale = (self, hit) => { if (!hit || (!hit.maxAge && !self[MAX_AGE])) return false const diff = Date.now() - hit.now return hit.maxAge ? diff > hit.maxAge : self[MAX_AGE] && (diff > self[MAX_AGE]) } const trim = self => { if (self[LENGTH] > self[MAX]) { for (let walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) { // We know that we're about to delete this one, and also // what the next least recently used key will be, so just // go ahead and set it now. const prev = walker.prev del(self, walker) walker = prev } } } const del = (self, node) => { if (node) { const hit = node.value if (self[DISPOSE]) self[DISPOSE](hit.key, hit.value) self[LENGTH] -= hit.length self[CACHE].delete(hit.key) self[LRU_LIST].removeNode(node) } } class Entry { constructor (key, value, length, now, maxAge) { this.key = key this.value = value this.length = length this.now = now this.maxAge = maxAge || 0 } } const forEachStep = (self, fn, node, thisp) => { let hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) hit = undefined } if (hit) fn.call(thisp, hit.value, hit.key, self) } module.exports = LRUCache /***/ }), /***/ 90910: /***/ ((module) => { module.exports = assert; function assert(val, msg) { if (!val) throw new Error(msg || 'Assertion failed'); } assert.equal = function assertEqual(l, r, msg) { if (l != r) throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); }; /***/ }), /***/ 83973: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = minimatch minimatch.Minimatch = Minimatch var path = (function () { try { return __nccwpck_require__(71017) } catch (e) {}}()) || { sep: '/' } minimatch.sep = path.sep var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} var expand = __nccwpck_require__(33717) 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, '\\$&') } /***/ }), /***/ 1223: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var wrappy = __nccwpck_require__(62940) 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 } /***/ }), /***/ 38714: /***/ ((module) => { "use strict"; function posix(path) { return path.charAt(0) === '/'; } function win32(path) { // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; var result = splitDeviceRe.exec(path); var device = result[1] || ''; var isUnc = Boolean(device && device.charAt(1) !== ':'); // UNC paths are always absolute return Boolean(result[2] || isUnc); } module.exports = process.platform === 'win32' ? win32 : posix; module.exports.posix = posix; module.exports.win32 = win32; /***/ }), /***/ 67214: /***/ ((module) => { "use strict"; const codes = {}; function createErrorType(code, message, Base) { if (!Base) { Base = Error } function getMessage (arg1, arg2, arg3) { if (typeof message === 'string') { return message } else { return message(arg1, arg2, arg3) } } class NodeError extends Base { constructor (arg1, arg2, arg3) { super(getMessage(arg1, arg2, arg3)); } } NodeError.prototype.name = Base.name; NodeError.prototype.code = code; codes[code] = NodeError; } // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js function oneOf(expected, thing) { if (Array.isArray(expected)) { const len = expected.length; expected = expected.map((i) => String(i)); if (len > 2) { return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + expected[len - 1]; } else if (len === 2) { return `one of ${thing} ${expected[0]} or ${expected[1]}`; } else { return `of ${thing} ${expected[0]}`; } } else { return `of ${thing} ${String(expected)}`; } } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith function startsWith(str, search, pos) { return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith function endsWith(str, search, this_len) { if (this_len === undefined || this_len > str.length) { this_len = str.length; } return str.substring(this_len - search.length, this_len) === search; } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes function includes(str, search, start) { if (typeof start !== 'number') { start = 0; } if (start + search.length > str.length) { return false; } else { return str.indexOf(search, start) !== -1; } } createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { return 'The value "' + value + '" is invalid for option "' + name + '"' }, TypeError); createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { // determiner: 'must be' or 'must not be' let determiner; if (typeof expected === 'string' && startsWith(expected, 'not ')) { determiner = 'must not be'; expected = expected.replace(/^not /, ''); } else { determiner = 'must be'; } let msg; if (endsWith(name, ' argument')) { // For cases like 'first argument' msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; } else { const type = includes(name, '.') ? 'property' : 'argument'; msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; } msg += `. Received type ${typeof actual}`; return msg; }, TypeError); createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { return 'The ' + name + ' method is not implemented' }); createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); createErrorType('ERR_STREAM_DESTROYED', function (name) { return 'Cannot call ' + name + ' after a stream was destroyed'; }); createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { return 'Unknown encoding: ' + arg }, TypeError); createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); module.exports.q = codes; /***/ }), /***/ 41359: /***/ ((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__(51433); var Writable = __nccwpck_require__(26993); __nccwpck_require__(44124)(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; } }); /***/ }), /***/ 81542: /***/ ((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__(34415); __nccwpck_require__(44124)(PassThrough, Transform); function PassThrough(options) { if (!(this instanceof PassThrough)) return new PassThrough(options); Transform.call(this, options); } PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); }; /***/ }), /***/ 51433: /***/ ((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__(82361).EventEmitter); var EElistenerCount = function EElistenerCount(emitter, type) { return emitter.listeners(type).length; }; /**/ /**/ var Stream = __nccwpck_require__(62387); /**/ var Buffer = (__nccwpck_require__(14300).Buffer); var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } /**/ var debugUtil = __nccwpck_require__(73837); var debug; if (debugUtil && debugUtil.debuglog) { debug = debugUtil.debuglog('stream'); } else { debug = function debug() {}; } /**/ var BufferList = __nccwpck_require__(52746); var destroyImpl = __nccwpck_require__(97049); var _require = __nccwpck_require__(39948), getHighWaterMark = _require.getHighWaterMark; var _require$codes = (__nccwpck_require__(67214)/* .codes */ .q), ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. var StringDecoder; var createReadableStreamAsyncIterator; var from; __nccwpck_require__(44124)(Readable, Stream); var errorOrDestroy = destroyImpl.errorOrDestroy; var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; function prependListener(emitter, event, fn) { // Sadly this is not cacheable as some libraries bundle their own // event emitter implementation with them. 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__(41359); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. 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__(94841)/* .StringDecoder */ .s); this.decoder = new StringDecoder(options.encoding); this.encoding = options.encoding; } } function Readable(options) { Duplex = Duplex || __nccwpck_require__(41359); 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__(94841)/* .StringDecoder */ .s); var decoder = new StringDecoder(enc); this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: var p = this._readableState.buffer.head; var content = ''; while (p !== null) { content += decoder.write(p.data); p = p.next; } this._readableState.buffer.clear(); if (content !== '') this._readableState.buffer.push(content); this._readableState.length = content.length; return this; }; // Don't raise the hwm > 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__(43306); } return createReadableStreamAsyncIterator(this); }; } Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { 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__(39082); } return from(Readable, iterable, opts); }; } function indexOf(xs, x) { for (var i = 0, l = xs.length; i < l; i++) { if (xs[i] === x) return i; } return -1; } /***/ }), /***/ 34415: /***/ ((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__(67214)/* .codes */ .q), ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; var Duplex = __nccwpck_require__(41359); __nccwpck_require__(44124)(Transform, Duplex); function afterTransform(er, data) { var ts = this._transformState; ts.transforming = false; var cb = ts.writecb; if (cb === 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); } /***/ }), /***/ 26993: /***/ ((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__(65278) }; /**/ /**/ var Stream = __nccwpck_require__(62387); /**/ var Buffer = (__nccwpck_require__(14300).Buffer); var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } var destroyImpl = __nccwpck_require__(97049); var _require = __nccwpck_require__(39948), getHighWaterMark = _require.getHighWaterMark; var _require$codes = (__nccwpck_require__(67214)/* .codes */ .q), ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; var errorOrDestroy = destroyImpl.errorOrDestroy; __nccwpck_require__(44124)(Writable, Stream); function nop() {} function WritableState(options, stream, isDuplex) { Duplex = Duplex || __nccwpck_require__(41359); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream, // 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__(41359); // 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); }; /***/ }), /***/ 43306: /***/ ((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__(76080); var kLastResolve = Symbol('lastResolve'); var kLastReject = Symbol('lastReject'); var kError = Symbol('error'); var kEnded = Symbol('ended'); var kLastPromise = Symbol('lastPromise'); var kHandlePromise = Symbol('handlePromise'); var kStream = Symbol('stream'); function createIterResult(value, done) { return { value: value, done: done }; } 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; /***/ }), /***/ 52746: /***/ ((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__(14300), Buffer = _require.Buffer; var _require2 = __nccwpck_require__(73837), inspect = _require2.inspect; var custom = inspect && inspect.custom || 'inspect'; function copyBuffer(src, target, offset) { Buffer.prototype.copy.call(src, target, offset); } module.exports = /*#__PURE__*/function () { function BufferList() { _classCallCheck(this, BufferList); this.head = null; this.tail = null; this.length = 0; } _createClass(BufferList, [{ key: "push", value: function push(v) { var entry = { data: v, next: null }; if (this.length > 0) this.tail.next = entry;else this.head = entry; this.tail = entry; ++this.length; } }, { key: "unshift", value: function unshift(v) { var entry = { data: v, next: this.head }; if (this.length === 0) this.tail = entry; this.head = entry; ++this.length; } }, { key: "shift", value: function shift() { if (this.length === 0) return; var ret = this.head.data; if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; --this.length; return ret; } }, { key: "clear", value: function clear() { this.head = this.tail = null; this.length = 0; } }, { key: "join", value: function join(s) { if (this.length === 0) return ''; var p = this.head; var ret = '' + p.data; while (p = p.next) ret += s + p.data; return ret; } }, { key: "concat", value: function concat(n) { if (this.length === 0) return Buffer.alloc(0); var ret = Buffer.allocUnsafe(n >>> 0); var p = this.head; var i = 0; while (p) { copyBuffer(p.data, ret, i); i += p.data.length; p = p.next; } return ret; } // Consumes a specified amount of bytes or characters from the buffered data. }, { key: "consume", value: function consume(n, hasStrings) { var ret; if (n < this.head.data.length) { // `slice` is the same for buffers and strings. ret = this.head.data.slice(0, n); this.head.data = this.head.data.slice(n); } else if (n === this.head.data.length) { // First chunk is a perfect match. ret = this.shift(); } else { // Result spans more than one buffer. ret = hasStrings ? this._getString(n) : this._getBuffer(n); } return ret; } }, { key: "first", value: function first() { return this.head.data; } // Consumes a specified amount of characters from the buffered data. }, { key: "_getString", value: function _getString(n) { var p = this.head; var c = 1; var ret = p.data; n -= ret.length; while (p = p.next) { var str = p.data; var nb = n > str.length ? str.length : n; if (nb === str.length) ret += str;else ret += str.slice(0, n); n -= nb; if (n === 0) { if (nb === str.length) { ++c; if (p.next) this.head = p.next;else this.head = this.tail = null; } else { this.head = p; p.data = str.slice(nb); } break; } ++c; } this.length -= c; return ret; } // Consumes a specified amount of bytes from the buffered data. }, { key: "_getBuffer", value: function _getBuffer(n) { var ret = Buffer.allocUnsafe(n); var p = this.head; var c = 1; p.data.copy(ret); n -= p.data.length; while (p = p.next) { var buf = p.data; var nb = n > buf.length ? buf.length : n; buf.copy(ret, ret.length - n, 0, nb); n -= nb; if (n === 0) { if (nb === buf.length) { ++c; if (p.next) this.head = p.next;else this.head = this.tail = null; } else { this.head = p; p.data = buf.slice(nb); } break; } ++c; } this.length -= c; return ret; } // Make sure the linked list only shows the minimal necessary information. }, { key: custom, value: function value(_, options) { return inspect(this, _objectSpread(_objectSpread({}, options), {}, { // Only inspect one level. depth: 0, // It should not recurse. customInspect: false })); } }]); return BufferList; }(); /***/ }), /***/ 97049: /***/ ((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 }; /***/ }), /***/ 76080: /***/ ((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__(67214)/* .codes.ERR_STREAM_PREMATURE_CLOSE */ .q.ERR_STREAM_PREMATURE_CLOSE); function once(callback) { var called = false; return function () { if (called) return; called = true; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } 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; /***/ }), /***/ 39082: /***/ ((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__(67214)/* .codes.ERR_INVALID_ARG_TYPE */ .q.ERR_INVALID_ARG_TYPE); function from(Readable, iterable, opts) { var iterator; if (iterable && typeof iterable.next === 'function') { iterator = iterable; } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); var readable = new Readable(_objectSpread({ objectMode: true }, opts)); // Reading boolean to protect against _read // being called before last iteration completion. var reading = false; readable._read = function () { if (!reading) { reading = true; next(); } }; 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; /***/ }), /***/ 76989: /***/ ((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__(67214)/* .codes */ .q), ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; function noop(err) { // Rethrow the error if it exists to avoid swallowing it if (err) throw err; } function isRequest(stream) { return stream.setHeader && typeof stream.abort === 'function'; } function destroyer(stream, reading, writing, callback) { callback = once(callback); var closed = false; stream.on('close', function () { closed = true; }); if (eos === undefined) eos = __nccwpck_require__(76080); eos(stream, { readable: reading, writable: writing }, function (err) { if (err) return callback(err); closed = true; callback(); }); var destroyed = false; return function (err) { if (closed) return; if (destroyed) return; destroyed = true; // 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; /***/ }), /***/ 39948: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var ERR_INVALID_OPT_VALUE = (__nccwpck_require__(67214)/* .codes.ERR_INVALID_OPT_VALUE */ .q.ERR_INVALID_OPT_VALUE); function highWaterMarkFrom(options, isDuplex, duplexKey) { return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; } function getHighWaterMark(state, options, duplexKey, isDuplex) { var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); if (hwm != null) { if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { var name = isDuplex ? duplexKey : 'highWaterMark'; throw new ERR_INVALID_OPT_VALUE(name, hwm); } return Math.floor(hwm); } // Default value return state.objectMode ? 16 : 16 * 1024; } module.exports = { getHighWaterMark: getHighWaterMark }; /***/ }), /***/ 62387: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = __nccwpck_require__(12781); /***/ }), /***/ 51642: /***/ ((module, exports, __nccwpck_require__) => { var Stream = __nccwpck_require__(12781); if (process.env.READABLE_STREAM === 'disable' && Stream) { module.exports = Stream.Readable; Object.assign(module.exports, Stream); module.exports.Stream = Stream; } else { exports = module.exports = __nccwpck_require__(51433); exports.Stream = Stream || exports; exports.Readable = exports; exports.Writable = __nccwpck_require__(26993); exports.Duplex = __nccwpck_require__(41359); exports.Transform = __nccwpck_require__(34415); exports.PassThrough = __nccwpck_require__(81542); exports.finished = __nccwpck_require__(76080); exports.pipeline = __nccwpck_require__(76989); } /***/ }), /***/ 85888: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { exports.setopts = setopts exports.ownProp = ownProp exports.makeAbs = makeAbs exports.finish = finish exports.mark = mark exports.isIgnored = isIgnored exports.childrenIgnored = childrenIgnored function ownProp (obj, field) { return Object.prototype.hasOwnProperty.call(obj, field) } var fs = __nccwpck_require__(57147) var path = __nccwpck_require__(71017) var minimatch = __nccwpck_require__(83973) var isAbsolute = __nccwpck_require__(38714) var Minimatch = minimatch.Minimatch function alphasort (a, b) { return a.localeCompare(b, 'en') } function setupIgnores (self, options) { self.ignore = options.ignore || [] if (!Array.isArray(self.ignore)) self.ignore = [self.ignore] if (self.ignore.length) { self.ignore = self.ignore.map(ignoreMap) } } // ignore patterns are always in dot:true mode. function ignoreMap (pattern) { var gmatcher = null if (pattern.slice(-3) === '/**') { var gpattern = pattern.replace(/(\/\*\*)+$/, '') gmatcher = new Minimatch(gpattern, { dot: true }) } return { matcher: new Minimatch(pattern, { dot: true }), gmatcher: gmatcher } } function setopts (self, pattern, options) { if (!options) options = {} // base-matching: just use globstar for that. if (options.matchBase && -1 === pattern.indexOf("/")) { if (options.noglobstar) { throw new Error("base matching requires globstar") } pattern = "**/" + pattern } self.silent = !!options.silent self.pattern = pattern self.strict = options.strict !== false self.realpath = !!options.realpath self.realpathCache = options.realpathCache || Object.create(null) self.follow = !!options.follow self.dot = !!options.dot self.mark = !!options.mark self.nodir = !!options.nodir if (self.nodir) self.mark = true self.sync = !!options.sync self.nounique = !!options.nounique self.nonull = !!options.nonull self.nosort = !!options.nosort self.nocase = !!options.nocase self.stat = !!options.stat self.noprocess = !!options.noprocess self.absolute = !!options.absolute self.fs = options.fs || fs self.maxLength = options.maxLength || Infinity self.cache = options.cache || Object.create(null) self.statCache = options.statCache || Object.create(null) self.symlinks = options.symlinks || Object.create(null) setupIgnores(self, options) self.changedCwd = false var cwd = process.cwd() if (!ownProp(options, "cwd")) self.cwd = cwd else { self.cwd = path.resolve(options.cwd) self.changedCwd = self.cwd !== cwd } self.root = options.root || path.resolve(self.cwd, "/") self.root = path.resolve(self.root) if (process.platform === "win32") self.root = self.root.replace(/\\/g, "/") // TODO: is an absolute `cwd` supposed to be resolved against `root`? // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) if (process.platform === "win32") self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") self.nomount = !!options.nomount // disable comments and negation in Minimatch. // Note that they are not supported in Glob itself anyway. options.nonegate = true options.nocomment = true // always treat \ in patterns as escapes, not path separators options.allowWindowsEscape = false self.minimatch = new Minimatch(pattern, options) self.options = self.minimatch.options } function finish (self) { var nou = self.nounique var all = nou ? [] : Object.create(null) for (var i = 0, l = self.matches.length; i < l; i ++) { var matches = self.matches[i] if (!matches || Object.keys(matches).length === 0) { if (self.nonull) { // do like the shell, and spit out the literal glob var literal = self.minimatch.globSet[i] if (nou) all.push(literal) else all[literal] = true } } else { // had matches var m = Object.keys(matches) if (nou) all.push.apply(all, m) else m.forEach(function (m) { all[m] = true }) } } if (!nou) all = Object.keys(all) if (!self.nosort) all = all.sort(alphasort) // at *some* point we statted all of these if (self.mark) { for (var i = 0; i < all.length; i++) { all[i] = self._mark(all[i]) } if (self.nodir) { all = all.filter(function (e) { var notDir = !(/\/$/.test(e)) var c = self.cache[e] || self.cache[makeAbs(self, e)] if (notDir && c) notDir = c !== 'DIR' && !Array.isArray(c) return notDir }) } } if (self.ignore.length) all = all.filter(function(m) { return !isIgnored(self, m) }) self.found = all } function mark (self, p) { var abs = makeAbs(self, p) var c = self.cache[abs] var m = p if (c) { var isDir = c === 'DIR' || Array.isArray(c) var slash = p.slice(-1) === '/' if (isDir && !slash) m += '/' else if (!isDir && slash) m = m.slice(0, -1) if (m !== p) { var mabs = makeAbs(self, m) self.statCache[mabs] = self.statCache[abs] self.cache[mabs] = self.cache[abs] } } return m } // lotta situps... function makeAbs (self, f) { var abs = f if (f.charAt(0) === '/') { abs = path.join(self.root, f) } else if (isAbsolute(f) || f === '') { abs = f } else if (self.changedCwd) { abs = path.resolve(self.cwd, f) } else { abs = path.resolve(f) } if (process.platform === 'win32') abs = abs.replace(/\\/g, '/') return abs } // Return true, if pattern ends with globstar '**', for the accompanying parent directory. // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents function isIgnored (self, path) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) }) } function childrenIgnored (self, path) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return !!(item.gmatcher && item.gmatcher.match(path)) }) } /***/ }), /***/ 46968: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Approach: // // 1. Get the minimatch set // 2. For each pattern in the set, PROCESS(pattern, false) // 3. Store matches per-set, then uniq them // // PROCESS(pattern, inGlobStar) // Get the first [n] items from pattern that are all strings // Join these together. This is PREFIX. // If there is no more remaining, then stat(PREFIX) and // add to matches if it succeeds. END. // // If inGlobStar and PREFIX is symlink and points to dir // set ENTRIES = [] // else readdir(PREFIX) as ENTRIES // If fail, END // // with ENTRIES // If pattern[n] is GLOBSTAR // // handle the case where the globstar match is empty // // by pruning it out, and testing the resulting pattern // PROCESS(pattern[0..n] + pattern[n+1 .. $], false) // // handle other cases. // for ENTRY in ENTRIES (not dotfiles) // // attach globstar + tail onto the entry // // Mark that this entry is a globstar match // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) // // else // not globstar // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) // Test ENTRY against pattern[n] // If fails, continue // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) // // Caveat: // Cache all stats and readdirs results to minimize syscall. Since all // we ever care about is existence and directory-ness, we can just keep // `true` for files, and [children,...] for directories, or `false` for // things that don't exist. module.exports = glob var rp = __nccwpck_require__(46863) var minimatch = __nccwpck_require__(83973) var Minimatch = minimatch.Minimatch var inherits = __nccwpck_require__(44124) var EE = (__nccwpck_require__(82361).EventEmitter) var path = __nccwpck_require__(71017) var assert = __nccwpck_require__(39491) var isAbsolute = __nccwpck_require__(38714) var globSync = __nccwpck_require__(27967) var common = __nccwpck_require__(85888) var setopts = common.setopts var ownProp = common.ownProp var inflight = __nccwpck_require__(52492) var util = __nccwpck_require__(73837) var childrenIgnored = common.childrenIgnored var isIgnored = common.isIgnored var once = __nccwpck_require__(1223) function glob (pattern, options, cb) { if (typeof options === 'function') cb = options, options = {} if (!options) options = {} if (options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return globSync(pattern, options) } return new Glob(pattern, options, cb) } glob.sync = globSync var GlobSync = glob.GlobSync = globSync.GlobSync // old api surface glob.glob = glob function extend (origin, add) { if (add === null || typeof add !== 'object') { return origin } var keys = Object.keys(add) var i = keys.length while (i--) { origin[keys[i]] = add[keys[i]] } return origin } glob.hasMagic = function (pattern, options_) { var options = extend({}, options_) options.noprocess = true var g = new Glob(pattern, options) var set = g.minimatch.set if (!pattern) return false if (set.length > 1) return true for (var j = 0; j < set[0].length; j++) { if (typeof set[0][j] !== 'string') return true } return false } glob.Glob = Glob inherits(Glob, EE) function Glob (pattern, options, cb) { if (typeof options === 'function') { cb = options options = null } if (options && options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return new GlobSync(pattern, options) } if (!(this instanceof Glob)) return new Glob(pattern, options, cb) setopts(this, pattern, options) this._didRealPath = false // process each pattern in the minimatch set var n = this.minimatch.set.length // The matches are stored as {: true,...} so that // duplicates are automagically pruned. // Later, we do an Object.keys() on these. // Keep them as a list so we can fill in when nonull is set. this.matches = new Array(n) if (typeof cb === 'function') { cb = once(cb) this.on('error', cb) this.on('end', function (matches) { cb(null, matches) }) } var self = this this._processing = 0 this._emitQueue = [] this._processQueue = [] this.paused = false if (this.noprocess) return this if (n === 0) return done() var sync = true for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false, done) } sync = false function done () { --self._processing if (self._processing <= 0) { if (sync) { process.nextTick(function () { self._finish() }) } else { self._finish() } } } } Glob.prototype._finish = function () { assert(this instanceof Glob) if (this.aborted) return if (this.realpath && !this._didRealpath) return this._realpath() common.finish(this) this.emit('end', this.found) } Glob.prototype._realpath = function () { if (this._didRealpath) return this._didRealpath = true var n = this.matches.length if (n === 0) return this._finish() var self = this for (var i = 0; i < this.matches.length; i++) this._realpathSet(i, next) function next () { if (--n === 0) self._finish() } } Glob.prototype._realpathSet = function (index, cb) { var matchset = this.matches[index] if (!matchset) return cb() var found = Object.keys(matchset) var self = this var n = found.length if (n === 0) return cb() var set = this.matches[index] = Object.create(null) found.forEach(function (p, i) { // If there's a problem with the stat, then it means that // one or more of the links in the realpath couldn't be // resolved. just return the abs value in that case. p = self._makeAbs(p) rp.realpath(p, self.realpathCache, function (er, real) { if (!er) set[real] = true else if (er.syscall === 'stat') set[p] = true else self.emit('error', er) // srsly wtf right here if (--n === 0) { self.matches[index] = set cb() } }) }) } Glob.prototype._mark = function (p) { return common.mark(this, p) } Glob.prototype._makeAbs = function (f) { return common.makeAbs(this, f) } Glob.prototype.abort = function () { this.aborted = true this.emit('abort') } Glob.prototype.pause = function () { if (!this.paused) { this.paused = true this.emit('pause') } } Glob.prototype.resume = function () { if (this.paused) { this.emit('resume') this.paused = false if (this._emitQueue.length) { var eq = this._emitQueue.slice(0) this._emitQueue.length = 0 for (var i = 0; i < eq.length; i ++) { var e = eq[i] this._emitMatch(e[0], e[1]) } } if (this._processQueue.length) { var pq = this._processQueue.slice(0) this._processQueue.length = 0 for (var i = 0; i < pq.length; i ++) { var p = pq[i] this._processing-- this._process(p[0], p[1], p[2], p[3]) } } } } Glob.prototype._process = function (pattern, index, inGlobStar, cb) { assert(this instanceof Glob) assert(typeof cb === 'function') if (this.aborted) return this._processing++ if (this.paused) { this._processQueue.push([pattern, index, inGlobStar, cb]) return } //console.error('PROCESS %d', this._processing, pattern) // Get the first [n] parts of pattern that are all strings. var n = 0 while (typeof pattern[n] === 'string') { n ++ } // now n is the index of the first one that is *not* a string. // see if there's anything else var prefix switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index, cb) return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/') break } var remain = pattern.slice(n) // get the list of entries. var read if (prefix === null) read = '.' else if (isAbsolute(prefix) || isAbsolute(pattern.map(function (p) { return typeof p === 'string' ? p : '[*]' }).join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix } else read = prefix var abs = this._makeAbs(read) //if ignored, skip _processing if (childrenIgnored(this, read)) return cb() var isGlobStar = remain[0] === minimatch.GLOBSTAR if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) else this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) } Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this this._readdir(abs, inGlobStar, function (er, entries) { return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) }) } Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { // if the abs isn't a dir, then nothing can match! if (!entries) return cb() // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0] var negate = !!this.minimatch.negate var rawGlob = pn._glob var dotOk = this.dot || rawGlob.charAt(0) === '.' var matchedEntries = [] for (var i = 0; i < entries.length; i++) { var e = entries[i] if (e.charAt(0) !== '.' || dotOk) { var m if (negate && !prefix) { m = !e.match(pn) } else { m = e.match(pn) } if (m) matchedEntries.push(e) } } //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) var len = matchedEntries.length // If there are no matched entries, then nothing matches. if (len === 0) return cb() // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null) for (var i = 0; i < len; i ++) { var e = matchedEntries[i] if (prefix) { if (prefix !== '/') e = prefix + '/' + e else e = prefix + e } if (e.charAt(0) === '/' && !this.nomount) { e = path.join(this.root, e) } this._emitMatch(index, e) } // This was the last one, and no stats were needed return cb() } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift() for (var i = 0; i < len; i ++) { var e = matchedEntries[i] var newPattern if (prefix) { if (prefix !== '/') e = prefix + '/' + e else e = prefix + e } this._process([e].concat(remain), index, inGlobStar, cb) } cb() } Glob.prototype._emitMatch = function (index, e) { if (this.aborted) return if (isIgnored(this, e)) return if (this.paused) { this._emitQueue.push([index, e]) return } var abs = isAbsolute(e) ? e : this._makeAbs(e) if (this.mark) e = this._mark(e) if (this.absolute) e = abs if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs] if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true var st = this.statCache[abs] if (st) this.emit('stat', e, st) this.emit('match', e) } Glob.prototype._readdirInGlobStar = function (abs, cb) { if (this.aborted) return // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false, cb) var lstatkey = 'lstat\0' + abs var self = this var lstatcb = inflight(lstatkey, lstatcb_) if (lstatcb) self.fs.lstat(abs, lstatcb) function lstatcb_ (er, lstat) { if (er && er.code === 'ENOENT') return cb() var isSym = lstat && lstat.isSymbolicLink() self.symlinks[abs] = isSym // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) { self.cache[abs] = 'FILE' cb() } else self._readdir(abs, false, cb) } } Glob.prototype._readdir = function (abs, inGlobStar, cb) { if (this.aborted) return cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) if (!cb) return //console.error('RD %j %j', +inGlobStar, abs) if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs, cb) if (ownProp(this.cache, abs)) { var c = this.cache[abs] if (!c || c === 'FILE') return cb() if (Array.isArray(c)) return cb(null, c) } var self = this self.fs.readdir(abs, readdirCb(this, abs, cb)) } function readdirCb (self, abs, cb) { return function (er, entries) { if (er) self._readdirError(abs, er, cb) else self._readdirEntries(abs, entries, cb) } } Glob.prototype._readdirEntries = function (abs, entries, cb) { if (this.aborted) return // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i] if (abs === '/') e = abs + e else e = abs + '/' + e this.cache[e] = true } } this.cache[abs] = entries return cb(null, entries) } Glob.prototype._readdirError = function (f, er, cb) { if (this.aborted) return // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f) this.cache[abs] = 'FILE' if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd) error.path = this.cwd error.code = er.code this.emit('error', error) this.abort() } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false if (this.strict) { this.emit('error', er) // If the error is handled, then we abort // if not, we threw out of here this.abort() } if (!this.silent) console.error('glob error', er) break } return cb() } Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this this._readdir(abs, inGlobStar, function (er, entries) { self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) }) } Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { //console.error('pgs2', prefix, remain[0], entries) // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return cb() // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1) var gspref = prefix ? [ prefix ] : [] var noGlobStar = gspref.concat(remainWithoutGlobStar) // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false, cb) var isSym = this.symlinks[abs] var len = entries.length // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return cb() for (var i = 0; i < len; i++) { var e = entries[i] if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar) this._process(instead, index, true, cb) var below = gspref.concat(entries[i], remain) this._process(below, index, true, cb) } cb() } Glob.prototype._processSimple = function (prefix, index, cb) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var self = this this._stat(prefix, function (er, exists) { self._processSimple2(prefix, index, er, exists, cb) }) } Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { //console.error('ps2', prefix, exists) if (!this.matches[index]) this.matches[index] = Object.create(null) // If it doesn't exist, then just mark the lack of results if (!exists) return cb() if (prefix && isAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix) if (prefix.charAt(0) === '/') { prefix = path.join(this.root, prefix) } else { prefix = path.resolve(this.root, prefix) if (trail) prefix += '/' } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/') // Mark this as a match this._emitMatch(index, prefix) cb() } // Returns either 'DIR', 'FILE', or false Glob.prototype._stat = function (f, cb) { var abs = this._makeAbs(f) var needDir = f.slice(-1) === '/' if (f.length > this.maxLength) return cb() if (!this.stat && ownProp(this.cache, abs)) { var c = this.cache[abs] if (Array.isArray(c)) c = 'DIR' // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return cb(null, c) if (needDir && c === 'FILE') return cb() // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var exists var stat = this.statCache[abs] if (stat !== undefined) { if (stat === false) return cb(null, stat) else { var type = stat.isDirectory() ? 'DIR' : 'FILE' if (needDir && type === 'FILE') return cb() else return cb(null, type, stat) } } var self = this var statcb = inflight('stat\0' + abs, lstatcb_) if (statcb) self.fs.lstat(abs, statcb) function lstatcb_ (er, lstat) { if (lstat && lstat.isSymbolicLink()) { // If it's a symlink, then treat it as the target, unless // the target does not exist, then treat it as a file. return self.fs.stat(abs, function (er, stat) { if (er) self._stat2(f, abs, null, lstat, cb) else self._stat2(f, abs, er, stat, cb) }) } else { self._stat2(f, abs, er, lstat, cb) } } } Glob.prototype._stat2 = function (f, abs, er, stat, cb) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false return cb() } var needDir = f.slice(-1) === '/' this.statCache[abs] = stat if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) return cb(null, false, stat) var c = true if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE' this.cache[abs] = this.cache[abs] || c if (needDir && c === 'FILE') return cb() return cb(null, c, stat) } /***/ }), /***/ 27967: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = globSync globSync.GlobSync = GlobSync var rp = __nccwpck_require__(46863) var minimatch = __nccwpck_require__(83973) var Minimatch = minimatch.Minimatch var Glob = (__nccwpck_require__(46968).Glob) var util = __nccwpck_require__(73837) var path = __nccwpck_require__(71017) var assert = __nccwpck_require__(39491) var isAbsolute = __nccwpck_require__(38714) var common = __nccwpck_require__(85888) var setopts = common.setopts var ownProp = common.ownProp var childrenIgnored = common.childrenIgnored var isIgnored = common.isIgnored function globSync (pattern, options) { if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n'+ 'See: https://github.com/isaacs/node-glob/issues/167') return new GlobSync(pattern, options).found } function GlobSync (pattern, options) { if (!pattern) throw new Error('must provide pattern') if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n'+ 'See: https://github.com/isaacs/node-glob/issues/167') if (!(this instanceof GlobSync)) return new GlobSync(pattern, options) setopts(this, pattern, options) if (this.noprocess) return this var n = this.minimatch.set.length this.matches = new Array(n) for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false) } this._finish() } GlobSync.prototype._finish = function () { assert.ok(this instanceof GlobSync) if (this.realpath) { var self = this this.matches.forEach(function (matchset, index) { var set = self.matches[index] = Object.create(null) for (var p in matchset) { try { p = self._makeAbs(p) var real = rp.realpathSync(p, self.realpathCache) set[real] = true } catch (er) { if (er.syscall === 'stat') set[self._makeAbs(p)] = true else throw er } } }) } common.finish(this) } GlobSync.prototype._process = function (pattern, index, inGlobStar) { assert.ok(this instanceof GlobSync) // Get the first [n] parts of pattern that are all strings. var n = 0 while (typeof pattern[n] === 'string') { n ++ } // now n is the index of the first one that is *not* a string. // See if there's anything else var prefix switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index) return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/') break } var remain = pattern.slice(n) // get the list of entries. var read if (prefix === null) read = '.' else if (isAbsolute(prefix) || isAbsolute(pattern.map(function (p) { return typeof p === 'string' ? p : '[*]' }).join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix } else read = prefix var abs = this._makeAbs(read) //if ignored, skip processing if (childrenIgnored(this, read)) return var isGlobStar = remain[0] === minimatch.GLOBSTAR if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) else this._processReaddir(prefix, read, abs, remain, index, inGlobStar) } GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { var entries = this._readdir(abs, inGlobStar) // if the abs isn't a dir, then nothing can match! if (!entries) return // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0] var negate = !!this.minimatch.negate var rawGlob = pn._glob var dotOk = this.dot || rawGlob.charAt(0) === '.' var matchedEntries = [] for (var i = 0; i < entries.length; i++) { var e = entries[i] if (e.charAt(0) !== '.' || dotOk) { var m if (negate && !prefix) { m = !e.match(pn) } else { m = e.match(pn) } if (m) matchedEntries.push(e) } } var len = matchedEntries.length // If there are no matched entries, then nothing matches. if (len === 0) return // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null) for (var i = 0; i < len; i ++) { var e = matchedEntries[i] if (prefix) { if (prefix.slice(-1) !== '/') e = prefix + '/' + e else e = prefix + e } if (e.charAt(0) === '/' && !this.nomount) { e = path.join(this.root, e) } this._emitMatch(index, e) } // This was the last one, and no stats were needed return } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift() for (var i = 0; i < len; i ++) { var e = matchedEntries[i] var newPattern if (prefix) newPattern = [prefix, e] else newPattern = [e] this._process(newPattern.concat(remain), index, inGlobStar) } } GlobSync.prototype._emitMatch = function (index, e) { if (isIgnored(this, e)) return var abs = this._makeAbs(e) if (this.mark) e = this._mark(e) if (this.absolute) { e = abs } if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs] if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true if (this.stat) this._stat(e) } GlobSync.prototype._readdirInGlobStar = function (abs) { // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false) var entries var lstat var stat try { lstat = this.fs.lstatSync(abs) } catch (er) { if (er.code === 'ENOENT') { // lstat failed, doesn't exist return null } } var isSym = lstat && lstat.isSymbolicLink() this.symlinks[abs] = isSym // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) this.cache[abs] = 'FILE' else entries = this._readdir(abs, false) return entries } GlobSync.prototype._readdir = function (abs, inGlobStar) { var entries if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs) if (ownProp(this.cache, abs)) { var c = this.cache[abs] if (!c || c === 'FILE') return null if (Array.isArray(c)) return c } try { return this._readdirEntries(abs, this.fs.readdirSync(abs)) } catch (er) { this._readdirError(abs, er) return null } } GlobSync.prototype._readdirEntries = function (abs, entries) { // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i] if (abs === '/') e = abs + e else e = abs + '/' + e this.cache[e] = true } } this.cache[abs] = entries // mark and cache dir-ness return entries } GlobSync.prototype._readdirError = function (f, er) { // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f) this.cache[abs] = 'FILE' if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd) error.path = this.cwd error.code = er.code throw error } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false if (this.strict) throw er if (!this.silent) console.error('glob error', er) break } } GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { var entries = this._readdir(abs, inGlobStar) // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1) var gspref = prefix ? [ prefix ] : [] var noGlobStar = gspref.concat(remainWithoutGlobStar) // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false) var len = entries.length var isSym = this.symlinks[abs] // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return for (var i = 0; i < len; i++) { var e = entries[i] if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar) this._process(instead, index, true) var below = gspref.concat(entries[i], remain) this._process(below, index, true) } } GlobSync.prototype._processSimple = function (prefix, index) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var exists = this._stat(prefix) if (!this.matches[index]) this.matches[index] = Object.create(null) // If it doesn't exist, then just mark the lack of results if (!exists) return if (prefix && isAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix) if (prefix.charAt(0) === '/') { prefix = path.join(this.root, prefix) } else { prefix = path.resolve(this.root, prefix) if (trail) prefix += '/' } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/') // Mark this as a match this._emitMatch(index, prefix) } // Returns either 'DIR', 'FILE', or false GlobSync.prototype._stat = function (f) { var abs = this._makeAbs(f) var needDir = f.slice(-1) === '/' if (f.length > this.maxLength) return false if (!this.stat && ownProp(this.cache, abs)) { var c = this.cache[abs] if (Array.isArray(c)) c = 'DIR' // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return c if (needDir && c === 'FILE') return false // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var exists var stat = this.statCache[abs] if (!stat) { var lstat try { lstat = this.fs.lstatSync(abs) } catch (er) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false return false } } if (lstat && lstat.isSymbolicLink()) { try { stat = this.fs.statSync(abs) } catch (er) { stat = lstat } } else { stat = lstat } } this.statCache[abs] = stat var c = true if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE' this.cache[abs] = this.cache[abs] || c if (needDir && c === 'FILE') return false return c } GlobSync.prototype._mark = function (p) { return common.mark(this, p) } GlobSync.prototype._makeAbs = function (f) { return common.makeAbs(this, f) } /***/ }), /***/ 14959: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const assert = __nccwpck_require__(39491) const path = __nccwpck_require__(71017) const fs = __nccwpck_require__(57147) let glob = undefined try { glob = __nccwpck_require__(46968) } catch (_err) { // treat glob as optional. } const defaultGlobOpts = { nosort: true, silent: true } // for EMFILE handling let timeout = 0 const isWindows = (process.platform === "win32") const defaults = options => { const methods = [ 'unlink', 'chmod', 'stat', 'lstat', 'rmdir', 'readdir' ] methods.forEach(m => { options[m] = options[m] || fs[m] m = m + 'Sync' options[m] = options[m] || fs[m] }) options.maxBusyTries = options.maxBusyTries || 3 options.emfileWait = options.emfileWait || 1000 if (options.glob === false) { options.disableGlob = true } if (options.disableGlob !== true && glob === undefined) { throw Error('glob dependency not found, set `options.disableGlob = true` if intentional') } options.disableGlob = options.disableGlob || false options.glob = options.glob || defaultGlobOpts } const rimraf = (p, options, cb) => { if (typeof options === 'function') { cb = options options = {} } assert(p, 'rimraf: missing path') assert.equal(typeof p, 'string', 'rimraf: path should be a string') assert.equal(typeof cb, 'function', 'rimraf: callback function required') assert(options, 'rimraf: invalid options argument provided') assert.equal(typeof options, 'object', 'rimraf: options should be object') defaults(options) let busyTries = 0 let errState = null let n = 0 const next = (er) => { errState = errState || er if (--n === 0) cb(errState) } const afterGlob = (er, results) => { if (er) return cb(er) n = results.length if (n === 0) return cb() results.forEach(p => { const CB = (er) => { if (er) { if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && busyTries < options.maxBusyTries) { busyTries ++ // try again, with the same exact callback as this one. return setTimeout(() => rimraf_(p, options, CB), busyTries * 100) } // this one won't happen if graceful-fs is used. if (er.code === "EMFILE" && timeout < options.emfileWait) { return setTimeout(() => rimraf_(p, options, CB), timeout ++) } // already gone if (er.code === "ENOENT") er = null } timeout = 0 next(er) } rimraf_(p, options, CB) }) } if (options.disableGlob || !glob.hasMagic(p)) return afterGlob(null, [p]) options.lstat(p, (er, stat) => { if (!er) return afterGlob(null, [p]) glob(p, options.glob, afterGlob) }) } // Two possible strategies. // 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR // 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR // // Both result in an extra syscall when you guess wrong. However, there // are likely far more normal files in the world than directories. This // is based on the assumption that a the average number of files per // directory is >= 1. // // If anyone ever complains about this, then I guess the strategy could // be made configurable somehow. But until then, YAGNI. const rimraf_ = (p, options, cb) => { assert(p) assert(options) assert(typeof cb === 'function') // sunos lets the root user unlink directories, which is... weird. // so we have to lstat here and make sure it's not a dir. options.lstat(p, (er, st) => { if (er && er.code === "ENOENT") return cb(null) // Windows can EPERM on stat. Life is suffering. if (er && er.code === "EPERM" && isWindows) fixWinEPERM(p, options, er, cb) if (st && st.isDirectory()) return rmdir(p, options, er, cb) options.unlink(p, er => { if (er) { if (er.code === "ENOENT") return cb(null) if (er.code === "EPERM") return (isWindows) ? fixWinEPERM(p, options, er, cb) : rmdir(p, options, er, cb) if (er.code === "EISDIR") return rmdir(p, options, er, cb) } return cb(er) }) }) } const fixWinEPERM = (p, options, er, cb) => { assert(p) assert(options) assert(typeof cb === 'function') options.chmod(p, 0o666, er2 => { if (er2) cb(er2.code === "ENOENT" ? null : er) else options.stat(p, (er3, stats) => { if (er3) cb(er3.code === "ENOENT" ? null : er) else if (stats.isDirectory()) rmdir(p, options, er, cb) else options.unlink(p, cb) }) }) } const fixWinEPERMSync = (p, options, er) => { assert(p) assert(options) try { options.chmodSync(p, 0o666) } catch (er2) { if (er2.code === "ENOENT") return else throw er } let stats try { stats = options.statSync(p) } catch (er3) { if (er3.code === "ENOENT") return else throw er } if (stats.isDirectory()) rmdirSync(p, options, er) else options.unlinkSync(p) } const rmdir = (p, options, originalEr, cb) => { assert(p) assert(options) assert(typeof cb === 'function') // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) // if we guessed wrong, and it's not a directory, then // raise the original error. options.rmdir(p, er => { if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) rmkids(p, options, cb) else if (er && er.code === "ENOTDIR") cb(originalEr) else cb(er) }) } const rmkids = (p, options, cb) => { assert(p) assert(options) assert(typeof cb === 'function') options.readdir(p, (er, files) => { if (er) return cb(er) let n = files.length if (n === 0) return options.rmdir(p, cb) let errState files.forEach(f => { rimraf(path.join(p, f), options, er => { if (errState) return if (er) return cb(errState = er) if (--n === 0) options.rmdir(p, cb) }) }) }) } // this looks simpler, and is strictly *faster*, but will // tie up the JavaScript thread and fail on excessively // deep directory trees. const rimrafSync = (p, options) => { options = options || {} defaults(options) assert(p, 'rimraf: missing path') assert.equal(typeof p, 'string', 'rimraf: path should be a string') assert(options, 'rimraf: missing options') assert.equal(typeof options, 'object', 'rimraf: options should be object') let results if (options.disableGlob || !glob.hasMagic(p)) { results = [p] } else { try { options.lstatSync(p) results = [p] } catch (er) { results = glob.sync(p, options.glob) } } if (!results.length) return for (let i = 0; i < results.length; i++) { const p = results[i] let st try { st = options.lstatSync(p) } catch (er) { if (er.code === "ENOENT") return // Windows can EPERM on stat. Life is suffering. if (er.code === "EPERM" && isWindows) fixWinEPERMSync(p, options, er) } try { // sunos lets the root user unlink directories, which is... weird. if (st && st.isDirectory()) rmdirSync(p, options, null) else options.unlinkSync(p) } catch (er) { if (er.code === "ENOENT") return if (er.code === "EPERM") return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) if (er.code !== "EISDIR") throw er rmdirSync(p, options, er) } } } const rmdirSync = (p, options, originalEr) => { assert(p) assert(options) try { options.rmdirSync(p) } catch (er) { if (er.code === "ENOENT") return if (er.code === "ENOTDIR") throw originalEr if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") rmkidsSync(p, options) } } const rmkidsSync = (p, options) => { assert(p) assert(options) options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options)) // We only end up here once we got ENOTEMPTY at least once, and // at this point, we are guaranteed to have removed all the kids. // So, we know that it won't be ENOENT or ENOTDIR or anything else. // try really hard to delete stuff on windows, because it has a // PROFOUNDLY annoying habit of not closing handles promptly when // files are deleted, resulting in spurious ENOTEMPTY errors. const retries = isWindows ? 100 : 1 let i = 0 do { let threw = true try { const ret = options.rmdirSync(p, options) threw = false return ret } finally { if (++i < retries && threw) continue } } while (true) } module.exports = rimraf rimraf.sync = rimrafSync /***/ }), /***/ 21867: /***/ ((module, exports, __nccwpck_require__) => { /*! safe-buffer. MIT License. Feross Aboukhadijeh */ /* eslint-disable node/no-deprecated-api */ var buffer = __nccwpck_require__(14300) var Buffer = buffer.Buffer // alternative to using Object.keys for old browsers function copyProps (src, dst) { for (var key in src) { dst[key] = src[key] } } if (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) } SafeBuffer.prototype = Object.create(Buffer.prototype) // Copy static methods from Buffer copyProps(Buffer, SafeBuffer) SafeBuffer.from = function (arg, encodingOrOffset, length) { if (typeof arg === 'number') { throw new TypeError('Argument must not be a number') } 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) } /***/ }), /***/ 15118: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* eslint-disable node/no-deprecated-api */ var buffer = __nccwpck_require__(14300) var Buffer = buffer.Buffer var safer = {} var key for (key in buffer) { if (!buffer.hasOwnProperty(key)) continue if (key === 'SlowBuffer' || key === 'Buffer') continue safer[key] = buffer[key] } var Safer = safer.Buffer = {} for (key in Buffer) { if (!Buffer.hasOwnProperty(key)) continue if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue Safer[key] = Buffer[key] } safer.Buffer.prototype = Buffer.prototype if (!Safer.from || Safer.from === Uint8Array.from) { Safer.from = function (value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value) } if (value && typeof value.length === 'undefined') { throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value) } return Buffer(value, encodingOrOffset, length) } } if (!Safer.alloc) { Safer.alloc = function (size, fill, encoding) { if (typeof size !== 'number') { throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) } if (size < 0 || size >= 2 * (1 << 30)) { throw new RangeError('The value "' + size + '" is invalid for option "size"') } var buf = Buffer(size) if (!fill || fill.length === 0) { buf.fill(0) } else if (typeof encoding === 'string') { buf.fill(fill, encoding) } else { buf.fill(fill) } return buf } } if (!safer.kStringMaxLength) { try { safer.kStringMaxLength = process.binding('buffer').kStringMaxLength } catch (e) { // we can't determine kStringMaxLength in environments where process.binding // is unsupported, so let's not set it } } if (!safer.constants) { safer.constants = { MAX_LENGTH: safer.kMaxLength } if (safer.kStringMaxLength) { safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength } } module.exports = safer /***/ }), /***/ 66121: /***/ ((module) => { module.exports = shift function shift (stream) { var rs = stream._readableState if (!rs) return null return (rs.objectMode || typeof stream._duplexState === 'number') ? stream.read() : stream.read(getStateLength(rs)) } function getStateLength (state) { if (state.buffer.length) { // Since node 6.3.0 state.buffer is a BufferList not an array if (state.buffer.head) { return state.buffer.head.data.length } return state.buffer[0].length } return state.length } /***/ }), /***/ 94841: /***/ ((__unused_webpack_module, 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. /**/ var Buffer = (__nccwpck_require__(21867).Buffer); /**/ var isEncoding = Buffer.isEncoding || function (encoding) { encoding = '' + encoding; switch (encoding && encoding.toLowerCase()) { case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': return true; default: return false; } }; function _normalizeEncoding(enc) { if (!enc) return 'utf8'; var retried; while (true) { switch (enc) { case 'utf8': case 'utf-8': return 'utf8'; case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return 'utf16le'; case 'latin1': case 'binary': return 'latin1'; case 'base64': case 'ascii': case 'hex': return enc; default: if (retried) return; // undefined enc = ('' + enc).toLowerCase(); retried = true; } } }; // Do not cache `Buffer.isEncoding` when checking encoding names as some // modules monkey-patch it to support additional encodings function normalizeEncoding(enc) { var nenc = _normalizeEncoding(enc); if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); return nenc || enc; } // StringDecoder provides an interface for efficiently splitting a series of // buffers into a series of JS strings without breaking apart multi-byte // characters. exports.s = StringDecoder; function StringDecoder(encoding) { this.encoding = normalizeEncoding(encoding); var nb; switch (this.encoding) { case 'utf16le': this.text = utf16Text; this.end = utf16End; nb = 4; break; case 'utf8': this.fillLast = utf8FillLast; nb = 4; break; case 'base64': this.text = base64Text; this.end = base64End; nb = 3; break; default: this.write = simpleWrite; this.end = simpleEnd; return; } this.lastNeed = 0; this.lastTotal = 0; this.lastChar = Buffer.allocUnsafe(nb); } StringDecoder.prototype.write = function (buf) { if (buf.length === 0) return ''; var r; var i; if (this.lastNeed) { r = this.fillLast(buf); if (r === undefined) return ''; i = this.lastNeed; this.lastNeed = 0; } else { i = 0; } if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); return r || ''; }; StringDecoder.prototype.end = utf8End; // Returns only complete characters in a Buffer StringDecoder.prototype.text = utf8Text; // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer StringDecoder.prototype.fillLast = function (buf) { if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); this.lastNeed -= buf.length; }; // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a // continuation byte. If an invalid byte is detected, -2 is returned. function utf8CheckByte(byte) { if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; return byte >> 6 === 0x02 ? -1 : -2; } // Checks at most 3 bytes at the end of a Buffer in order to detect an // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) // needed to complete the UTF-8 character (if applicable) are returned. function utf8CheckIncomplete(self, buf, i) { var j = buf.length - 1; if (j < i) return 0; var nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 1; return nb; } if (--j < i || nb === -2) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 2; return nb; } if (--j < i || nb === -2) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) { if (nb === 2) nb = 0;else self.lastNeed = nb - 3; } return nb; } return 0; } // Validates as many continuation bytes for a multi-byte UTF-8 character as // needed or are available. If we see a non-continuation byte where we expect // one, we "replace" the validated continuation bytes we've seen so far with // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding // behavior. The continuation byte check is included three times in the case // where all of the continuation bytes for a character exist in the same buffer. // It is also done this way as a slight performance increase instead of using a // loop. function utf8CheckExtraBytes(self, buf, p) { if ((buf[0] & 0xC0) !== 0x80) { self.lastNeed = 0; return '\ufffd'; } if (self.lastNeed > 1 && buf.length > 1) { if ((buf[1] & 0xC0) !== 0x80) { self.lastNeed = 1; return '\ufffd'; } if (self.lastNeed > 2 && buf.length > 2) { if ((buf[2] & 0xC0) !== 0x80) { self.lastNeed = 2; return '\ufffd'; } } } } // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. function utf8FillLast(buf) { var p = this.lastTotal - this.lastNeed; var r = utf8CheckExtraBytes(this, buf, p); if (r !== undefined) return r; if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, p, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, p, 0, buf.length); this.lastNeed -= buf.length; } // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a // partial character, the character's bytes are buffered until the required // number of bytes are available. function utf8Text(buf, i) { var total = utf8CheckIncomplete(this, buf, i); if (!this.lastNeed) return buf.toString('utf8', i); this.lastTotal = total; var end = buf.length - (total - this.lastNeed); buf.copy(this.lastChar, 0, end); return buf.toString('utf8', i, end); } // For UTF-8, a replacement character is added when ending on a partial // character. function utf8End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + '\ufffd'; return r; } // UTF-16LE typically needs two bytes per character, but even if we have an even // number of bytes available, we need to check if we end on a leading/high // surrogate. In that case, we need to wait for the next two bytes in order to // decode the last character properly. function utf16Text(buf, i) { if ((buf.length - i) % 2 === 0) { var r = buf.toString('utf16le', i); if (r) { var c = r.charCodeAt(r.length - 1); if (c >= 0xD800 && c <= 0xDBFF) { this.lastNeed = 2; this.lastTotal = 4; this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; return r.slice(0, -1); } } return r; } this.lastNeed = 1; this.lastTotal = 2; this.lastChar[0] = buf[buf.length - 1]; return buf.toString('utf16le', i, buf.length - 1); } // For UTF-16LE we do not explicitly append special replacement characters if we // end on a partial character, we simply let v8 handle that. function utf16End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) { var end = this.lastTotal - this.lastNeed; return r + this.lastChar.toString('utf16le', 0, end); } return r; } function base64Text(buf, i) { var n = (buf.length - i) % 3; if (n === 0) return buf.toString('base64', i); this.lastNeed = 3 - n; this.lastTotal = 3; if (n === 1) { this.lastChar[0] = buf[buf.length - 1]; } else { this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; } return buf.toString('base64', i, buf.length - n); } function base64End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); return r; } // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) function simpleWrite(buf) { return buf.toString(this.encoding); } function simpleEnd(buf) { return buf && buf.length ? this.write(buf) : ''; } /***/ }), /***/ 14526: /***/ ((module) => { const hexRegex = /^[-+]?0x[a-fA-F0-9]+$/; const numRegex = /^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/; // const octRegex = /0x[a-z0-9]+/; // const binRegex = /0x[a-z0-9]+/; //polyfill if (!Number.parseInt && window.parseInt) { Number.parseInt = window.parseInt; } if (!Number.parseFloat && window.parseFloat) { Number.parseFloat = window.parseFloat; } const consider = { hex : true, leadingZeros: true, decimalPoint: "\.", eNotation: true //skipLike: /regex/ }; function toNumber(str, options = {}){ // const options = Object.assign({}, consider); // if(opt.leadingZeros === false){ // options.leadingZeros = false; // }else if(opt.hex === false){ // options.hex = false; // } options = Object.assign({}, consider, options ); if(!str || typeof str !== "string" ) return str; let trimmedStr = str.trim(); // if(trimmedStr === "0.0") return 0; // else if(trimmedStr === "+0.0") return 0; // else if(trimmedStr === "-0.0") return -0; if(options.skipLike !== undefined && options.skipLike.test(trimmedStr)) return str; else if (options.hex && hexRegex.test(trimmedStr)) { return Number.parseInt(trimmedStr, 16); // } else if (options.parseOct && octRegex.test(str)) { // return Number.parseInt(val, 8); // }else if (options.parseBin && binRegex.test(str)) { // return Number.parseInt(val, 2); }else{ //separate negative sign, leading zeros, and rest number const match = numRegex.exec(trimmedStr); if(match){ const sign = match[1]; const leadingZeros = match[2]; let numTrimmedByZeros = trimZeros(match[3]); //complete num without leading zeros //trim ending zeros for floating number const eNotation = match[4] || match[6]; if(!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== ".") return str; //-0123 else if(!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== ".") return str; //0123 else{//no leading zeros or leading zeros are allowed const num = Number(trimmedStr); const numStr = "" + num; if(numStr.search(/[eE]/) !== -1){ //given number is long and parsed to eNotation if(options.eNotation) return num; else return str; }else if(eNotation){ //given number has enotation if(options.eNotation) return num; else return str; }else if(trimmedStr.indexOf(".") !== -1){ //floating number // const decimalPart = match[5].substr(1); // const intPart = trimmedStr.substr(0,trimmedStr.indexOf(".")); // const p = numStr.indexOf("."); // const givenIntPart = numStr.substr(0,p); // const givenDecPart = numStr.substr(p+1); if(numStr === "0" && (numTrimmedByZeros === "") ) return num; //0.0 else if(numStr === numTrimmedByZeros) return num; //0.456. 0.79000 else if( sign && numStr === "-"+numTrimmedByZeros) return num; else return str; } if(leadingZeros){ // if(numTrimmedByZeros === numStr){ // if(options.leadingZeros) return num; // else return str; // }else return str; if(numTrimmedByZeros === numStr) return num; else if(sign+numTrimmedByZeros === numStr) return num; else return str; } if(trimmedStr === numStr) return num; else if(trimmedStr === sign+numStr) return num; // else{ // //number with +/- sign // trimmedStr.test(/[-+][0-9]); // } return str; } // else if(!eNotation && trimmedStr && trimmedStr !== Number(trimmedStr) ) return str; }else{ //non-numeric string return str; } } } /** * * @param {string} numStr without leading zeros * @returns */ function trimZeros(numStr){ if(numStr && numStr.indexOf(".") !== -1){//float numStr = numStr.replace(/0+$/, ""); //remove ending zeros if(numStr === ".") numStr = "0"; else if(numStr[0] === ".") numStr = "0"+numStr; else if(numStr[numStr.length-1] === ".") numStr = numStr.substr(0,numStr.length-1); return numStr; } return numStr; } module.exports = toNumber /***/ }), /***/ 68065: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { promisify } = __nccwpck_require__(73837); const tmp = __nccwpck_require__(8517); // file module.exports.fileSync = tmp.fileSync; const fileWithOptions = promisify((options, cb) => tmp.file(options, (err, path, fd, cleanup) => err ? cb(err) : cb(undefined, { path, fd, cleanup: promisify(cleanup) }) ) ); module.exports.file = async (options) => fileWithOptions(options); module.exports.withFile = async function withFile(fn, options) { const { path, fd, cleanup } = await module.exports.file(options); try { return await fn({ path, fd }); } finally { await cleanup(); } }; // directory module.exports.dirSync = tmp.dirSync; const dirWithOptions = promisify((options, cb) => tmp.dir(options, (err, path, cleanup) => err ? cb(err) : cb(undefined, { path, cleanup: promisify(cleanup) }) ) ); module.exports.dir = async (options) => dirWithOptions(options); module.exports.withDir = async function withDir(fn, options) { const { path, cleanup } = await module.exports.dir(options); try { return await fn({ path }); } finally { await cleanup(); } }; // name generation module.exports.tmpNameSync = tmp.tmpNameSync; module.exports.tmpName = promisify(tmp.tmpName); module.exports.tmpdir = tmp.tmpdir; module.exports.setGracefulCleanup = tmp.setGracefulCleanup; /***/ }), /***/ 8517: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /*! * Tmp * * Copyright (c) 2011-2017 KARASZI Istvan * * MIT Licensed */ /* * Module dependencies. */ const fs = __nccwpck_require__(57147); const os = __nccwpck_require__(22037); const path = __nccwpck_require__(71017); const crypto = __nccwpck_require__(6113); const _c = { fs: fs.constants, os: os.constants }; const rimraf = __nccwpck_require__(14959); /* * The working inner variables. */ const // the random characters to choose from RANDOM_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', TEMPLATE_PATTERN = /XXXXXX/, DEFAULT_TRIES = 3, CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR), // constants are off on the windows platform and will not match the actual errno codes IS_WIN32 = os.platform() === 'win32', EBADF = _c.EBADF || _c.os.errno.EBADF, ENOENT = _c.ENOENT || _c.os.errno.ENOENT, DIR_MODE = 0o700 /* 448 */, FILE_MODE = 0o600 /* 384 */, EXIT = 'exit', // this will hold the objects need to be removed on exit _removeObjects = [], // API change in fs.rmdirSync leads to error when passing in a second parameter, e.g. the callback FN_RMDIR_SYNC = fs.rmdirSync.bind(fs), FN_RIMRAF_SYNC = rimraf.sync; let _gracefulCleanup = false; /** * Gets a temporary file name. * * @param {(Options|tmpNameCallback)} options options or callback * @param {?tmpNameCallback} callback the callback function */ function tmpName(options, callback) { const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; try { _assertAndSanitizeOptions(opts); } catch (err) { return cb(err); } let tries = opts.tries; (function _getUniqueName() { try { const name = _generateTmpName(opts); // check whether the path exists then retry if needed fs.stat(name, function (err) { /* istanbul ignore else */ if (!err) { /* istanbul ignore else */ if (tries-- > 0) return _getUniqueName(); return cb(new Error('Could not get a unique tmp filename, max tries reached ' + name)); } cb(null, name); }); } catch (err) { cb(err); } }()); } /** * Synchronous version of tmpName. * * @param {Object} options * @returns {string} the generated random name * @throws {Error} if the options are invalid or could not generate a filename */ function tmpNameSync(options) { const args = _parseArguments(options), opts = args[0]; _assertAndSanitizeOptions(opts); let tries = opts.tries; do { const name = _generateTmpName(opts); try { fs.statSync(name); } catch (e) { return name; } } while (tries-- > 0); throw new Error('Could not get a unique tmp filename, max tries reached'); } /** * Creates and opens a temporary file. * * @param {(Options|null|undefined|fileCallback)} options the config options or the callback function or null or undefined * @param {?fileCallback} callback */ function file(options, callback) { const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; // gets a temporary filename tmpName(opts, function _tmpNameCreated(err, name) { /* istanbul ignore else */ if (err) return cb(err); // create and open the file fs.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err, fd) { /* istanbu ignore else */ if (err) return cb(err); if (opts.discardDescriptor) { return fs.close(fd, function _discardCallback(possibleErr) { // the chance of getting an error on close here is rather low and might occur in the most edgiest cases only return cb(possibleErr, name, undefined, _prepareTmpFileRemoveCallback(name, -1, opts, false)); }); } else { // detachDescriptor passes the descriptor whereas discardDescriptor closes it, either way, we no longer care // about the descriptor const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; cb(null, name, fd, _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, false)); } }); }); } /** * Synchronous version of file. * * @param {Options} options * @returns {FileSyncObject} object consists of name, fd and removeCallback * @throws {Error} if cannot create a file */ function fileSync(options) { const args = _parseArguments(options), opts = args[0]; const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; const name = tmpNameSync(opts); var fd = fs.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE); /* istanbul ignore else */ if (opts.discardDescriptor) { fs.closeSync(fd); fd = undefined; } return { name: name, fd: fd, removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, true) }; } /** * Creates a temporary directory. * * @param {(Options|dirCallback)} options the options or the callback function * @param {?dirCallback} callback */ function dir(options, callback) { const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; // gets a temporary filename tmpName(opts, function _tmpNameCreated(err, name) { /* istanbul ignore else */ if (err) return cb(err); // create the directory fs.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err) { /* istanbul ignore else */ if (err) return cb(err); cb(null, name, _prepareTmpDirRemoveCallback(name, opts, false)); }); }); } /** * Synchronous version of dir. * * @param {Options} options * @returns {DirSyncObject} object consists of name and removeCallback * @throws {Error} if it cannot create a directory */ function dirSync(options) { const args = _parseArguments(options), opts = args[0]; const name = tmpNameSync(opts); fs.mkdirSync(name, opts.mode || DIR_MODE); return { name: name, removeCallback: _prepareTmpDirRemoveCallback(name, opts, true) }; } /** * Removes files asynchronously. * * @param {Object} fdPath * @param {Function} next * @private */ function _removeFileAsync(fdPath, next) { const _handler = function (err) { if (err && !_isENOENT(err)) { // reraise any unanticipated error return next(err); } next(); }; if (0 <= fdPath[0]) fs.close(fdPath[0], function () { fs.unlink(fdPath[1], _handler); }); else fs.unlink(fdPath[1], _handler); } /** * Removes files synchronously. * * @param {Object} fdPath * @private */ function _removeFileSync(fdPath) { let rethrownException = null; try { if (0 <= fdPath[0]) fs.closeSync(fdPath[0]); } catch (e) { // reraise any unanticipated error if (!_isEBADF(e) && !_isENOENT(e)) throw e; } finally { try { fs.unlinkSync(fdPath[1]); } catch (e) { // reraise any unanticipated error if (!_isENOENT(e)) rethrownException = e; } } if (rethrownException !== null) { throw rethrownException; } } /** * Prepares the callback for removal of the temporary file. * * Returns either a sync callback or a async callback depending on whether * fileSync or file was called, which is expressed by the sync parameter. * * @param {string} name the path of the file * @param {number} fd file descriptor * @param {Object} opts * @param {boolean} sync * @returns {fileCallback | fileCallbackSync} * @private */ function _prepareTmpFileRemoveCallback(name, fd, opts, sync) { const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name], sync); const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], sync, removeCallbackSync); if (!opts.keep) _removeObjects.unshift(removeCallbackSync); return sync ? removeCallbackSync : removeCallback; } /** * Prepares the callback for removal of the temporary directory. * * Returns either a sync callback or a async callback depending on whether * tmpFileSync or tmpFile was called, which is expressed by the sync parameter. * * @param {string} name * @param {Object} opts * @param {boolean} sync * @returns {Function} the callback * @private */ function _prepareTmpDirRemoveCallback(name, opts, sync) { const removeFunction = opts.unsafeCleanup ? rimraf : fs.rmdir.bind(fs); const removeFunctionSync = opts.unsafeCleanup ? FN_RIMRAF_SYNC : FN_RMDIR_SYNC; const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name, sync); const removeCallback = _prepareRemoveCallback(removeFunction, name, sync, removeCallbackSync); if (!opts.keep) _removeObjects.unshift(removeCallbackSync); return sync ? removeCallbackSync : removeCallback; } /** * Creates a guarded function wrapping the removeFunction call. * * The cleanup callback is save to be called multiple times. * Subsequent invocations will be ignored. * * @param {Function} removeFunction * @param {string} fileOrDirName * @param {boolean} sync * @param {cleanupCallbackSync?} cleanupCallbackSync * @returns {cleanupCallback | cleanupCallbackSync} * @private */ function _prepareRemoveCallback(removeFunction, fileOrDirName, sync, cleanupCallbackSync) { let called = false; // if sync is true, the next parameter will be ignored return function _cleanupCallback(next) { /* istanbul ignore else */ if (!called) { // remove cleanupCallback from cache const toRemove = cleanupCallbackSync || _cleanupCallback; const index = _removeObjects.indexOf(toRemove); /* istanbul ignore else */ if (index >= 0) _removeObjects.splice(index, 1); called = true; if (sync || removeFunction === FN_RMDIR_SYNC || removeFunction === FN_RIMRAF_SYNC) { return removeFunction(fileOrDirName); } else { return removeFunction(fileOrDirName, next || function() {}); } } }; } /** * The garbage collector. * * @private */ function _garbageCollector() { /* istanbul ignore else */ if (!_gracefulCleanup) return; // the function being called removes itself from _removeObjects, // loop until _removeObjects is empty while (_removeObjects.length) { try { _removeObjects[0](); } catch (e) { // already removed? } } } /** * Random name generator based on crypto. * Adapted from http://blog.tompawlak.org/how-to-generate-random-values-nodejs-javascript * * @param {number} howMany * @returns {string} the generated random name * @private */ function _randomChars(howMany) { let value = [], rnd = null; // make sure that we do not fail because we ran out of entropy try { rnd = crypto.randomBytes(howMany); } catch (e) { rnd = crypto.pseudoRandomBytes(howMany); } for (var i = 0; i < howMany; i++) { value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]); } return value.join(''); } /** * Helper which determines whether a string s is blank, that is undefined, or empty or null. * * @private * @param {string} s * @returns {Boolean} true whether the string s is blank, false otherwise */ function _isBlank(s) { return s === null || _isUndefined(s) || !s.trim(); } /** * Checks whether the `obj` parameter is defined or not. * * @param {Object} obj * @returns {boolean} true if the object is undefined * @private */ function _isUndefined(obj) { return typeof obj === 'undefined'; } /** * Parses the function arguments. * * This function helps to have optional arguments. * * @param {(Options|null|undefined|Function)} options * @param {?Function} callback * @returns {Array} parsed arguments * @private */ function _parseArguments(options, callback) { /* istanbul ignore else */ if (typeof options === 'function') { return [{}, options]; } /* istanbul ignore else */ if (_isUndefined(options)) { return [{}, callback]; } // copy options so we do not leak the changes we make internally const actualOptions = {}; for (const key of Object.getOwnPropertyNames(options)) { actualOptions[key] = options[key]; } return [actualOptions, callback]; } /** * Generates a new temporary name. * * @param {Object} opts * @returns {string} the new random name according to opts * @private */ function _generateTmpName(opts) { const tmpDir = opts.tmpdir; /* istanbul ignore else */ if (!_isUndefined(opts.name)) return path.join(tmpDir, opts.dir, opts.name); /* istanbul ignore else */ if (!_isUndefined(opts.template)) return path.join(tmpDir, opts.dir, opts.template).replace(TEMPLATE_PATTERN, _randomChars(6)); // prefix and postfix const name = [ opts.prefix ? opts.prefix : 'tmp', '-', process.pid, '-', _randomChars(12), opts.postfix ? '-' + opts.postfix : '' ].join(''); return path.join(tmpDir, opts.dir, name); } /** * Asserts whether the specified options are valid, also sanitizes options and provides sane defaults for missing * options. * * @param {Options} options * @private */ function _assertAndSanitizeOptions(options) { options.tmpdir = _getTmpDir(options); const tmpDir = options.tmpdir; /* istanbul ignore else */ if (!_isUndefined(options.name)) _assertIsRelative(options.name, 'name', tmpDir); /* istanbul ignore else */ if (!_isUndefined(options.dir)) _assertIsRelative(options.dir, 'dir', tmpDir); /* istanbul ignore else */ if (!_isUndefined(options.template)) { _assertIsRelative(options.template, 'template', tmpDir); if (!options.template.match(TEMPLATE_PATTERN)) throw new Error(`Invalid template, found "${options.template}".`); } /* istanbul ignore else */ if (!_isUndefined(options.tries) && isNaN(options.tries) || options.tries < 0) throw new Error(`Invalid tries, found "${options.tries}".`); // if a name was specified we will try once options.tries = _isUndefined(options.name) ? options.tries || DEFAULT_TRIES : 1; options.keep = !!options.keep; options.detachDescriptor = !!options.detachDescriptor; options.discardDescriptor = !!options.discardDescriptor; options.unsafeCleanup = !!options.unsafeCleanup; // sanitize dir, also keep (multiple) blanks if the user, purportedly sane, requests us to options.dir = _isUndefined(options.dir) ? '' : path.relative(tmpDir, _resolvePath(options.dir, tmpDir)); options.template = _isUndefined(options.template) ? undefined : path.relative(tmpDir, _resolvePath(options.template, tmpDir)); // sanitize further if template is relative to options.dir options.template = _isBlank(options.template) ? undefined : path.relative(options.dir, options.template); // for completeness' sake only, also keep (multiple) blanks if the user, purportedly sane, requests us to options.name = _isUndefined(options.name) ? undefined : _sanitizeName(options.name); options.prefix = _isUndefined(options.prefix) ? '' : options.prefix; options.postfix = _isUndefined(options.postfix) ? '' : options.postfix; } /** * Resolve the specified path name in respect to tmpDir. * * The specified name might include relative path components, e.g. ../ * so we need to resolve in order to be sure that is is located inside tmpDir * * @param name * @param tmpDir * @returns {string} * @private */ function _resolvePath(name, tmpDir) { const sanitizedName = _sanitizeName(name); if (sanitizedName.startsWith(tmpDir)) { return path.resolve(sanitizedName); } else { return path.resolve(path.join(tmpDir, sanitizedName)); } } /** * Sanitize the specified path name by removing all quote characters. * * @param name * @returns {string} * @private */ function _sanitizeName(name) { if (_isBlank(name)) { return name; } return name.replace(/["']/g, ''); } /** * Asserts whether specified name is relative to the specified tmpDir. * * @param {string} name * @param {string} option * @param {string} tmpDir * @throws {Error} * @private */ function _assertIsRelative(name, option, tmpDir) { if (option === 'name') { // assert that name is not absolute and does not contain a path if (path.isAbsolute(name)) throw new Error(`${option} option must not contain an absolute path, found "${name}".`); // must not fail on valid . or .. or similar such constructs let basename = path.basename(name); if (basename === '..' || basename === '.' || basename !== name) throw new Error(`${option} option must not contain a path, found "${name}".`); } else { // if (option === 'dir' || option === 'template') { // assert that dir or template are relative to tmpDir if (path.isAbsolute(name) && !name.startsWith(tmpDir)) { throw new Error(`${option} option must be relative to "${tmpDir}", found "${name}".`); } let resolvedPath = _resolvePath(name, tmpDir); if (!resolvedPath.startsWith(tmpDir)) throw new Error(`${option} option must be relative to "${tmpDir}", found "${resolvedPath}".`); } } /** * Helper for testing against EBADF to compensate changes made to Node 7.x under Windows. * * @private */ function _isEBADF(error) { return _isExpectedError(error, -EBADF, 'EBADF'); } /** * Helper for testing against ENOENT to compensate changes made to Node 7.x under Windows. * * @private */ function _isENOENT(error) { return _isExpectedError(error, -ENOENT, 'ENOENT'); } /** * Helper to determine whether the expected error code matches the actual code and errno, * which will differ between the supported node versions. * * - Node >= 7.0: * error.code {string} * error.errno {number} any numerical value will be negated * * CAVEAT * * On windows, the errno for EBADF is -4083 but os.constants.errno.EBADF is different and we must assume that ENOENT * is no different here. * * @param {SystemError} error * @param {number} errno * @param {string} code * @private */ function _isExpectedError(error, errno, code) { return IS_WIN32 ? error.code === code : error.code === code && error.errno === errno; } /** * Sets the graceful cleanup. * * If graceful cleanup is set, tmp will remove all controlled temporary objects on process exit, otherwise the * temporary objects will remain in place, waiting to be cleaned up on system restart or otherwise scheduled temporary * object removals. */ function setGracefulCleanup() { _gracefulCleanup = true; } /** * Returns the currently configured tmp dir from os.tmpdir(). * * @private * @param {?Options} options * @returns {string} the currently configured tmp dir */ function _getTmpDir(options) { return path.resolve(_sanitizeName(options && options.tmpdir || os.tmpdir())); } // Install process exit listener process.addListener(EXIT, _garbageCollector); /** * Configuration options. * * @typedef {Object} Options * @property {?boolean} keep the temporary object (file or dir) will not be garbage collected * @property {?number} tries the number of tries before give up the name generation * @property (?int) mode the access mode, defaults are 0o700 for directories and 0o600 for files * @property {?string} template the "mkstemp" like filename template * @property {?string} name fixed name relative to tmpdir or the specified dir option * @property {?string} dir tmp directory relative to the root tmp directory in use * @property {?string} prefix prefix for the generated name * @property {?string} postfix postfix for the generated name * @property {?string} tmpdir the root tmp directory which overrides the os tmpdir * @property {?boolean} unsafeCleanup recursively removes the created temporary directory, even when it's not empty * @property {?boolean} detachDescriptor detaches the file descriptor, caller is responsible for closing the file, tmp will no longer try closing the file during garbage collection * @property {?boolean} discardDescriptor discards the file descriptor (closes file, fd is -1), tmp will no longer try closing the file during garbage collection */ /** * @typedef {Object} FileSyncObject * @property {string} name the name of the file * @property {string} fd the file descriptor or -1 if the fd has been discarded * @property {fileCallback} removeCallback the callback function to remove the file */ /** * @typedef {Object} DirSyncObject * @property {string} name the name of the directory * @property {fileCallback} removeCallback the callback function to remove the directory */ /** * @callback tmpNameCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name */ /** * @callback fileCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {number} fd the file descriptor or -1 if the fd had been discarded * @param {cleanupCallback} fn the cleanup callback function */ /** * @callback fileCallbackSync * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {number} fd the file descriptor or -1 if the fd had been discarded * @param {cleanupCallbackSync} fn the cleanup callback function */ /** * @callback dirCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {cleanupCallback} fn the cleanup callback function */ /** * @callback dirCallbackSync * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {cleanupCallbackSync} fn the cleanup callback function */ /** * Removes the temporary created file or directory. * * @callback cleanupCallback * @param {simpleCallback} [next] function to call whenever the tmp object needs to be removed */ /** * Removes the temporary created file or directory. * * @callback cleanupCallbackSync */ /** * Callback function for function composition. * @see {@link https://github.com/raszi/node-tmp/issues/57|raszi/node-tmp#57} * * @callback simpleCallback */ // exporting all the needed methods // evaluate _getTmpDir() lazily, mainly for simplifying testing but it also will // allow users to reconfigure the temporary directory Object.defineProperty(module.exports, "tmpdir", ({ enumerable: true, configurable: false, get: function () { return _getTmpDir(); } })); module.exports.dir = dir; module.exports.dirSync = dirSync; module.exports.file = file; module.exports.fileSync = fileSync; module.exports.tmpName = tmpName; module.exports.tmpNameSync = tmpNameSync; module.exports.setGracefulCleanup = setGracefulCleanup; /***/ }), /***/ 4351: /***/ ((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, Symbol, Reflect, Promise, SuppressedError */ var __extends; var __assign; var __rest; var __decorate; var __param; var __esDecorate; var __runInitializers; var __propKey; var __setFunctionName; var __metadata; var __awaiter; var __generator; 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; var __addDisposableResource; var __disposeResources; (function (factory) { var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; if (typeof define === "function" && define.amd) { 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.unshift(_); } else if (_ = accept(result)) { if (kind === "field") initializers.unshift(_); else descriptor[key] = _; } } if (target) Object.defineProperty(target, contextIn.name, descriptor); done = true; }; __runInitializers = function (thisArg, initializers, value) { var useValue = arguments.length > 2; for (var i = 0; i < initializers.length; i++) { value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); } return useValue ? value : void 0; }; __propKey = function (x) { return typeof x === "symbol" ? x : "".concat(x); }; __setFunctionName = function (f, name, prefix) { if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); }; __metadata = function (metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); }; __awaiter = function (thisArg, _arguments, P, generator) { 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); }; __addDisposableResource = function (env, value, async) { if (value !== null && value !== void 0) { if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); var dispose; if (async) { if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); dispose = value[Symbol.asyncDispose]; } if (dispose === void 0) { if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); dispose = value[Symbol.dispose]; } if (typeof dispose !== "function") throw new TypeError("Object not disposable."); env.stack.push({ value: value, dispose: dispose, async: async }); } else if (async) { env.stack.push({ async: true }); } return value; }; var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; __disposeResources = function (env) { function fail(e) { env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; env.hasError = true; } function next() { while (env.stack.length) { var rec = env.stack.pop(); try { var result = rec.dispose && rec.dispose.call(rec.value); if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); } catch (e) { fail(e); } } if (env.hasError) throw env.error; } return next(); }; exporter("__extends", __extends); exporter("__assign", __assign); exporter("__rest", __rest); exporter("__decorate", __decorate); exporter("__param", __param); exporter("__esDecorate", __esDecorate); exporter("__runInitializers", __runInitializers); exporter("__propKey", __propKey); exporter("__setFunctionName", __setFunctionName); exporter("__metadata", __metadata); exporter("__awaiter", __awaiter); exporter("__generator", __generator); 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); exporter("__addDisposableResource", __addDisposableResource); exporter("__disposeResources", __disposeResources); }); /***/ }), /***/ 74294: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = __nccwpck_require__(54219); /***/ }), /***/ 54219: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; var net = __nccwpck_require__(41808); var tls = __nccwpck_require__(24404); var http = __nccwpck_require__(13685); var https = __nccwpck_require__(95687); var events = __nccwpck_require__(82361); var assert = __nccwpck_require__(39491); var util = __nccwpck_require__(73837); exports.httpOverHttp = httpOverHttp; exports.httpsOverHttp = httpsOverHttp; exports.httpOverHttps = httpOverHttps; exports.httpsOverHttps = httpsOverHttps; function httpOverHttp(options) { var agent = new TunnelingAgent(options); agent.request = http.request; return agent; } function httpsOverHttp(options) { var agent = new TunnelingAgent(options); agent.request = http.request; agent.createSocket = createSecureSocket; agent.defaultPort = 443; return agent; } function httpOverHttps(options) { var agent = new TunnelingAgent(options); agent.request = https.request; return agent; } function httpsOverHttps(options) { var agent = new TunnelingAgent(options); agent.request = https.request; agent.createSocket = createSecureSocket; agent.defaultPort = 443; return agent; } function TunnelingAgent(options) { var self = this; self.options = options || {}; self.proxyOptions = self.options.proxy || {}; self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; self.requests = []; self.sockets = []; self.on('free', function onFree(socket, host, port, localAddress) { var options = toOptions(host, port, localAddress); for (var i = 0, len = self.requests.length; i < len; ++i) { var pending = self.requests[i]; if (pending.host === options.host && pending.port === options.port) { // Detect the request to connect same origin server, // reuse the connection. self.requests.splice(i, 1); pending.request.onSocket(socket); return; } } socket.destroy(); self.removeSocket(socket); }); } util.inherits(TunnelingAgent, events.EventEmitter); TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { var self = this; var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); if (self.sockets.length >= this.maxSockets) { // We are over limit so we'll add it to the queue. self.requests.push(options); return; } // If we are under maxSockets create a new one. self.createSocket(options, function(socket) { socket.on('free', onFree); socket.on('close', onCloseOrRemove); socket.on('agentRemove', onCloseOrRemove); req.onSocket(socket); function onFree() { self.emit('free', socket, options); } function onCloseOrRemove(err) { self.removeSocket(socket); socket.removeListener('free', onFree); socket.removeListener('close', onCloseOrRemove); socket.removeListener('agentRemove', onCloseOrRemove); } }); }; TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { var self = this; var placeholder = {}; self.sockets.push(placeholder); var connectOptions = mergeOptions({}, self.proxyOptions, { method: 'CONNECT', path: options.host + ':' + options.port, agent: false, headers: { host: options.host + ':' + options.port } }); if (options.localAddress) { connectOptions.localAddress = options.localAddress; } if (connectOptions.proxyAuth) { connectOptions.headers = connectOptions.headers || {}; connectOptions.headers['Proxy-Authorization'] = 'Basic ' + new Buffer(connectOptions.proxyAuth).toString('base64'); } debug('making CONNECT request'); var connectReq = self.request(connectOptions); connectReq.useChunkedEncodingByDefault = false; // for v0.6 connectReq.once('response', onResponse); // for v0.6 connectReq.once('upgrade', onUpgrade); // for v0.6 connectReq.once('connect', onConnect); // for v0.7 or later connectReq.once('error', onError); connectReq.end(); function onResponse(res) { // Very hacky. This is necessary to avoid http-parser leaks. res.upgrade = true; } function onUpgrade(res, socket, head) { // Hacky. process.nextTick(function() { onConnect(res, socket, head); }); } function onConnect(res, socket, head) { connectReq.removeAllListeners(); socket.removeAllListeners(); if (res.statusCode !== 200) { debug('tunneling socket could not be established, statusCode=%d', res.statusCode); socket.destroy(); var error = new Error('tunneling socket could not be established, ' + 'statusCode=' + res.statusCode); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); return; } if (head.length > 0) { debug('got illegal response body from proxy'); socket.destroy(); var error = new Error('got illegal response body from proxy'); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); return; } debug('tunneling connection has established'); self.sockets[self.sockets.indexOf(placeholder)] = socket; return cb(socket); } function onError(cause) { connectReq.removeAllListeners(); debug('tunneling socket could not be established, cause=%s\n', cause.message, cause.stack); var error = new Error('tunneling socket could not be established, ' + 'cause=' + cause.message); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); } }; TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { var pos = this.sockets.indexOf(socket) if (pos === -1) { return; } this.sockets.splice(pos, 1); var pending = this.requests.shift(); if (pending) { // If we have pending requests and a socket gets closed a new one // needs to be created to take over in the pool for the one that closed. this.createSocket(pending, function(socket) { pending.request.onSocket(socket); }); } }; function createSecureSocket(options, cb) { var self = this; TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { var hostHeader = options.request.getHeader('host'); var tlsOptions = mergeOptions({}, self.options, { socket: socket, servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host }); // 0 is dummy port for v0.6 var secureSocket = tls.connect(0, tlsOptions); self.sockets[self.sockets.indexOf(socket)] = secureSocket; cb(secureSocket); }); } function toOptions(host, port, localAddress) { if (typeof host === 'string') { // since v0.10 return { host: host, port: port, localAddress: localAddress }; } return host; // for v0.11 or later } function mergeOptions(target) { for (var i = 1, len = arguments.length; i < len; ++i) { var overrides = arguments[i]; if (typeof overrides === 'object') { var keys = Object.keys(overrides); for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { var k = keys[j]; if (overrides[k] !== undefined) { target[k] = overrides[k]; } } } } return target; } var debug; if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { debug = function() { var args = Array.prototype.slice.call(arguments); if (typeof args[0] === 'string') { args[0] = 'TUNNEL: ' + args[0]; } else { args.unshift('TUNNEL:'); } console.error.apply(console, args); } } else { debug = function() {}; } exports.debug = debug; // for test /***/ }), /***/ 65278: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** * For Node.js, simply re-export the core `util.deprecate` function. */ module.exports = __nccwpck_require__(73837).deprecate; /***/ }), /***/ 75840: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "v1", ({ enumerable: true, get: function () { return _v.default; } })); Object.defineProperty(exports, "v3", ({ enumerable: true, get: function () { return _v2.default; } })); Object.defineProperty(exports, "v4", ({ enumerable: true, get: function () { return _v3.default; } })); Object.defineProperty(exports, "v5", ({ enumerable: true, get: function () { return _v4.default; } })); Object.defineProperty(exports, "NIL", ({ enumerable: true, get: function () { return _nil.default; } })); Object.defineProperty(exports, "version", ({ enumerable: true, get: function () { return _version.default; } })); Object.defineProperty(exports, "validate", ({ enumerable: true, get: function () { return _validate.default; } })); Object.defineProperty(exports, "stringify", ({ enumerable: true, get: function () { return _stringify.default; } })); Object.defineProperty(exports, "parse", ({ enumerable: true, get: function () { return _parse.default; } })); var _v = _interopRequireDefault(__nccwpck_require__(78628)); var _v2 = _interopRequireDefault(__nccwpck_require__(86409)); var _v3 = _interopRequireDefault(__nccwpck_require__(85122)); var _v4 = _interopRequireDefault(__nccwpck_require__(79120)); var _nil = _interopRequireDefault(__nccwpck_require__(25332)); var _version = _interopRequireDefault(__nccwpck_require__(81595)); var _validate = _interopRequireDefault(__nccwpck_require__(66900)); var _stringify = _interopRequireDefault(__nccwpck_require__(18950)); var _parse = _interopRequireDefault(__nccwpck_require__(62746)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /***/ }), /***/ 4569: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function md5(bytes) { if (Array.isArray(bytes)) { bytes = Buffer.from(bytes); } else if (typeof bytes === 'string') { bytes = Buffer.from(bytes, 'utf8'); } return _crypto.default.createHash('md5').update(bytes).digest(); } var _default = md5; exports["default"] = _default; /***/ }), /***/ 25332: /***/ ((__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; /***/ }), /***/ 62746: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _validate = _interopRequireDefault(__nccwpck_require__(66900)); 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; /***/ }), /***/ 40814: /***/ ((__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; /***/ }), /***/ 50807: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = rng; var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate let poolPtr = rnds8Pool.length; function rng() { if (poolPtr > rnds8Pool.length - 16) { _crypto.default.randomFillSync(rnds8Pool); poolPtr = 0; } return rnds8Pool.slice(poolPtr, poolPtr += 16); } /***/ }), /***/ 85274: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function sha1(bytes) { if (Array.isArray(bytes)) { bytes = Buffer.from(bytes); } else if (typeof bytes === 'string') { bytes = Buffer.from(bytes, 'utf8'); } return _crypto.default.createHash('sha1').update(bytes).digest(); } var _default = sha1; exports["default"] = _default; /***/ }), /***/ 18950: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _validate = _interopRequireDefault(__nccwpck_require__(66900)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Convert array of 16 byte values to UUID string format of the form: * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */ const byteToHex = []; for (let i = 0; i < 256; ++i) { byteToHex.push((i + 0x100).toString(16).substr(1)); } function stringify(arr, offset = 0) { // Note: Be careful editing this code! It's been tuned for performance // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one // of the following: // - One or more input array values don't map to a hex octet (leading to // "undefined" in the uuid) // - Invalid input values for the RFC `version` or `variant` fields if (!(0, _validate.default)(uuid)) { throw TypeError('Stringified UUID is invalid'); } return uuid; } var _default = stringify; exports["default"] = _default; /***/ }), /***/ 78628: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _rng = _interopRequireDefault(__nccwpck_require__(50807)); var _stringify = _interopRequireDefault(__nccwpck_require__(18950)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // **`v1()` - Generate time-based UUID** // // Inspired by https://github.com/LiosK/UUID.js // and http://docs.python.org/library/uuid.html let _nodeId; let _clockseq; // Previous uuid creation time let _lastMSecs = 0; let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details function v1(options, buf, offset) { let i = buf && offset || 0; const b = buf || new Array(16); options = options || {}; let node = options.node || _nodeId; let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not // specified. We do this lazily to minimize issues related to insufficient // system entropy. See #189 if (node == null || clockseq == null) { const seedBytes = options.random || (options.rng || _rng.default)(); if (node == null) { // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; } if (clockseq == null) { // Per 4.2.2, randomize (14 bit) clockseq clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; } } // UUID timestamps are 100 nano-second units since the Gregorian epoch, // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock // cycle to simulate higher resolution clock let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression if (dt < 0 && options.clockseq === undefined) { clockseq = clockseq + 1 & 0x3fff; } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new // time interval if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { nsecs = 0; } // Per 4.2.1.2 Throw error if too many uuids are requested if (nsecs >= 10000) { throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); } _lastMSecs = msecs; _lastNSecs = nsecs; _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch msecs += 12219292800000; // `time_low` const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; b[i++] = tl >>> 24 & 0xff; b[i++] = tl >>> 16 & 0xff; b[i++] = tl >>> 8 & 0xff; b[i++] = tl & 0xff; // `time_mid` const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; b[i++] = tmh >>> 8 & 0xff; b[i++] = tmh & 0xff; // `time_high_and_version` b[i++] = tmh >>> 24 & 0xf | 0x10; // include version b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` b[i++] = clockseq & 0xff; // `node` for (let n = 0; n < 6; ++n) { b[i + n] = node[n]; } return buf || (0, _stringify.default)(b); } var _default = v1; exports["default"] = _default; /***/ }), /***/ 86409: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _v = _interopRequireDefault(__nccwpck_require__(65998)); var _md = _interopRequireDefault(__nccwpck_require__(4569)); 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; /***/ }), /***/ 65998: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = _default; exports.URL = exports.DNS = void 0; var _stringify = _interopRequireDefault(__nccwpck_require__(18950)); var _parse = _interopRequireDefault(__nccwpck_require__(62746)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function stringToBytes(str) { str = unescape(encodeURIComponent(str)); // UTF8 escape const bytes = []; for (let i = 0; i < str.length; ++i) { bytes.push(str.charCodeAt(i)); } return bytes; } const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; exports.DNS = DNS; const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; exports.URL = URL; function _default(name, version, hashfunc) { function generateUUID(value, namespace, buf, offset) { if (typeof value === 'string') { value = stringToBytes(value); } if (typeof namespace === 'string') { namespace = (0, _parse.default)(namespace); } if (namespace.length !== 16) { throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); } // Compute hash of namespace and value, Per 4.3 // Future: Use spread syntax when supported on all platforms, e.g. `bytes = // hashfunc([...namespace, ... value])` let bytes = new Uint8Array(16 + value.length); 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.default)(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; } /***/ }), /***/ 85122: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _rng = _interopRequireDefault(__nccwpck_require__(50807)); var _stringify = _interopRequireDefault(__nccwpck_require__(18950)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function v4(options, buf, offset) { 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.default)(rnds); } var _default = v4; exports["default"] = _default; /***/ }), /***/ 79120: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _v = _interopRequireDefault(__nccwpck_require__(65998)); var _sha = _interopRequireDefault(__nccwpck_require__(85274)); 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; /***/ }), /***/ 66900: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _regex = _interopRequireDefault(__nccwpck_require__(40814)); 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; /***/ }), /***/ 81595: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _validate = _interopRequireDefault(__nccwpck_require__(66900)); 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.substr(14, 1), 16); } var _default = version; exports["default"] = _default; /***/ }), /***/ 62940: /***/ ((module) => { // Returns a wrapper function that returns a wrapped callback // The wrapper function should do some stuff, and return a // presumably different callback function. // This makes sure that own properties are retained, so that // decorations and such are not lost along the way. module.exports = wrappy function wrappy (fn, cb) { if (fn && cb) return wrappy(fn)(cb) if (typeof fn !== 'function') throw new TypeError('need wrapper function') Object.keys(fn).forEach(function (k) { wrapper[k] = fn[k] }) return wrapper function wrapper() { var args = new Array(arguments.length) for (var i = 0; i < args.length; i++) { args[i] = arguments[i] } var ret = fn.apply(this, args) var cb = args[args.length-1] if (typeof ret === 'function' && ret !== cb) { Object.keys(cb).forEach(function (k) { ret[k] = cb[k] }) } return ret } } /***/ }), /***/ 4091: /***/ ((module) => { "use strict"; module.exports = function (Yallist) { Yallist.prototype[Symbol.iterator] = function* () { for (let walker = this.head; walker; walker = walker.next) { yield walker.value } } } /***/ }), /***/ 40665: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports = Yallist Yallist.Node = Node Yallist.create = Yallist function Yallist (list) { var self = this if (!(self instanceof Yallist)) { self = new Yallist() } self.tail = null self.head = null self.length = 0 if (list && typeof list.forEach === 'function') { list.forEach(function (item) { self.push(item) }) } else if (arguments.length > 0) { for (var i = 0, l = arguments.length; i < l; i++) { self.push(arguments[i]) } } return self } Yallist.prototype.removeNode = function (node) { if (node.list !== this) { throw new Error('removing node which does not belong to this list') } var next = node.next var prev = node.prev if (next) { next.prev = prev } if (prev) { prev.next = next } if (node === this.head) { this.head = next } if (node === this.tail) { this.tail = prev } node.list.length-- node.next = null node.prev = null node.list = null return next } Yallist.prototype.unshiftNode = function (node) { if (node === this.head) { return } if (node.list) { node.list.removeNode(node) } var head = this.head node.list = this node.next = head if (head) { head.prev = node } this.head = node if (!this.tail) { this.tail = node } this.length++ } Yallist.prototype.pushNode = function (node) { if (node === this.tail) { return } if (node.list) { node.list.removeNode(node) } var tail = this.tail node.list = this node.prev = tail if (tail) { tail.next = node } this.tail = node if (!this.head) { this.head = node } this.length++ } Yallist.prototype.push = function () { for (var i = 0, l = arguments.length; i < l; i++) { push(this, arguments[i]) } return this.length } Yallist.prototype.unshift = function () { for (var i = 0, l = arguments.length; i < l; i++) { unshift(this, arguments[i]) } return this.length } Yallist.prototype.pop = function () { if (!this.tail) { return undefined } var res = this.tail.value this.tail = this.tail.prev if (this.tail) { this.tail.next = null } else { this.head = null } this.length-- return res } Yallist.prototype.shift = function () { if (!this.head) { return undefined } var res = this.head.value this.head = this.head.next if (this.head) { this.head.prev = null } else { this.tail = null } this.length-- return res } Yallist.prototype.forEach = function (fn, thisp) { thisp = thisp || this for (var walker = this.head, i = 0; walker !== null; i++) { fn.call(thisp, walker.value, i, this) walker = walker.next } } Yallist.prototype.forEachReverse = function (fn, thisp) { thisp = thisp || this for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { fn.call(thisp, walker.value, i, this) walker = walker.prev } } Yallist.prototype.get = function (n) { for (var i = 0, walker = this.head; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.next } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.getReverse = function (n) { for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.prev } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.map = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.head; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.next } return res } Yallist.prototype.mapReverse = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.tail; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.prev } return res } Yallist.prototype.reduce = function (fn, initial) { var acc var walker = this.head if (arguments.length > 1) { acc = initial } else if (this.head) { walker = this.head.next acc = this.head.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = 0; walker !== null; i++) { acc = fn(acc, walker.value, i) walker = walker.next } return acc } Yallist.prototype.reduceReverse = function (fn, initial) { var acc var walker = this.tail if (arguments.length > 1) { acc = initial } else if (this.tail) { walker = this.tail.prev acc = this.tail.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = this.length - 1; walker !== null; i--) { acc = fn(acc, walker.value, i) walker = walker.prev } return acc } Yallist.prototype.toArray = function () { var arr = new Array(this.length) for (var i = 0, walker = this.head; walker !== null; i++) { arr[i] = walker.value walker = walker.next } return arr } Yallist.prototype.toArrayReverse = function () { var arr = new Array(this.length) for (var i = 0, walker = this.tail; walker !== null; i++) { arr[i] = walker.value walker = walker.prev } return arr } Yallist.prototype.slice = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = 0, walker = this.head; walker !== null && i < from; i++) { walker = walker.next } for (; walker !== null && i < to; i++, walker = walker.next) { ret.push(walker.value) } return ret } Yallist.prototype.sliceReverse = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { walker = walker.prev } for (; walker !== null && i > from; i--, walker = walker.prev) { ret.push(walker.value) } return ret } Yallist.prototype.splice = function (start, deleteCount, ...nodes) { if (start > this.length) { start = this.length - 1 } if (start < 0) { start = this.length + start; } for (var i = 0, walker = this.head; walker !== null && i < start; i++) { walker = walker.next } var ret = [] for (var i = 0; walker && i < deleteCount; i++) { ret.push(walker.value) walker = this.removeNode(walker) } if (walker === null) { walker = this.tail } if (walker !== this.head && walker !== this.tail) { walker = walker.prev } for (var i = 0; i < nodes.length; i++) { walker = insert(this, walker, nodes[i]) } return ret; } Yallist.prototype.reverse = function () { var head = this.head var tail = this.tail for (var walker = head; walker !== null; walker = walker.prev) { var p = walker.prev walker.prev = walker.next walker.next = p } this.head = tail this.tail = head return this } function insert (self, node, value) { var inserted = node === self.head ? new Node(value, null, node, self) : new Node(value, node, node.next, self) if (inserted.next === null) { self.tail = inserted } if (inserted.prev === null) { self.head = inserted } self.length++ return inserted } function push (self, item) { self.tail = new Node(item, self.tail, null, self) if (!self.head) { self.head = self.tail } self.length++ } function unshift (self, item) { self.head = new Node(item, null, self.head, self) if (!self.tail) { self.tail = self.head } self.length++ } function Node (value, prev, next, list) { if (!(this instanceof Node)) { return new Node(value, prev, next, list) } this.list = list this.value = value if (prev) { prev.next = this this.prev = prev } else { this.prev = null } if (next) { next.prev = this this.next = next } else { this.next = null } } try { // add if support for Symbol.iterator is present __nccwpck_require__(4091)(Yallist) } catch (er) {} /***/ }), /***/ 69042: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoFileOptions = exports.Inputs = void 0; /* eslint-disable no-unused-vars */ var Inputs; (function (Inputs) { Inputs["Name"] = "name"; Inputs["Path"] = "path"; Inputs["IfNoFilesFound"] = "if-no-files-found"; Inputs["RetentionDays"] = "retention-days"; Inputs["kmsKeyId"] = "kms-key-id"; })(Inputs = exports.Inputs || (exports.Inputs = {})); var NoFileOptions; (function (NoFileOptions) { /** * Default. Output a warning but do not fail the action */ NoFileOptions["warn"] = "warn"; /** * Fail the action with an error message */ NoFileOptions["error"] = "error"; /** * Do not output any warnings or errors, the action does not fail */ NoFileOptions["ignore"] = "ignore"; })(NoFileOptions = exports.NoFileOptions || (exports.NoFileOptions = {})); /***/ }), /***/ 43594: /***/ (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.encryptFile = void 0; const client_node_1 = __nccwpck_require__(17783); const fs_1 = __nccwpck_require__(57147); function encryptFile(filePath, kmsKeyId) { return __awaiter(this, void 0, void 0, function* () { const keyring = new client_node_1.KmsKeyringNode({ generatorKeyId: kmsKeyId }); const client = (0, client_node_1.buildEncrypt)(client_node_1.CommitmentPolicy.REQUIRE_ENCRYPT_ALLOW_DECRYPT); // Read the file content const fileBuffer = (0, fs_1.readFileSync)(filePath); try { // Encrypt the data const { result } = yield client.encrypt(keyring, fileBuffer); // Overwrite file with encrypted data (0, fs_1.writeFileSync)(filePath, result); console.log('File encrypted successfully'); } catch (error) { console.error('Error encrypting file:', error); throw error; } }); } exports.encryptFile = encryptFile; /***/ }), /***/ 46455: /***/ (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.getInputs = void 0; const core = __importStar(__nccwpck_require__(42186)); const constants_1 = __nccwpck_require__(69042); /** * Helper to get all the inputs for the action */ function getInputs() { const name = core.getInput(constants_1.Inputs.Name); const path = core.getInput(constants_1.Inputs.Path, { required: true }); const kmsKeyId = core.getInput(constants_1.Inputs.kmsKeyId); const ifNoFilesFound = core.getInput(constants_1.Inputs.IfNoFilesFound); const noFileBehavior = constants_1.NoFileOptions[ifNoFilesFound]; if (!noFileBehavior) { core.setFailed(`Unrecognized ${constants_1.Inputs.IfNoFilesFound} input. Provided: ${ifNoFilesFound}. Available options: ${Object.keys(constants_1.NoFileOptions)}`); } const inputs = { artifactName: name, searchPath: path, ifNoFilesFound: noFileBehavior, kmsKeyId }; const retentionDaysStr = core.getInput(constants_1.Inputs.RetentionDays); if (retentionDaysStr) { inputs.retentionDays = parseInt(retentionDaysStr); if (isNaN(inputs.retentionDays)) { core.setFailed('Invalid retention-days'); } } return inputs; } exports.getInputs = getInputs; /***/ }), /***/ 13930: /***/ (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.findFilesToUpload = void 0; const glob = __importStar(__nccwpck_require__(28090)); const path = __importStar(__nccwpck_require__(71017)); const core_1 = __nccwpck_require__(42186); const fs_1 = __nccwpck_require__(57147); const path_1 = __nccwpck_require__(71017); const util_1 = __nccwpck_require__(73837); const stats = (0, util_1.promisify)(fs_1.stat); function getDefaultGlobOptions() { return { followSymbolicLinks: true, implicitDescendants: true, omitBrokenSymbolicLinks: true }; } /** * If multiple paths are specific, the least common ancestor (LCA) of the search paths is used as * the delimiter to control the directory structure for the artifact. This function returns the LCA * when given an array of search paths * * Example 1: The patterns `/foo/` and `/bar/` returns `/` * * Example 2: The patterns `~/foo/bar/*` and `~/foo/voo/two/*` and `~/foo/mo/` returns `~/foo` */ function getMultiPathLCA(searchPaths) { if (searchPaths.length < 2) { throw new Error('At least two search paths must be provided'); } const commonPaths = new Array(); const splitPaths = new Array(); let smallestPathLength = Number.MAX_SAFE_INTEGER; // split each of the search paths using the platform specific separator for (const searchPath of searchPaths) { (0, core_1.debug)(`Using search path ${searchPath}`); const splitSearchPath = path.normalize(searchPath).split(path.sep); // keep track of the smallest path length so that we don't accidentally later go out of bounds smallestPathLength = Math.min(smallestPathLength, splitSearchPath.length); splitPaths.push(splitSearchPath); } // on Unix-like file systems, the file separator exists at the beginning of the file path, make sure to preserve it if (searchPaths[0].startsWith(path.sep)) { commonPaths.push(path.sep); } let splitIndex = 0; // function to check if the paths are the same at a specific index function isPathTheSame() { const compare = splitPaths[0][splitIndex]; for (let i = 1; i < splitPaths.length; i++) { if (compare !== splitPaths[i][splitIndex]) { // a non-common index has been reached return false; } } return true; } // loop over all the search paths until there is a non-common ancestor or we go out of bounds while (splitIndex < smallestPathLength) { if (!isPathTheSame()) { break; } // if all are the same, add to the end result & increment the index commonPaths.push(splitPaths[0][splitIndex]); splitIndex++; } return path.join(...commonPaths); } function findFilesToUpload(searchPath, globOptions) { return __awaiter(this, void 0, void 0, function* () { const searchResults = []; const globber = yield glob.create(searchPath, globOptions || getDefaultGlobOptions()); const rawSearchResults = yield globber.glob(); /* Files are saved with case insensitivity. Uploading both a.txt and A.txt will files to be overwritten Detect any files that could be overwritten for user awareness */ const set = new Set(); /* Directories will be rejected if attempted to be uploaded. This includes just empty directories so filter any directories out from the raw search results */ for (const searchResult of rawSearchResults) { const fileStats = yield stats(searchResult); // isDirectory() returns false for symlinks if using fs.lstat(), make sure to use fs.stat() instead if (!fileStats.isDirectory()) { (0, core_1.debug)(`File:${searchResult} was found using the provided searchPath`); searchResults.push(searchResult); // detect any files that would be overwritten because of case insensitivity if (set.has(searchResult.toLowerCase())) { (0, core_1.info)(`Uploads are case insensitive: ${searchResult} was detected that it will be overwritten by another file with the same path`); } else { set.add(searchResult.toLowerCase()); } } else { (0, core_1.debug)(`Removing ${searchResult} from rawSearchResults because it is a directory`); } } // Calculate the root directory for the artifact using the search paths that were utilized const searchPaths = globber.getSearchPaths(); if (searchPaths.length > 1) { (0, core_1.info)(`Multiple search paths detected. Calculating the least common ancestor of all paths`); const lcaSearchPath = getMultiPathLCA(searchPaths); (0, core_1.info)(`The least common ancestor is ${lcaSearchPath}. This will be the root directory of the artifact`); return { filesToUpload: searchResults, rootDirectory: lcaSearchPath }; } /* Special case for a single file artifact that is uploaded without a directory or wildcard pattern. The directory structure is not preserved and the root directory will be the single files parent directory */ if (searchResults.length === 1 && searchPaths[0] === searchResults[0]) { return { filesToUpload: searchResults, rootDirectory: (0, path_1.dirname)(searchResults[0]) }; } return { filesToUpload: searchResults, rootDirectory: searchPaths[0] }; }); } exports.findFilesToUpload = findFilesToUpload; /***/ }), /***/ 10334: /***/ (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 })); const core = __importStar(__nccwpck_require__(42186)); const artifact_1 = __nccwpck_require__(52605); const constants_1 = __nccwpck_require__(69042); const encrypt_1 = __nccwpck_require__(43594); const search_1 = __nccwpck_require__(13930); const input_helper_1 = __nccwpck_require__(46455); function run() { return __awaiter(this, void 0, void 0, function* () { try { const inputs = (0, input_helper_1.getInputs)(); const searchResult = yield (0, search_1.findFilesToUpload)(inputs.searchPath); if (searchResult.filesToUpload.length === 0) { // No files were found, different use cases warrant different types of behavior if nothing is found switch (inputs.ifNoFilesFound) { case constants_1.NoFileOptions.warn: { core.warning(`No files were found with the provided path: ${inputs.searchPath}. No artifacts will be uploaded.`); break; } case constants_1.NoFileOptions.error: { core.setFailed(`No files were found with the provided path: ${inputs.searchPath}. No artifacts will be uploaded.`); break; } case constants_1.NoFileOptions.ignore: { core.info(`No files were found with the provided path: ${inputs.searchPath}. No artifacts will be uploaded.`); break; } } } else { const s = searchResult.filesToUpload.length === 1 ? '' : 's'; core.info(`With the provided path, there will be ${searchResult.filesToUpload.length} file${s} uploaded`); core.debug(`Root artifact directory is ${searchResult.rootDirectory}`); if (searchResult.filesToUpload.length > 10000) { core.warning(`There are over 10,000 files in this artifact, consider creating an archive before upload to improve the upload performance.`); } for (const file of searchResult.filesToUpload) { yield (0, encrypt_1.encryptFile)(file, inputs.kmsKeyId); } const artifactClient = (0, artifact_1.create)(); const options = { continueOnError: false }; if (inputs.retentionDays) { options.retentionDays = inputs.retentionDays; } const uploadResponse = yield artifactClient.uploadArtifact(inputs.artifactName, searchResult.filesToUpload, searchResult.rootDirectory, options); if (uploadResponse.failedItems.length > 0) { core.setFailed(`An error was encountered when uploading ${uploadResponse.artifactName}. There were ${uploadResponse.failedItems.length} items that failed to upload.`); } else { core.info(`Artifact ${uploadResponse.artifactName} has been successfully uploaded!`); } } } catch (error) { core.setFailed(error.message); } }); } run(); /***/ }), /***/ 39491: /***/ ((module) => { "use strict"; module.exports = require("assert"); /***/ }), /***/ 14300: /***/ ((module) => { "use strict"; module.exports = require("buffer"); /***/ }), /***/ 32081: /***/ ((module) => { "use strict"; module.exports = require("child_process"); /***/ }), /***/ 6113: /***/ ((module) => { "use strict"; module.exports = require("crypto"); /***/ }), /***/ 82361: /***/ ((module) => { "use strict"; module.exports = require("events"); /***/ }), /***/ 57147: /***/ ((module) => { "use strict"; module.exports = require("fs"); /***/ }), /***/ 13685: /***/ ((module) => { "use strict"; module.exports = require("http"); /***/ }), /***/ 85158: /***/ ((module) => { "use strict"; module.exports = require("http2"); /***/ }), /***/ 95687: /***/ ((module) => { "use strict"; module.exports = require("https"); /***/ }), /***/ 41808: /***/ ((module) => { "use strict"; module.exports = require("net"); /***/ }), /***/ 22037: /***/ ((module) => { "use strict"; module.exports = require("os"); /***/ }), /***/ 71017: /***/ ((module) => { "use strict"; module.exports = require("path"); /***/ }), /***/ 4074: /***/ ((module) => { "use strict"; module.exports = require("perf_hooks"); /***/ }), /***/ 77282: /***/ ((module) => { "use strict"; module.exports = require("process"); /***/ }), /***/ 12781: /***/ ((module) => { "use strict"; module.exports = require("stream"); /***/ }), /***/ 24404: /***/ ((module) => { "use strict"; module.exports = require("tls"); /***/ }), /***/ 57310: /***/ ((module) => { "use strict"; module.exports = require("url"); /***/ }), /***/ 73837: /***/ ((module) => { "use strict"; module.exports = require("util"); /***/ }), /***/ 59796: /***/ ((module) => { "use strict"; module.exports = require("zlib"); /***/ }), /***/ 19842: /***/ ((module) => { "use strict"; module.exports = JSON.parse('{"name":"@aws-sdk/client-kms","description":"AWS SDK for JavaScript Kms Client for Node.js, Browser and React Native","version":"3.460.0","scripts":{"build":"concurrently \'yarn:build:cjs\' \'yarn:build:es\' \'yarn:build:types\'","build:cjs":"tsc -p tsconfig.cjs.json","build:docs":"typedoc","build:es":"tsc -p tsconfig.es.json","build:include:deps":"lerna run --scope $npm_package_name --include-dependencies build","build:types":"tsc -p tsconfig.types.json","build:types:downlevel":"downlevel-dts dist-types dist-types/ts3.4","clean":"rimraf ./dist-* && rimraf *.tsbuildinfo","extract:docs":"api-extractor run --local","generate:client":"node ../../scripts/generate-clients/single-service --solo kms"},"main":"./dist-cjs/index.js","types":"./dist-types/index.d.ts","module":"./dist-es/index.js","sideEffects":false,"dependencies":{"@aws-crypto/sha256-browser":"3.0.0","@aws-crypto/sha256-js":"3.0.0","@aws-sdk/client-sts":"3.460.0","@aws-sdk/core":"3.451.0","@aws-sdk/credential-provider-node":"3.460.0","@aws-sdk/middleware-host-header":"3.460.0","@aws-sdk/middleware-logger":"3.460.0","@aws-sdk/middleware-recursion-detection":"3.460.0","@aws-sdk/middleware-signing":"3.460.0","@aws-sdk/middleware-user-agent":"3.460.0","@aws-sdk/region-config-resolver":"3.451.0","@aws-sdk/types":"3.460.0","@aws-sdk/util-endpoints":"3.460.0","@aws-sdk/util-user-agent-browser":"3.460.0","@aws-sdk/util-user-agent-node":"3.460.0","@smithy/config-resolver":"^2.0.18","@smithy/fetch-http-handler":"^2.2.6","@smithy/hash-node":"^2.0.15","@smithy/invalid-dependency":"^2.0.13","@smithy/middleware-content-length":"^2.0.15","@smithy/middleware-endpoint":"^2.2.0","@smithy/middleware-retry":"^2.0.20","@smithy/middleware-serde":"^2.0.13","@smithy/middleware-stack":"^2.0.7","@smithy/node-config-provider":"^2.1.5","@smithy/node-http-handler":"^2.1.9","@smithy/protocol-http":"^3.0.9","@smithy/smithy-client":"^2.1.15","@smithy/types":"^2.5.0","@smithy/url-parser":"^2.0.13","@smithy/util-base64":"^2.0.1","@smithy/util-body-length-browser":"^2.0.0","@smithy/util-body-length-node":"^2.1.0","@smithy/util-defaults-mode-browser":"^2.0.19","@smithy/util-defaults-mode-node":"^2.0.25","@smithy/util-endpoints":"^1.0.4","@smithy/util-retry":"^2.0.6","@smithy/util-utf8":"^2.0.2","tslib":"^2.5.0"},"devDependencies":{"@smithy/service-client-documentation-generator":"^2.0.0","@tsconfig/node14":"1.0.3","@types/node":"^14.14.31","concurrently":"7.0.0","downlevel-dts":"0.10.1","rimraf":"3.0.2","typedoc":"0.23.23","typescript":"~4.9.5"},"engines":{"node":">=14.0.0"},"typesVersions":{"<4.0":{"dist-types/*":["dist-types/ts3.4/*"]}},"files":["dist-*/**"],"author":{"name":"AWS SDK for JavaScript Team","url":"https://aws.amazon.com/javascript/"},"license":"Apache-2.0","browser":{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.browser"},"react-native":{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.native"},"homepage":"https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-kms","repository":{"type":"git","url":"https://github.com/aws/aws-sdk-js-v3.git","directory":"clients/client-kms"}}'); /***/ }), /***/ 91092: /***/ ((module) => { "use strict"; module.exports = JSON.parse('{"name":"@aws-sdk/client-sso","description":"AWS SDK for JavaScript Sso Client for Node.js, Browser and React Native","version":"3.460.0","scripts":{"build":"concurrently \'yarn:build:cjs\' \'yarn:build:es\' \'yarn:build:types\'","build:cjs":"tsc -p tsconfig.cjs.json","build:docs":"typedoc","build:es":"tsc -p tsconfig.es.json","build:include:deps":"lerna run --scope $npm_package_name --include-dependencies build","build:types":"tsc -p tsconfig.types.json","build:types:downlevel":"downlevel-dts dist-types dist-types/ts3.4","clean":"rimraf ./dist-* && rimraf *.tsbuildinfo","extract:docs":"api-extractor run --local","generate:client":"node ../../scripts/generate-clients/single-service --solo sso"},"main":"./dist-cjs/index.js","types":"./dist-types/index.d.ts","module":"./dist-es/index.js","sideEffects":false,"dependencies":{"@aws-crypto/sha256-browser":"3.0.0","@aws-crypto/sha256-js":"3.0.0","@aws-sdk/core":"3.451.0","@aws-sdk/middleware-host-header":"3.460.0","@aws-sdk/middleware-logger":"3.460.0","@aws-sdk/middleware-recursion-detection":"3.460.0","@aws-sdk/middleware-user-agent":"3.460.0","@aws-sdk/region-config-resolver":"3.451.0","@aws-sdk/types":"3.460.0","@aws-sdk/util-endpoints":"3.460.0","@aws-sdk/util-user-agent-browser":"3.460.0","@aws-sdk/util-user-agent-node":"3.460.0","@smithy/config-resolver":"^2.0.18","@smithy/fetch-http-handler":"^2.2.6","@smithy/hash-node":"^2.0.15","@smithy/invalid-dependency":"^2.0.13","@smithy/middleware-content-length":"^2.0.15","@smithy/middleware-endpoint":"^2.2.0","@smithy/middleware-retry":"^2.0.20","@smithy/middleware-serde":"^2.0.13","@smithy/middleware-stack":"^2.0.7","@smithy/node-config-provider":"^2.1.5","@smithy/node-http-handler":"^2.1.9","@smithy/protocol-http":"^3.0.9","@smithy/smithy-client":"^2.1.15","@smithy/types":"^2.5.0","@smithy/url-parser":"^2.0.13","@smithy/util-base64":"^2.0.1","@smithy/util-body-length-browser":"^2.0.0","@smithy/util-body-length-node":"^2.1.0","@smithy/util-defaults-mode-browser":"^2.0.19","@smithy/util-defaults-mode-node":"^2.0.25","@smithy/util-endpoints":"^1.0.4","@smithy/util-retry":"^2.0.6","@smithy/util-utf8":"^2.0.2","tslib":"^2.5.0"},"devDependencies":{"@smithy/service-client-documentation-generator":"^2.0.0","@tsconfig/node14":"1.0.3","@types/node":"^14.14.31","concurrently":"7.0.0","downlevel-dts":"0.10.1","rimraf":"3.0.2","typedoc":"0.23.23","typescript":"~4.9.5"},"engines":{"node":">=14.0.0"},"typesVersions":{"<4.0":{"dist-types/*":["dist-types/ts3.4/*"]}},"files":["dist-*/**"],"author":{"name":"AWS SDK for JavaScript Team","url":"https://aws.amazon.com/javascript/"},"license":"Apache-2.0","browser":{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.browser"},"react-native":{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.native"},"homepage":"https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-sso","repository":{"type":"git","url":"https://github.com/aws/aws-sdk-js-v3.git","directory":"clients/client-sso"}}'); /***/ }), /***/ 7947: /***/ ((module) => { "use strict"; module.exports = JSON.parse('{"name":"@aws-sdk/client-sts","description":"AWS SDK for JavaScript Sts Client for Node.js, Browser and React Native","version":"3.460.0","scripts":{"build":"concurrently \'yarn:build:cjs\' \'yarn:build:es\' \'yarn:build:types\'","build:cjs":"tsc -p tsconfig.cjs.json","build:docs":"typedoc","build:es":"tsc -p tsconfig.es.json","build:include:deps":"lerna run --scope $npm_package_name --include-dependencies build","build:types":"tsc -p tsconfig.types.json","build:types:downlevel":"downlevel-dts dist-types dist-types/ts3.4","clean":"rimraf ./dist-* && rimraf *.tsbuildinfo","extract:docs":"api-extractor run --local","generate:client":"node ../../scripts/generate-clients/single-service --solo sts","test":"yarn test:unit","test:unit":"jest"},"main":"./dist-cjs/index.js","types":"./dist-types/index.d.ts","module":"./dist-es/index.js","sideEffects":false,"dependencies":{"@aws-crypto/sha256-browser":"3.0.0","@aws-crypto/sha256-js":"3.0.0","@aws-sdk/core":"3.451.0","@aws-sdk/credential-provider-node":"3.460.0","@aws-sdk/middleware-host-header":"3.460.0","@aws-sdk/middleware-logger":"3.460.0","@aws-sdk/middleware-recursion-detection":"3.460.0","@aws-sdk/middleware-sdk-sts":"3.460.0","@aws-sdk/middleware-signing":"3.460.0","@aws-sdk/middleware-user-agent":"3.460.0","@aws-sdk/region-config-resolver":"3.451.0","@aws-sdk/types":"3.460.0","@aws-sdk/util-endpoints":"3.460.0","@aws-sdk/util-user-agent-browser":"3.460.0","@aws-sdk/util-user-agent-node":"3.460.0","@smithy/config-resolver":"^2.0.18","@smithy/fetch-http-handler":"^2.2.6","@smithy/hash-node":"^2.0.15","@smithy/invalid-dependency":"^2.0.13","@smithy/middleware-content-length":"^2.0.15","@smithy/middleware-endpoint":"^2.2.0","@smithy/middleware-retry":"^2.0.20","@smithy/middleware-serde":"^2.0.13","@smithy/middleware-stack":"^2.0.7","@smithy/node-config-provider":"^2.1.5","@smithy/node-http-handler":"^2.1.9","@smithy/protocol-http":"^3.0.9","@smithy/smithy-client":"^2.1.15","@smithy/types":"^2.5.0","@smithy/url-parser":"^2.0.13","@smithy/util-base64":"^2.0.1","@smithy/util-body-length-browser":"^2.0.0","@smithy/util-body-length-node":"^2.1.0","@smithy/util-defaults-mode-browser":"^2.0.19","@smithy/util-defaults-mode-node":"^2.0.25","@smithy/util-endpoints":"^1.0.4","@smithy/util-retry":"^2.0.6","@smithy/util-utf8":"^2.0.2","fast-xml-parser":"4.2.5","tslib":"^2.5.0"},"devDependencies":{"@smithy/service-client-documentation-generator":"^2.0.0","@tsconfig/node14":"1.0.3","@types/node":"^14.14.31","concurrently":"7.0.0","downlevel-dts":"0.10.1","rimraf":"3.0.2","typedoc":"0.23.23","typescript":"~4.9.5"},"engines":{"node":">=14.0.0"},"typesVersions":{"<4.0":{"dist-types/*":["dist-types/ts3.4/*"]}},"files":["dist-*/**"],"author":{"name":"AWS SDK for JavaScript Team","url":"https://aws.amazon.com/javascript/"},"license":"Apache-2.0","browser":{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.browser"},"react-native":{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.native"},"homepage":"https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-sts","repository":{"type":"git","url":"https://github.com/aws/aws-sdk-js-v3.git","directory":"clients/client-sts"}}'); /***/ }), /***/ 95367: /***/ ((module) => { "use strict"; module.exports = JSON.parse('{"partitions":[{"id":"aws","outputs":{"dnsSuffix":"amazonaws.com","dualStackDnsSuffix":"api.aws","implicitGlobalRegion":"us-east-1","name":"aws","supportsDualStack":true,"supportsFIPS":true},"regionRegex":"^(us|eu|ap|sa|ca|me|af|il)\\\\-\\\\w+\\\\-\\\\d+$","regions":{"af-south-1":{"description":"Africa (Cape Town)"},"ap-east-1":{"description":"Asia Pacific (Hong Kong)"},"ap-northeast-1":{"description":"Asia Pacific (Tokyo)"},"ap-northeast-2":{"description":"Asia Pacific (Seoul)"},"ap-northeast-3":{"description":"Asia Pacific (Osaka)"},"ap-south-1":{"description":"Asia Pacific (Mumbai)"},"ap-south-2":{"description":"Asia Pacific (Hyderabad)"},"ap-southeast-1":{"description":"Asia Pacific (Singapore)"},"ap-southeast-2":{"description":"Asia Pacific (Sydney)"},"ap-southeast-3":{"description":"Asia Pacific (Jakarta)"},"ap-southeast-4":{"description":"Asia Pacific (Melbourne)"},"aws-global":{"description":"AWS Standard global region"},"ca-central-1":{"description":"Canada (Central)"},"eu-central-1":{"description":"Europe (Frankfurt)"},"eu-central-2":{"description":"Europe (Zurich)"},"eu-north-1":{"description":"Europe (Stockholm)"},"eu-south-1":{"description":"Europe (Milan)"},"eu-south-2":{"description":"Europe (Spain)"},"eu-west-1":{"description":"Europe (Ireland)"},"eu-west-2":{"description":"Europe (London)"},"eu-west-3":{"description":"Europe (Paris)"},"il-central-1":{"description":"Israel (Tel Aviv)"},"me-central-1":{"description":"Middle East (UAE)"},"me-south-1":{"description":"Middle East (Bahrain)"},"sa-east-1":{"description":"South America (Sao Paulo)"},"us-east-1":{"description":"US East (N. Virginia)"},"us-east-2":{"description":"US East (Ohio)"},"us-west-1":{"description":"US West (N. California)"},"us-west-2":{"description":"US West (Oregon)"}}},{"id":"aws-cn","outputs":{"dnsSuffix":"amazonaws.com.cn","dualStackDnsSuffix":"api.amazonwebservices.com.cn","implicitGlobalRegion":"cn-northwest-1","name":"aws-cn","supportsDualStack":true,"supportsFIPS":true},"regionRegex":"^cn\\\\-\\\\w+\\\\-\\\\d+$","regions":{"aws-cn-global":{"description":"AWS China global region"},"cn-north-1":{"description":"China (Beijing)"},"cn-northwest-1":{"description":"China (Ningxia)"}}},{"id":"aws-us-gov","outputs":{"dnsSuffix":"amazonaws.com","dualStackDnsSuffix":"api.aws","implicitGlobalRegion":"us-gov-west-1","name":"aws-us-gov","supportsDualStack":true,"supportsFIPS":true},"regionRegex":"^us\\\\-gov\\\\-\\\\w+\\\\-\\\\d+$","regions":{"aws-us-gov-global":{"description":"AWS GovCloud (US) global region"},"us-gov-east-1":{"description":"AWS GovCloud (US-East)"},"us-gov-west-1":{"description":"AWS GovCloud (US-West)"}}},{"id":"aws-iso","outputs":{"dnsSuffix":"c2s.ic.gov","dualStackDnsSuffix":"c2s.ic.gov","implicitGlobalRegion":"us-iso-east-1","name":"aws-iso","supportsDualStack":false,"supportsFIPS":true},"regionRegex":"^us\\\\-iso\\\\-\\\\w+\\\\-\\\\d+$","regions":{"aws-iso-global":{"description":"AWS ISO (US) global region"},"us-iso-east-1":{"description":"US ISO East"},"us-iso-west-1":{"description":"US ISO WEST"}}},{"id":"aws-iso-b","outputs":{"dnsSuffix":"sc2s.sgov.gov","dualStackDnsSuffix":"sc2s.sgov.gov","implicitGlobalRegion":"us-isob-east-1","name":"aws-iso-b","supportsDualStack":false,"supportsFIPS":true},"regionRegex":"^us\\\\-isob\\\\-\\\\w+\\\\-\\\\d+$","regions":{"aws-iso-b-global":{"description":"AWS ISOB (US) global region"},"us-isob-east-1":{"description":"US ISOB East (Ohio)"}}},{"id":"aws-iso-e","outputs":{"dnsSuffix":"cloud.adc-e.uk","dualStackDnsSuffix":"cloud.adc-e.uk","implicitGlobalRegion":"eu-isoe-west-1","name":"aws-iso-e","supportsDualStack":false,"supportsFIPS":true},"regionRegex":"^eu\\\\-isoe\\\\-\\\\w+\\\\-\\\\d+$","regions":{}},{"id":"aws-iso-f","outputs":{"dnsSuffix":"csp.hci.ic.gov","dualStackDnsSuffix":"csp.hci.ic.gov","implicitGlobalRegion":"us-isof-south-1","name":"aws-iso-f","supportsDualStack":false,"supportsFIPS":true},"regionRegex":"^us\\\\-isof\\\\-\\\\w+\\\\-\\\\d+$","regions":{}}],"version":"1.1"}'); /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __nccwpck_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ id: moduleId, /******/ loaded: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ var threw = true; /******/ try { /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nccwpck_require__); /******/ threw = false; /******/ } finally { /******/ if(threw) delete __webpack_module_cache__[moduleId]; /******/ } /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ /******/ /* webpack/runtime/node module decorator */ /******/ (() => { /******/ __nccwpck_require__.nmd = (module) => { /******/ module.paths = []; /******/ if (!module.children) module.children = []; /******/ return module; /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/compat */ /******/ /******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/"; /******/ /************************************************************************/ /******/ /******/ // startup /******/ // Load entry module and return exports /******/ // This entry module is referenced by other modules so it can't be inlined /******/ var __webpack_exports__ = __nccwpck_require__(10334); /******/ module.exports = __webpack_exports__; /******/ /******/ })() ;